├── .github └── .workflows │ └── publish_action.yml ├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── nnt_data.py ├── nnt_layers.py ├── nnt_models.py ├── nnt_tensors.py ├── nnt_transformers.py ├── pyproject.toml ├── requirements.txt └── workflows ├── NNT_conv_CIFAR10.json ├── NNT_conv_CIFAR10.png ├── NNT_conv_MNIST.json ├── NNT_conv_MNIST.png ├── NNT_linear_regression.json ├── NNT_linear_regression.png ├── NNT_load_infer_MNIST.json ├── NNT_load_infer_MNIST.png ├── rnn-FashionMNIST-autoencoder.json ├── rnn-FashionMNIST-autoencoder.png └── sample_data ├── MNIST_four.png ├── MNIST_nine.png ├── MNIST_one.png ├── hoodie.jpg └── large_nine.png /.github/.workflows/publish_action.yml: -------------------------------------------------------------------------------- 1 | name: Publish to Comfy registry 2 | on: 3 | workflow_dispatch: 4 | push: 5 | branches: 6 | - main 7 | paths: 8 | - "pyproject.toml" 9 | 10 | jobs: 11 | publish-node: 12 | name: Publish Custom Node to registry 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Check out code 16 | uses: actions/checkout@v4 17 | - name: Publish Custom Node 18 | uses: Comfy-Org/publish-node-action@main 19 | with: 20 | personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }} ## Add your own personal access token to your Github Repository secrets and reference it here. -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | "__pycache__/" "*.pyc" ".DS_Store" 2 | "__pycache__/" "*.pyc" ".DS_Store" 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Neural Network Toolkit (NNT) for ComfyUI 2 | 3 | The **Neural Network Toolkit (NNT)** is an extensive set of custom ComfyUI nodes for designing, training, and fine-tuning neural networks. This toolkit allows defining models, layers, training workflows, transformers, and tensor operations in a visual manner using nodes. 4 | 5 | This toolkit is especially useful in educational environments for learning and explaining neural network principles and architecture without code. Even people with no programming experience can use it to experiment with neural networks. I created this project as a practical learning tool while studying neural networks. 6 | 7 | NNT allows you to quickly create and train various models, experiment with their structure, and observe the effect of changing their parameters. While it's a powerful learning and prototyping tool, please note it's a work in progress and not meant to replace PyTorch coding for production environments. 8 | 9 | ## License 10 | 11 | This project is licensed under the GNU General Public License v3.0 - see [LICENSE](LICENSE) for details. 12 | 13 | ## Key Features 14 | 15 | - Visual node-based neural network design 16 | - Support for various layer types (Dense, Conv, RNN, Transformer) 17 | - Interactive training and fine-tuning capabilities 18 | - Real-time visualization of model architecture and training metrics 19 | - Tensor manipulation and analysis tools 20 | - Educational focus with immediate visual feedback 21 | - No coding required for basic operations 22 | 23 | ## Installation 24 | 25 | ### Prerequisites 26 | 27 | - ComfyUI installed and working 28 | - Python 3.8+ 29 | - CUDA-compatible GPU (recommended) 30 | - PyTorch 2.0+ 31 | - Basic understanding of neural networks 32 | 33 | Installation can be done via ConfyUI Manager or manualy 34 | 35 | ```bash 36 | cd ComfyUI/custom_nodes 37 | git clone https://github.com/inventorado/ComfyUI_NNT.git 38 | cd ComfyUI_NNT 39 | pip install -r requirements.txt 40 | ``` 41 | On standalone version you can install requirements for embeded python using 42 | 43 | ```bash 44 | cd ComfyUI_NNT 45 | ..\..\..\python_embeded\python.exe -m pip install -r requirements.txt 46 | ``` 47 | 48 | ## Example Workflows 49 | 50 | Example workflows can be found in workflows directory under this custom node. They use ComfyUI-Jjk-Nodes for displaying text, you can install this by ConfyUI Manager - Install Missing Custom Nodes. 51 | 52 | ### Linear Regression Example 53 |

54 | Linear Regression Workflow 55 |

56 | 57 | A simple linear regression model demonstrating basic neural network construction and training. Shows how to create input layers, add linear layers, compile the model, and visualize training results. 58 | 59 | ### CIFAR10 Convolutional Network 60 |

61 | CIFAR10 CNN Workflow 62 |

63 | 64 | Advanced convolutional neural network for CIFAR10 image classification. Features data loading, model construction with conv layers, batch normalization, and pooling, followed by training and evaluation. 65 | 66 | ### MNIST Digit Recognition 67 |

68 | MNIST CNN Workflow 69 |

70 | 71 | Classic MNIST handwritten digit classification using convolutional neural network. Demonstrates proper model architecture for digit recognition with convolutional layers, pooling, and dense layers. 72 | 73 | ### MNIST Model Loading and Inference 74 |

75 | MNIST Inference Workflow 76 |

77 | 78 | Example of loading a pre-trained MNIST model and performing inference. Shows how to load model weights, process input data, and visualize prediction results. 79 | 80 | ### Fashion-MNIST Autoencoder with RNN 81 |

82 | Fashion-MNIST RNN Autoencoder 83 |

84 | 85 | Recurrent neural network (RNN) based autoencoder for Fashion-MNIST dataset. Demonstrates sequence processing capabilities with RNN layers for image reconstruction tasks. 86 | 87 | ## Node List and Descriptions 88 | 89 | ### Models 90 | 91 | #### **NntCompileModel** 92 | 93 | Compiles a neural network model from a layer stack. 94 | 95 | - **Inputs**: Layer stack, activation function, normalization, weight initialization. 96 | - **Options**: Compile mode, activation parameters. 97 | - **Outputs**: Compiled model, report, script. 98 | 99 | #### **NntTrainModel** 100 | 101 | Trains a model using provided training data. 102 | 103 | - **Inputs**: Model, training data, target data, hyperparameters. 104 | - **Options**: Batch size, epochs, loss function, optimizer. 105 | - **Outputs**: Trained model, training log, metrics. 106 | 107 | #### **NntFineTuneModel** 108 | 109 | Fine-tunes an existing model on new datasets. 110 | 111 | - **Inputs**: Model, training/validation data, learning rate, batch size. 112 | - **Options**: Scheduler settings, early stopping. 113 | - **Outputs**: Fine-tuned model, training summary. 114 | 115 | #### **NntSaveModel** 116 | 117 | Saves the model in various formats. 118 | 119 | - **Inputs**: Model, filename, directory. 120 | - **Options**: Save format, quantization type, optimizer inclusion. 121 | - **Outputs**: Model, save report. 122 | 123 | #### **NntLoadModel** 124 | 125 | Loads a model from a specified file. 126 | 127 | - **Inputs**: File path, load format. 128 | - **Options**: Device selection. 129 | - **Outputs**: Loaded model. 130 | 131 | #### **NntAnalyzeModel** 132 | 133 | Analyzes model layers, memory usage, and complexity. 134 | 135 | - **Inputs**: Model, input shape, batch size. 136 | - **Outputs**: Analysis report. 137 | 138 | #### **NntVisualizeGraph** 139 | 140 | Visualizes the computation graph of the model. 141 | 142 | - **Inputs**: Model. 143 | - **Outputs**: Graph visualization image. 144 | 145 | #### **NntEditModelLayers** 146 | 147 | Edits layers in an existing model. 148 | 149 | - **Inputs**: Model, layer editing instructions. 150 | - **Options**: Freeze/unfreeze layers, apply quantization, or modify weights. 151 | - **Outputs**: Edited model, operation summary. 152 | 153 | #### **NntMergeExtendModel** 154 | 155 | Merges or extends models with new layers. 156 | 157 | - **Inputs**: Two models or one model with a layer stack. 158 | - **Options**: Merge strategies, additional layer configurations. 159 | - **Outputs**: Merged/extended model, merge summary. 160 | * * * 161 | 162 | ### Layers 163 | 164 | #### **NntInputLayer** 165 | 166 | Defines the input layer for the model. 167 | 168 | - **Inputs**: Input shape as a list. 169 | - **Outputs**: Layer stack. 170 | 171 | #### **NntDefineDenseLayer** 172 | 173 | Defines a fully connected (dense) layer. 174 | 175 | - **Inputs**: Number of nodes, activation function, weight initialization. 176 | - **Options**: Bias settings, normalization, dropout rate. 177 | - **Outputs**: Layer stack, number of nodes. 178 | 179 | #### **NntDefineConvLayer** 180 | 181 | Defines convolutional layers with extensive configurations. 182 | 183 | - **Inputs**: Kernel size, stride, padding, dilation, channels. 184 | - **Options**: Weight initialization, normalization, dropout rate. 185 | - **Outputs**: Layer stack. 186 | 187 | #### **NntDefinePoolingLayer** 188 | 189 | Configures pooling layers (max, average, or adaptive). 190 | 191 | - **Inputs**: Pooling type, kernel size, stride. 192 | - **Options**: Padding, advanced settings for fractional or LPPool. 193 | - **Outputs**: Layer stack. 194 | 195 | #### **NntDefineRNNLayer** 196 | 197 | Defines recurrent layers like RNNs, LSTMs, and GRUs. 198 | 199 | - **Inputs**: Input size, hidden size, number of layers. 200 | - **Options**: Nonlinearity (tanh/relu), dropout, bidirectional settings. 201 | - **Outputs**: Layer stack. 202 | 203 | #### **NntDefineFlattenLayer** 204 | 205 | Flattens input tensors for fully connected layers. 206 | 207 | - **Inputs**: None. 208 | - **Outputs**: Layer stack. 209 | 210 | #### **NntDefineNormLayer** 211 | 212 | Adds normalization layers (batch, layer, instance). 213 | 214 | - **Inputs**: Type of normalization, number of features. 215 | - **Options**: Momentum, epsilon, affine parameters. 216 | - **Outputs**: Layer stack. 217 | 218 | #### **NntDefineActivationLayer** 219 | 220 | Configures activation functions for layers. 221 | 222 | - **Inputs**: Activation type (ReLU, Sigmoid, Tanh, etc.). 223 | - **Options**: In-place operations, additional parameters for specific activations. 224 | - **Outputs**: Layer stack. 225 | * * * 226 | 227 | ### Transformers 228 | 229 | #### **NntDefineTransformerEncoderLayer** 230 | 231 | Defines a transformer encoder layer. 232 | 233 | - **Inputs**: Model dimensions, number of heads, feedforward size. 234 | - **Options**: Batch-first processing, dropout, activation function. 235 | - **Outputs**: Layer stack. 236 | 237 | #### **NntDefineMultiheadAttention** 238 | 239 | Defines multi-head attention layers. 240 | 241 | - **Inputs**: Embedding dimension, number of heads, dropout. 242 | - **Options**: Add bias, batch-first processing. 243 | - **Outputs**: Layer stack. 244 | 245 | #### **NntDefineVanillaAttention** 246 | 247 | Implements basic attention mechanisms. 248 | 249 | - **Inputs**: Embedding dimension, attention type, dropout. 250 | - **Options**: Batch processing, zero attention. 251 | - **Outputs**: Layer stack. 252 | 253 | #### **NntDefineLinearAttention** 254 | 255 | Implements linear attention for efficient computation. 256 | 257 | - **Inputs**: Embedding dimension, feature map, dropout. 258 | - **Options**: Causality, epsilon for numerical stability. 259 | - **Outputs**: Layer stack. 260 | 261 | #### **NntDefineReformerAttention** 262 | 263 | Adds Reformer-style attention. 264 | 265 | - **Inputs**: Bucketing configuration, dropout, number of heads. 266 | - **Options**: Causality, hashing parameters. 267 | - **Outputs**: Layer stack. 268 | 269 | #### **NntDefinePositionalEncoding** 270 | 271 | Defines positional encodings for sequence data. 272 | 273 | - **Inputs**: Encoding type, sequence length, dropout. 274 | - **Options**: Normalize, learnable parameters. 275 | - **Outputs**: Layer stack. 276 | * * * 277 | 278 | ### Tensors 279 | 280 | #### **NntTensorToText** 281 | 282 | Converts tensors to human-readable text. 283 | 284 | - **Inputs**: Tensor, format options, precision. 285 | - **Options**: Max elements for output. 286 | - **Outputs**: Text representation. 287 | 288 | #### **NntTextToTensor** 289 | 290 | Parses text into a PyTorch tensor. 291 | 292 | - **Inputs**: Text data, data type, device. 293 | - **Options**: Gradient requirements. 294 | - **Outputs**: Tensor. 295 | 296 | #### **NntRandomTensorGenerator** 297 | 298 | Generates random tensors based on various distributions. 299 | 300 | - **Inputs**: Distribution type, shape, data type. 301 | - **Options**: Seed, min/max range for values. 302 | - **Outputs**: Tensor, generation summary. 303 | 304 | #### **NntTensorElementToImage** 305 | 306 | Converts tensor elements to images. 307 | 308 | - **Inputs**: Tensor, image dimensions, channels. 309 | - **Options**: Clamp range, reshape options. 310 | - **Outputs**: Image tensor. 311 | 312 | #### **NntDataLoader** 313 | 314 | Loads datasets in various formats (text, images, paired data). 315 | 316 | - **Inputs**: Data source, file path, data type. 317 | - **Options**: Normalization, batch-first processing. 318 | - **Outputs**: Tensors, paired data (optional), info message. 319 | * * * 320 | 321 | ### Visualization 322 | 323 | #### **NntVisualizeTrainingMetrics** 324 | 325 | Plots training metrics over time (loss, accuracy). 326 | 327 | - **Inputs**: Metrics data. 328 | - **Options**: Plot dimensions, smoothing factors. 329 | - **Outputs**: Visualization image. 330 | 331 | #### **NntSHAPSummaryNode** 332 | 333 | Generates SHAP explanations for model predictions. 334 | 335 | - **Inputs**: Model, sample data, plot type. 336 | - **Options**: Background sample size. 337 | - **Outputs**: SHAP summary report, visualization plot. 338 | 339 | #### **NntVisualizePredictions** 340 | 341 | Visualizes predictions with confusion matrices and error analysis. 342 | 343 | - **Inputs**: Model, input data, target data. 344 | - **Options**: Classification or regression task type. 345 | - **Outputs**: Report, main plot, loss/error plot, metrics. 346 | * * * 347 | 348 | ## Getting Started 349 | 350 | ### Step 1: Build Layers 351 | 352 | Use layer nodes (e.g., `NntDefineDenseLayer`) to define the architecture of your network. 353 | 354 | ### Step 2: Compile Model 355 | 356 | Pass the layer stack to `NntCompileModel` to create a trainable model. 357 | 358 | ### Step 3: Train Model 359 | 360 | Use `NntTrainModel` with training and target data to train your model. 361 | 362 | ### Step 4: Visualize Results 363 | 364 | Analyze performance using visualization nodes (e.g., `NntVisualizeTrainingMetrics`). 365 | 366 | * * * 367 | 368 | ## Contributing 369 | 370 | We welcome contributions! Submit issues, feature requests, or pull requests to enhance the toolkit. -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | from .nnt_models import ( 2 | 3 | NntCompileModel, 4 | NntShowModelInfo, 5 | NntSaveModel, 6 | NntLoadModel, 7 | NntAnalyzeModel, 8 | NntTrainModel, 9 | NntEvaluatePredictions, 10 | NntVisualizePredictionMetrics, 11 | NntFineTuneModel, 12 | NntEditModelLayers, 13 | NntMergeExtendModel, 14 | NntVisualizeGraph, 15 | NntSHAPSummaryNode, 16 | NntVisualizeTrainingMetrics, 17 | NntTrainingHyperparameters, 18 | NntInference, 19 | NntVisualizeConfidenceScores, 20 | NntAnalyzeInferenceMetrics, 21 | 22 | ) 23 | 24 | from .nnt_layers import ( 25 | NntDefineDenseLayer, 26 | NntDefineConvLayer, 27 | NntDefinePoolingLayer, 28 | NntInputLayer, 29 | NntDefineNormLayer, 30 | NntDefineActivationLayer, 31 | NntShowLayerStack, 32 | NntDefineLSTMLayer, 33 | NntDefineGRULayer, 34 | NntDefineRNNLayer, 35 | NntDefineFlattenLayer, 36 | NntDefineReshapeLayer, 37 | ) 38 | 39 | from .nnt_transformers import ( 40 | NntDefineTransformerEncoderLayer, 41 | NntDefinePositionalEncoding, 42 | NntDefineMultiheadAttention, 43 | NntDefineVanillaAttention, 44 | NntDefineLinearAttention, 45 | NntDefineTransformerXLAttention, 46 | NntDefineReformerAttention, 47 | NntDefineLocalAttention, 48 | NntDefineRelativePositionBias, 49 | NntDefineAlibiPositionalBias, 50 | NntDefineRotaryPositionalEmbedding, 51 | NntTextBatchProcessor, 52 | 53 | 54 | ) 55 | 56 | from .nnt_tensors import( 57 | NntTensorOperations, 58 | NntTensorToText, 59 | NntTextToTensor, 60 | NntTensorElementToImage, 61 | NntRandomTensorGenerator, 62 | NntTensorElementToImage, 63 | NntTensorSlice, 64 | NntTorchvisionDatasets, 65 | NntPlotTensors, 66 | NntImageToTensor, 67 | ) 68 | 69 | from .nnt_data import ( 70 | NntTorchvisionDataLoader, 71 | NntFileLoader, 72 | NntTimeSeriesDataLoader, 73 | NntHuggingFaceDataLoader, 74 | NntDatasetToImageTensor, 75 | NntDatasetToTextTensor, 76 | NntDatasetToTargetTensor, 77 | NntDatasetToTensor, 78 | ) 79 | 80 | 81 | 82 | 83 | NODE_CLASS_MAPPINGS = { 84 | "NntCompileModel": NntCompileModel, 85 | "NntShowLayerStack": NntShowLayerStack, 86 | "NntShowModelInfo": NntShowModelInfo, 87 | "NntSaveModel": NntSaveModel, 88 | "NntLoadModel": NntLoadModel, 89 | "NntDefineDenseLayer": NntDefineDenseLayer, 90 | "NntDefineConvLayer": NntDefineConvLayer, 91 | "NntDefinePoolingLayer": NntDefinePoolingLayer, 92 | "NntInputLayer": NntInputLayer, 93 | "NntDefineNormLayer": NntDefineNormLayer, 94 | "NntDefineLSTMLayer": NntDefineLSTMLayer, 95 | "NntDefineGRULayer":NntDefineGRULayer, 96 | "NntDefineRNNLayer":NntDefineRNNLayer, 97 | "NntDefineActivationLayer": NntDefineActivationLayer, 98 | "NntAnalyzeModel": NntAnalyzeModel, 99 | "NntTrainModel": NntTrainModel, 100 | "NntEvaluatePredictions": NntEvaluatePredictions, 101 | "NntVisualizePredictionMetrics": NntVisualizePredictionMetrics, 102 | "NntFineTuneModel": NntFineTuneModel, 103 | "NntEditModelLayers": NntEditModelLayers, 104 | "NntMergeExtendModel": NntMergeExtendModel, 105 | "NntDefineTransformerEncoderLayer": NntDefineTransformerEncoderLayer, 106 | "NntDefinePositionalEncoding": NntDefinePositionalEncoding, 107 | "NntDefineMultiheadAttention": NntDefineMultiheadAttention, 108 | "NntVisualizeGraph": NntVisualizeGraph, 109 | "NntTensorOperations": NntTensorOperations, 110 | "NntTensorToText":NntTensorToText, 111 | "NntTextToTensor": NntTextToTensor, 112 | "NntTensorElementToImage":NntTensorElementToImage, 113 | "NntRandomTensorGenerator": NntRandomTensorGenerator, 114 | "NntTensorElementToImage": NntTensorElementToImage, 115 | "NntSHAPSummaryNode":NntSHAPSummaryNode, 116 | "NntTensorSlice":NntTensorSlice, 117 | "NntDefineVanillaAttention":NntDefineVanillaAttention, 118 | "NntDefineLinearAttention":NntDefineLinearAttention, 119 | "NntDefineTransformerXLAttention":NntDefineTransformerXLAttention, 120 | "NntDefineReformerAttention":NntDefineReformerAttention, 121 | "NntDefineLocalAttention":NntDefineLocalAttention, 122 | "NntDefineRelativePositionBias":NntDefineRelativePositionBias, 123 | "NntDefineAlibiPositionalBias":NntDefineAlibiPositionalBias, 124 | "NntDefineRotaryPositionalEmbedding":NntDefineRotaryPositionalEmbedding, 125 | "NntTorchvisionDatasets": NntTorchvisionDatasets, 126 | "NntTrainingHyperparameters":NntTrainingHyperparameters, 127 | "NntDefineFlattenLayer":NntDefineFlattenLayer, 128 | "NntVisualizeTrainingMetrics":NntVisualizeTrainingMetrics, 129 | "NntDefineReshapeLayer": NntDefineReshapeLayer, 130 | "NntInference":NntInference, 131 | "NntVisualizeConfidenceScores": NntVisualizeConfidenceScores, 132 | "NntAnalyzeInferenceMetrics": NntAnalyzeInferenceMetrics, 133 | "NntTorchvisionDataLoader": NntTorchvisionDataLoader, 134 | "NntFileLoader": NntFileLoader, 135 | "NntTimeSeriesDataLoader": NntTimeSeriesDataLoader, 136 | "NntHuggingFaceDataLoader": NntHuggingFaceDataLoader, 137 | "NntTextBatchProcessor": NntTextBatchProcessor, 138 | "NntDatasetToImageTensor":NntDatasetToImageTensor, 139 | "NntDatasetToTextTensor":NntDatasetToTextTensor, 140 | "NntDatasetToTargetTensor":NntDatasetToTargetTensor, 141 | "NntDatasetToTensor" : NntDatasetToTensor, 142 | "NntPlotTensors":NntPlotTensors, 143 | "NntImageToTensor" : NntImageToTensor, 144 | } 145 | 146 | NODE_DISPLAY_NAME_MAPPINGS = { 147 | "NntDefineDenseLayer": "NNT Define Dense Layer", 148 | "NntCompileModel": "NNT Compile Model", 149 | "NntShowLayerStack": "NNT Show Layer Stack", 150 | "NntShowModelInfo": "NNT Show Model Info", 151 | "NntSaveModel": "NNT Save Model", 152 | "NntLoadModel": "NNT Load Model", 153 | "NntDefineConvLayer": "NNT Define Conv Layer", 154 | "NntDefinePoolingLayer": "NNT Define Pooling Layer", 155 | "NntInputLayer": "NNT Input Layer", 156 | "NntDefineLSTMLayer": "NNT Define LSTM Layer", 157 | "NntDefineGRULayer":"NNT Define GRU Layer", 158 | "NntDefineRNNLayer":"NNT Define RNN Layer", 159 | "NntDefineNormLayer": "NNT Define Normalization Layer", 160 | "NntDefineActivationLayer": "NNT Define Activation Layer", 161 | "NntAnalyzeModel": "NNT Analyze Model", 162 | "NntTrainModel": "NNT Train Model", 163 | "NntEvaluatePredictions": "NNT Evaluate Predictions", 164 | "NntVisualizePredictionMetrics": "NNT Visualize Prediction Metrics", 165 | "NntFineTuneModel": "NNT Fine Tune Model", 166 | "NntEditModelLayers": "NNT Edit Model Layers", 167 | "NntMergeExtendModel": "NNT Merge and Extend Model", 168 | "NntDefineTransformerEncoderLayer": "NNT Define Transformer Encoder Layer", 169 | "NntDefinePositionalEncoding": "NNT Define Positional Encoding", 170 | "NntDefineMultiheadAttention": "NNT Define Multihead Attention", 171 | "NntVisualizeGraph" : "NNT Visualize Model Graph", 172 | "NntTensorOperations" : "NNT Tensor Operations", 173 | "NntTensorToText": "NNT Tensor To Text", 174 | "NntTextToTensor": "NNT Text To Tensor", 175 | "NntTensorElementToImage": "NNT Tensor Element To Image", 176 | "NntRandomTensorGenerator":"NNT Random Tensor Generator", 177 | "NntDataLoader":"NNT Data Loader", 178 | "NntTensorElementToImage": "NNT Tensor Element To Image", 179 | "NntSHAPSummaryNode": "NNT SHAP Summary Node", 180 | "NntTensorSlice": "NNT Tensor Slice", 181 | "NntDefineVanillaAttention":"NNT Define Vanilla Attention", 182 | "NntDefineLinearAttention":"NNT Define Linear Attention", 183 | "NntDefineTransformerXLAttention":"NNT Define TransformerXL Attention", 184 | "NntDefineReformerAttention":"NNT DefineReformer Attention", 185 | "NntDefineLocalAttention":"NNT DefineLocal Attention", 186 | "NntDefineRelativePositionBias":"NNT Define Relative Position Bias", 187 | "NntDefineAlibiPositionalBias":"NNT Define Alibi PositionalBias", 188 | "NntDefineRotaryPositionalEmbedding":"NNT Define Rotary Positional Embedding", 189 | "NntTorchvisionDatasets": "NNT TorchVision Datasets", 190 | "NntTrainingHyperparameters":"NNT Training Hyperparameters", 191 | "NntDefineFlattenLayer":"NNT Define Flatten Layer", 192 | "NntVisualizeTrainingMetrics":"NNT Visualize Training Metrics", 193 | "NntDefineReshapeLayer": "NNT Define Reshape Layer", 194 | "NntInference":"NNT Inference", 195 | "NntVisualizeConfidenceScores": "NNT Visualize Confidence Scores", 196 | "NntAnalyzeInferenceMetrics": "NNT Analyze Inference Metrics", 197 | "NntTorchvisionDataLoader": "NNT TorchVision Data Loader", 198 | "NntFileLoader": "NNT File Data Loader", 199 | "NntTimeSeriesDataLoader": "NNT Time Series Data Loader", 200 | "NntHuggingFaceDataLoader": "NNT HuggingFace Data Loader", 201 | "NntTextBatchProcessor" : "NNT Text Batch Processor", 202 | "NntDatasetToImageTensor":"NntDatasetToImageTensor", 203 | "NntDatasetToTextTensor":"NNT Dataset To Text Tensor", 204 | "NntDatasetToTargetTensor":"NNT Dataset To Target Tensor", 205 | "NntDatasetToTensor":"NNT Dataset To Tensor" , 206 | "NntPlotTensors":"NNT Plot Tensors", 207 | "NntImageToTensor":"NNT Image To Tensor", 208 | } 209 | 210 | #WEB_DIRECTORY = "js" 211 | __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"] -------------------------------------------------------------------------------- /nnt_layers.py: -------------------------------------------------------------------------------- 1 | # dynamic_model_builder.py 2 | 3 | import torch 4 | import torch.nn as nn 5 | import os 6 | 7 | 8 | PADDING_MODES = ["zeros", "reflect", "replicate", "circular"] 9 | NONLINEARITY_TYPES = ["relu", "leaky_relu", "selu", "tanh", "linear", "sigmoid"] 10 | INIT_MODES = ["fan_in", "fan_out"] 11 | LAYER_NORM_TYPES = ["None", "BatchNorm", "LayerNorm"] 12 | 13 | NORMALIZATION_TYPES = [ 14 | "None", 15 | "BatchNorm1d", 16 | "BatchNorm2d", 17 | "BatchNorm3d", 18 | "LayerNorm", 19 | "InstanceNorm1d", 20 | "InstanceNorm2d", 21 | "InstanceNorm3d", 22 | "GroupNorm", 23 | "LocalResponseNorm" 24 | ] 25 | 26 | # List of activation function names 27 | ACTIVATION_FUNCTIONS = [ 28 | "None", 29 | "ELU", 30 | "GELU", 31 | "GLU", 32 | "Hardshrink", 33 | "Hardsigmoid", 34 | "Hardswish", 35 | "Hardtanh", 36 | "LeakyReLU", 37 | "LogSigmoid", 38 | "MultiheadAttention", 39 | "PReLU", 40 | "ReLU", 41 | "ReLU6", 42 | "RReLU", 43 | "SELU", 44 | "CELU", 45 | "Sigmoid", 46 | "SiLU", 47 | "Softmax", 48 | "Softmax2d", 49 | "Softmin", 50 | "Softplus", 51 | "Softshrink", 52 | "Softsign", 53 | "Tanh", 54 | "Tanhshrink", 55 | "Threshold" 56 | ] 57 | 58 | WEIGHT_INIT_METHODS = [ 59 | "default", 60 | "normal", 61 | "uniform", 62 | "xavier_normal", 63 | "xavier_uniform", 64 | "kaiming_normal", 65 | "kaiming_uniform", 66 | "orthogonal", 67 | "sparse", 68 | "dirac", 69 | "zeros", 70 | "ones" 71 | ] 72 | 73 | BIAS_INIT_METHODS = [ 74 | "default", 75 | "zeros", 76 | "ones", 77 | "normal", 78 | "uniform", 79 | ] 80 | 81 | PADDING_MODES = [ 82 | "zeros", 83 | "reflect", 84 | "replicate", 85 | "circular" 86 | ] 87 | 88 | NONLINEARITY_TYPES = [ 89 | "relu", 90 | "leaky_relu", 91 | "selu", 92 | "tanh", 93 | "linear", 94 | "sigmoid" 95 | ] 96 | 97 | INIT_MODES = [ 98 | "fan_in", 99 | "fan_out" 100 | ] 101 | 102 | LAYER_NORM_TYPES = [ 103 | "None", 104 | "BatchNorm", 105 | "LayerNorm", 106 | "InstanceNorm", 107 | "GroupNorm", 108 | "LocalResponseNorm" 109 | ] 110 | 111 | POOLING_TYPES = [ 112 | "MaxPool1d", "MaxPool2d", "MaxPool3d", 113 | "AvgPool1d", "AvgPool2d", "AvgPool3d", 114 | "AdaptiveMaxPool1d", "AdaptiveMaxPool2d", "AdaptiveMaxPool3d", 115 | "AdaptiveAvgPool1d", "AdaptiveAvgPool2d", "AdaptiveAvgPool3d", 116 | "MaxUnpool1d", "MaxUnpool2d", "MaxUnpool3d", 117 | "FractionalMaxPool2d", "LPPool1d", "LPPool2d" 118 | ] 119 | 120 | CONV_TYPES = [ 121 | "Conv1d", "Conv2d", "Conv3d", 122 | "ConvTranspose1d", "ConvTranspose2d", "ConvTranspose3d", 123 | "Unfold", "Fold" 124 | ] 125 | 126 | RNN_NONLINEARITY_TYPES = [ 127 | "tanh", 128 | "relu" 129 | ] 130 | 131 | # Remove duplicate lists and update references 132 | NONLINEARITY_TYPES_LIST = NONLINEARITY_TYPES 133 | WEIGHT_INIT_FUNCTIONS_LIST = WEIGHT_INIT_METHODS 134 | BIAS_INIT_FUNCTIONS_LIST = BIAS_INIT_METHODS 135 | 136 | class NntDefineDenseLayer: 137 | """ 138 | Advanced version of the dense layer node with comprehensive configuration options. 139 | """ 140 | 141 | @classmethod 142 | def INPUT_TYPES(cls): 143 | return { 144 | "required": { 145 | "num_nodes": ("INT", { 146 | "default": 64, 147 | "min": 1, 148 | "max": 8192, 149 | "step": 1, 150 | "display": "number" 151 | }), 152 | "activation_function": (ACTIVATION_FUNCTIONS, {"default": "ReLU"}), 153 | "use_bias": (["True", "False"], {"default": "True"}), 154 | # Weight initialization parameters 155 | "weight_init": (WEIGHT_INIT_FUNCTIONS_LIST, {"default": "kaiming_normal"}), 156 | "weight_init_gain": ("FLOAT", { 157 | "default": 1.0, 158 | "min": 0.01, 159 | "max": 10.0, 160 | "step": 0.01 161 | }), 162 | "weight_init_mode": (INIT_MODES, {"default": "fan_in"}), 163 | "weight_init_nonlinearity": (NONLINEARITY_TYPES, {"default": "relu"}), 164 | # Bias initialization 165 | "bias_init": (BIAS_INIT_FUNCTIONS_LIST, {"default": "zeros"}), 166 | "bias_init_value": ("FLOAT", { 167 | "default": 0.0, 168 | "min": -1.0, 169 | "max": 1.0, 170 | "step": 0.01 171 | }), 172 | # Normalization 173 | "normalization": (LAYER_NORM_TYPES, {"default": "None"}), 174 | "norm_eps": ("FLOAT", { 175 | "default": 1e-5, 176 | "min": 1e-12, 177 | "max": 1e-3, 178 | "step": 1e-6 179 | }), 180 | "norm_momentum": ("FLOAT", { 181 | "default": 0.1, 182 | "min": 0.001, 183 | "max": 0.999, 184 | "step": 0.001 185 | }), 186 | "norm_affine": (["True", "False"], {"default": "True"}), 187 | # Regularization 188 | "dropout_rate": ("FLOAT", { 189 | "default": 0.0, 190 | "min": 0.0, 191 | "max": 0.9, 192 | "step": 0.1 193 | }), 194 | "alpha": ("FLOAT", { # For LeakyReLU, ELU, etc. 195 | "default": 0.01, 196 | "min": 0.0, 197 | "max": 1.0, 198 | "step": 0.01 199 | }), 200 | "num_copies": ("INT", { 201 | "default": 1, 202 | "min": 1, 203 | "max": 100, 204 | "step": 1, 205 | "display": "number" 206 | }), 207 | }, 208 | "optional": { 209 | "LAYER_STACK": ("LIST",), 210 | }, 211 | } 212 | 213 | RETURN_TYPES = ("LIST", "INT") 214 | RETURN_NAMES = ("LAYER_STACK", "num_nodes") 215 | FUNCTION = "define_dense_layer" 216 | CATEGORY = "NNT Neural Network Toolkit/Layers" 217 | 218 | def define_dense_layer(self, num_nodes, activation_function, use_bias, 219 | weight_init, weight_init_gain, weight_init_mode, weight_init_nonlinearity, 220 | bias_init, bias_init_value, normalization, norm_eps, norm_momentum, 221 | norm_affine, dropout_rate, alpha, num_copies, LAYER_STACK=None): 222 | # Initialize or copy the layer stack 223 | if LAYER_STACK is None: 224 | LAYER_STACK = [] 225 | else: 226 | LAYER_STACK = LAYER_STACK.copy() 227 | 228 | # Create the layer definition with all advanced parameters 229 | layer = { 230 | 'type': 'Linear', 231 | 'num_nodes': num_nodes, 232 | 'activation': activation_function, 233 | 'use_bias': use_bias == 'True', 234 | 235 | # Weight initialization 236 | 'weight_init': weight_init, 237 | 'weight_init_gain': float(weight_init_gain), 238 | 'weight_init_mode': weight_init_mode, 239 | 'weight_init_nonlinearity': weight_init_nonlinearity, 240 | 241 | # Bias initialization 242 | 'bias_init': bias_init, 243 | 'bias_init_value': float(bias_init_value), 244 | 245 | # Normalization 246 | 'normalization': normalization, 247 | 'norm_eps': float(norm_eps), 248 | 'norm_momentum': float(norm_momentum), 249 | 'norm_affine': norm_affine == 'True', 250 | 251 | # Regularization and activation parameters 252 | 'dropout_rate': float(dropout_rate), 253 | 'alpha': float(alpha), # For activation functions that need it 254 | } 255 | 256 | # Append the layer definition 'num_copies' times 257 | for _ in range(num_copies): 258 | LAYER_STACK.append(layer.copy()) 259 | 260 | return (LAYER_STACK, num_nodes) 261 | 262 | class NntDefineGRULayer: 263 | @classmethod 264 | def INPUT_TYPES(cls): 265 | return { 266 | "required": { 267 | "input_size": ("INT", { 268 | "default": 10, 269 | "min": 1, 270 | "max": 2048, 271 | "step": 1 272 | }), 273 | "hidden_size": ("INT", { 274 | "default": 20, 275 | "min": 1, 276 | "max": 2048, 277 | "step": 1 278 | }), 279 | "num_layers": ("INT", { 280 | "default": 1, 281 | "min": 1, 282 | "max": 10, 283 | "step": 1 284 | }), 285 | "bias": (["True", "False"], {"default": "True"}), 286 | "batch_first": (["True", "False"], {"default": "True"}), 287 | "dropout": ("FLOAT", { 288 | "default": 0.0, 289 | "min": 0.0, 290 | "max": 1.0, 291 | "step": 0.1 292 | }), 293 | "bidirectional": (["True", "False"], {"default": "False"}), 294 | }, 295 | "optional": { 296 | "LAYER_STACK": ("LIST",), 297 | }, 298 | } 299 | 300 | RETURN_TYPES = ("LIST",) 301 | RETURN_NAMES = ("LAYER_STACK",) 302 | FUNCTION = "define_gru_layer" 303 | CATEGORY = "NNT Neural Network Toolkit/Layers" 304 | 305 | def define_gru_layer(self, input_size, hidden_size, num_layers, bias, 306 | batch_first, dropout, bidirectional, LAYER_STACK=None): 307 | if LAYER_STACK is None: 308 | LAYER_STACK = [] 309 | else: 310 | LAYER_STACK = LAYER_STACK.copy() 311 | 312 | layer = { 313 | 'type': 'GRU', 314 | 'input_size': input_size, 315 | 'hidden_size': hidden_size, 316 | 'num_layers': num_layers, 317 | 'bias': bias == 'True', 318 | 'batch_first': batch_first == 'True', 319 | 'dropout': dropout, 320 | 'bidirectional': bidirectional == 'True' 321 | } 322 | 323 | LAYER_STACK.append(layer) 324 | return (LAYER_STACK,) 325 | 326 | class NntDefineRNNLayer: 327 | @classmethod 328 | def INPUT_TYPES(cls): 329 | return { 330 | "required": { 331 | "input_size": ("INT", { 332 | "default": 10, 333 | "min": 1, 334 | "max": 2048, 335 | "step": 1 336 | }), 337 | "hidden_size": ("INT", { 338 | "default": 20, 339 | "min": 1, 340 | "max": 2048, 341 | "step": 1 342 | }), 343 | "num_layers": ("INT", { 344 | "default": 1, 345 | "min": 1, 346 | "max": 10, 347 | "step": 1 348 | }), 349 | "nonlinearity": (RNN_NONLINEARITY_TYPES, {"default": "tanh"}), 350 | "bias": (["True", "False"], {"default": "True"}), 351 | "batch_first": (["True", "False"], {"default": "True"}), 352 | "dropout": ("FLOAT", { 353 | "default": 0.0, 354 | "min": 0.0, 355 | "max": 1.0, 356 | "step": 0.1 357 | }), 358 | "bidirectional": (["True", "False"], {"default": "False"}), 359 | }, 360 | "optional": { 361 | "LAYER_STACK": ("LIST",), 362 | }, 363 | } 364 | 365 | RETURN_TYPES = ("LIST",) 366 | RETURN_NAMES = ("LAYER_STACK",) 367 | FUNCTION = "define_rnn_layer" 368 | CATEGORY = "NNT Neural Network Toolkit/Layers" 369 | 370 | def define_rnn_layer(self, input_size, hidden_size, num_layers, nonlinearity, 371 | bias, batch_first, dropout, bidirectional, LAYER_STACK=None): 372 | if LAYER_STACK is None: 373 | LAYER_STACK = [] 374 | else: 375 | LAYER_STACK = LAYER_STACK.copy() 376 | 377 | layer = { 378 | 'type': 'RNN', 379 | 'input_size': input_size, 380 | 'hidden_size': hidden_size, 381 | 'num_layers': num_layers, 382 | 'nonlinearity': nonlinearity, 383 | 'bias': bias == 'True', 384 | 'batch_first': batch_first == 'True', 385 | 'dropout': dropout, 386 | 'bidirectional': bidirectional == 'True' 387 | } 388 | 389 | LAYER_STACK.append(layer) 390 | return (LAYER_STACK,) 391 | 392 | 393 | class NntDefineConvLayer: 394 | """Node for defining convolutional layers with full configuration options and hyperparameter support.""" 395 | 396 | @classmethod 397 | def INPUT_TYPES(cls): 398 | return { 399 | "required": { 400 | "conv_type": (CONV_TYPES, { 401 | "default": "Conv2d" 402 | }), 403 | "out_channels": ("INT", { 404 | "default": 64, 405 | "min": 1, 406 | "max": 2048, 407 | "step": 1 408 | }), 409 | "kernel_size": ("INT", { 410 | "default": 3, 411 | "min": 1, 412 | "max": 15, 413 | "step": 1 414 | }), 415 | "stride": ("INT", { 416 | "default": 1, 417 | "min": 1, 418 | "max": 8, 419 | "step": 1 420 | }), 421 | "padding": ("INT", { 422 | "default": 1, 423 | "min": 0, 424 | "max": 10, 425 | "step": 1 426 | }), 427 | "padding_mode": (PADDING_MODES, {"default": "zeros"}), 428 | "output_padding": ("INT", { 429 | "default": 0, 430 | "min": 0, 431 | "max": 2, 432 | "step": 1 433 | }), 434 | "dilation": ("INT", { 435 | "default": 1, 436 | "min": 1, 437 | "max": 5, 438 | "step": 1 439 | }), 440 | "groups": ("INT", { 441 | "default": 1, 442 | "min": 1, 443 | "max": 2048, 444 | "step": 1 445 | }), 446 | "use_bias": (["True", "False"], {"default": "True"}), 447 | "activation_function": (ACTIVATION_FUNCTIONS, {"default": "ReLU"}), 448 | "normalization": (NORMALIZATION_TYPES, {"default": "BatchNorm"}), 449 | "norm_eps": ("FLOAT", { 450 | "default": 1e-5, 451 | "min": 1e-12, 452 | "max": 1e-3, 453 | "step": 1e-6 454 | }), 455 | "norm_momentum": ("FLOAT", { 456 | "default": 0.1, 457 | "min": 0.001, 458 | "max": 0.999, 459 | "step": 0.001 460 | }), 461 | "norm_affine": (["True", "False"], {"default": "True"}), 462 | "dropout_rate": ("FLOAT", { 463 | "default": 0.0, 464 | "min": 0.0, 465 | "max": 0.9, 466 | "step": 0.1 467 | }), 468 | "weight_init": (WEIGHT_INIT_METHODS, {"default": "kaiming_normal"}), 469 | "weight_init_gain": ("FLOAT", { 470 | "default": 1.414, 471 | "min": 0.01, 472 | "max": 10.0, 473 | "step": 0.01 474 | }), 475 | "weight_init_mode": (INIT_MODES, {"default": "fan_out"}), 476 | "weight_init_nonlinearity": (NONLINEARITY_TYPES, {"default": "relu"}), 477 | "num_copies": ("INT", { 478 | "default": 1, 479 | "min": 1, 480 | "max": 100, 481 | "step": 1 482 | }) 483 | }, 484 | "optional": { 485 | "LAYER_STACK": ("LIST",), 486 | "hyperparameters": ("DICT",) 487 | } 488 | } 489 | 490 | RETURN_TYPES = ("LIST",) 491 | RETURN_NAMES = ("layer_stack",) 492 | FUNCTION = "define_conv_layer" 493 | CATEGORY = "NNT Neural Network Toolkit/Layers" 494 | 495 | def define_conv_layer(self, conv_type, out_channels, kernel_size, stride, padding, 496 | padding_mode, output_padding, dilation, groups, use_bias, activation_function, 497 | normalization, norm_eps, norm_momentum, norm_affine, dropout_rate, 498 | weight_init, weight_init_gain, weight_init_mode, weight_init_nonlinearity, 499 | num_copies, LAYER_STACK=None, hyperparameters=None): 500 | try: 501 | if LAYER_STACK is None: 502 | LAYER_STACK = [] 503 | else: 504 | LAYER_STACK = LAYER_STACK.copy() 505 | 506 | # Create the layers 507 | for _ in range(num_copies): 508 | # Main convolution layer definition 509 | conv_layer = { 510 | 'type': conv_type, 511 | 'in_channels': 3 if not LAYER_STACK else LAYER_STACK[-1].get('out_channels', 3), 512 | 'out_channels': out_channels, 513 | 'kernel_size': kernel_size, 514 | 'stride': stride, 515 | 'padding': padding, 516 | 'padding_mode': padding_mode, 517 | 'dilation': dilation, 518 | 'groups': groups, 519 | 'bias': use_bias == "True", 520 | 'weight_init': weight_init, 521 | 'weight_init_gain': float(weight_init_gain), 522 | 'weight_init_mode': weight_init_mode, 523 | 'weight_init_nonlinearity': weight_init_nonlinearity 524 | } 525 | 526 | # Add output_padding only for ConvTranspose layers 527 | if 'ConvTranspose' in conv_type: 528 | conv_layer['output_padding'] = output_padding 529 | 530 | LAYER_STACK.append(conv_layer) 531 | 532 | # Normalization layer 533 | if normalization != "None": 534 | norm_layer = { 535 | 'type': normalization, 536 | 'num_features': out_channels, 537 | 'out_channels': out_channels, 538 | 'eps': float(norm_eps), 539 | 'momentum': float(norm_momentum), 540 | 'affine': norm_affine == "True", 541 | 'track_running_stats': True 542 | } 543 | LAYER_STACK.append(norm_layer) 544 | 545 | # Activation layer 546 | # Activation layer 547 | if activation_function != "None": 548 | if activation_function == "ReLU": 549 | act_layer = { 550 | 'type': 'Activation', 551 | 'activation_type': activation_function 552 | } 553 | elif activation_function == "LeakyReLU": 554 | act_layer = { 555 | 'type': 'Activation', 556 | 'activation_type': activation_function, 557 | 'negative_slope': 0.01 # Default value, you can make it configurable if needed 558 | } 559 | else: 560 | act_layer = { 561 | 'type': 'Activation', 562 | 'activation_type': activation_function 563 | } 564 | LAYER_STACK.append(act_layer) 565 | 566 | # Dropout layer 567 | if dropout_rate > 0: 568 | dropout_layer = { 569 | 'type': 'Dropout', 570 | 'dropout_rate': float(dropout_rate), 571 | 'out_channels': out_channels 572 | } 573 | LAYER_STACK.append(dropout_layer) 574 | 575 | return (LAYER_STACK,) 576 | 577 | except Exception as e: 578 | import traceback 579 | error_msg = f"Error defining convolutional layer: {str(e)}\n{traceback.format_exc()}" 580 | print(error_msg) 581 | return (LAYER_STACK if LAYER_STACK is not None else [],) 582 | 583 | @classmethod 584 | def IS_CHANGED(cls, **kwargs): 585 | # This ensures the node is evaluated when hyperparameters change 586 | return float("NaN") 587 | 588 | @classmethod 589 | def VALIDATE_INPUTS(cls, **kwargs): 590 | # Basic input validation 591 | try: 592 | if kwargs.get('stride', 1) > kwargs.get('kernel_size', 3): 593 | return "Stride should not be larger than kernel size" 594 | return True 595 | except Exception as e: 596 | return f"Validation error: {str(e)}" 597 | 598 | 599 | class NntDefinePoolingLayer: 600 | @classmethod 601 | def INPUT_TYPES(cls): 602 | POOL_TYPES = [ 603 | "MaxPool1d", "MaxPool2d", "MaxPool3d", 604 | "AvgPool1d", "AvgPool2d", "AvgPool3d", 605 | "AdaptiveMaxPool1d", "AdaptiveMaxPool2d", "AdaptiveMaxPool3d", 606 | "AdaptiveAvgPool1d", "AdaptiveAvgPool2d", "AdaptiveAvgPool3d", 607 | "MaxUnpool1d", "MaxUnpool2d", "MaxUnpool3d", 608 | "FractionalMaxPool2d", "LPPool1d", "LPPool2d" 609 | ] 610 | 611 | return { 612 | "required": { 613 | "pooling_type": (POOL_TYPES, {"default": "MaxPool2d"}), 614 | # Basic pooling parameters - handled as string for multi-dimensional input 615 | "kernel_size": ("STRING", { 616 | "default": "2", 617 | "multiline": False, 618 | "placeholder": "Single int or tuple: 2 or (2,2) or (2,2,2)" 619 | }), 620 | "stride": ("STRING", { 621 | "default": "2", 622 | "multiline": False, 623 | "placeholder": "Single int or tuple" 624 | }), 625 | "padding": ("STRING", { 626 | "default": "0", 627 | "multiline": False, 628 | "placeholder": "Single int or tuple" 629 | }), 630 | # Advanced MaxPool options 631 | "dilation": ("STRING", { 632 | "default": "1", 633 | "multiline": False, 634 | "placeholder": "Single int or tuple" 635 | }), 636 | "ceil_mode": (["True", "False"], {"default": "False"}), 637 | "return_indices": (["True", "False"], {"default": "False"}), 638 | # AvgPool specific options 639 | "count_include_pad": (["True", "False"], {"default": "True"}), 640 | # Adaptive pooling options - handled as string for multi-dimensional output size 641 | "output_size": ("STRING", { 642 | "default": "1", 643 | "multiline": False, 644 | "placeholder": "Single int or tuple" 645 | }), 646 | # FractionalMaxPool options 647 | "fractional_factor": ("FLOAT", { 648 | "default": 1.5, 649 | "min": 1.0, 650 | "max": 3.0, 651 | "step": 0.1 652 | }), 653 | # LPPool options 654 | "norm_type": ("FLOAT", { 655 | "default": 2.0, 656 | "min": 1.0, 657 | "max": 6.0, 658 | "step": 0.1 659 | }), 660 | "flatten_output": (["True", "False"], {"default": "False"}), 661 | "num_copies": ("INT", { 662 | "default": 1, 663 | "min": 1, 664 | "max": 100, 665 | "step": 1 666 | }), 667 | }, 668 | "optional": { 669 | "LAYER_STACK": ("LIST",), 670 | }, 671 | } 672 | 673 | RETURN_TYPES = ("LIST",) 674 | RETURN_NAMES = ("LAYER_STACK",) 675 | FUNCTION = "define_pooling_layer" 676 | CATEGORY = "NNT Neural Network Toolkit/Layers" 677 | 678 | def parse_size_param(self, param_str, dim=2): 679 | try: 680 | val = eval(param_str) 681 | if isinstance(val, (int, float)): 682 | return val 683 | if isinstance(val, (tuple, list)): 684 | if len(val) == dim: 685 | return val 686 | raise ValueError 687 | except: 688 | if 'd1' in self.pooling_type: 689 | return int(param_str) 690 | elif 'd2' in self.pooling_type: 691 | return (int(param_str), int(param_str)) 692 | else: # 3d 693 | return (int(param_str), int(param_str), int(param_str)) 694 | 695 | def define_pooling_layer(self, pooling_type, kernel_size, stride, padding, dilation, 696 | ceil_mode, return_indices, count_include_pad, output_size, 697 | fractional_factor, norm_type, flatten_output, num_copies, LAYER_STACK=None): 698 | if LAYER_STACK is None: 699 | LAYER_STACK = [] 700 | else: 701 | LAYER_STACK = LAYER_STACK.copy() 702 | 703 | # Determine dimensionality 704 | dim = 2 # default 705 | if '1d' in pooling_type: 706 | dim = 1 707 | elif '3d' in pooling_type: 708 | dim = 3 709 | 710 | # Parse size parameters 711 | kernel = self.parse_size_param(kernel_size, dim) 712 | stride_val = self.parse_size_param(stride, dim) 713 | padding_val = self.parse_size_param(padding, dim) 714 | dilation_val = self.parse_size_param(dilation, dim) 715 | output_size_val = self.parse_size_param(output_size, dim) 716 | 717 | layer = { 718 | 'type': pooling_type, 719 | 'flatten_output': flatten_output == 'True' 720 | } 721 | 722 | if pooling_type.startswith(('MaxPool', 'AvgPool', 'LPPool')): 723 | layer.update({ 724 | 'kernel_size': kernel, 725 | 'stride': stride_val, 726 | 'padding': padding_val, 727 | 'ceil_mode': ceil_mode == 'True' 728 | }) 729 | 730 | if 'MaxPool' in pooling_type: 731 | layer.update({ 732 | 'dilation': dilation_val, 733 | 'return_indices': return_indices == 'True' 734 | }) 735 | elif 'AvgPool' in pooling_type: 736 | layer['count_include_pad'] = count_include_pad == 'True' 737 | elif 'LPPool' in pooling_type: 738 | layer['norm_type'] = float(norm_type) 739 | 740 | elif pooling_type.startswith('Adaptive'): 741 | layer.update({ 742 | 'output_size': output_size_val, 743 | 'return_indices': return_indices == 'True' if 'Max' in pooling_type else False 744 | }) 745 | 746 | elif pooling_type.startswith('MaxUnpool'): 747 | layer.update({ 748 | 'kernel_size': kernel, 749 | 'stride': stride_val, 750 | 'padding': padding_val 751 | }) 752 | 753 | elif pooling_type == 'FractionalMaxPool2d': 754 | layer.update({ 755 | 'kernel_size': kernel, 756 | 'fractional_factor': float(fractional_factor), 757 | 'return_indices': return_indices == 'True' 758 | }) 759 | 760 | for _ in range(num_copies): 761 | LAYER_STACK.append(layer.copy()) 762 | 763 | return (LAYER_STACK,) 764 | 765 | class NntInputLayer: 766 | """ 767 | A node to define the input layer with the specified input shape provided as a text field. 768 | """ 769 | 770 | @classmethod 771 | def INPUT_TYPES(cls): 772 | return { 773 | "required": { 774 | "input_shape_str": ("STRING", { 775 | "default": "[3, 224, 224]", 776 | "multiline": False, 777 | "placeholder": "Enter input shape as a list, e.g., [3, 224, 224]" 778 | }), 779 | } 780 | } 781 | 782 | RETURN_TYPES = ("LIST",) 783 | RETURN_NAMES = ("LAYER_STACK",) 784 | FUNCTION = "define_input_layer" 785 | CATEGORY = "NNT Neural Network Toolkit/Layers" 786 | 787 | def define_input_layer(self, input_shape_str): 788 | # Parse the input_shape_str into a list of integers 789 | try: 790 | # Remove any whitespace and parse the string 791 | input_shape = eval(input_shape_str.strip(), {"__builtins__": None}, {}) 792 | if not isinstance(input_shape, list): 793 | raise ValueError("Input shape must be a list of integers.") 794 | # Validate that all elements are integers 795 | for dim in input_shape: 796 | if not isinstance(dim, int): 797 | raise ValueError("All dimensions must be integers.") 798 | # Ensure input_shape is not empty 799 | if len(input_shape) == 0: 800 | raise ValueError("Input shape cannot be empty.") 801 | except Exception as e: 802 | raise ValueError(f"Invalid input_shape format: {str(e)}") 803 | 804 | # Create the layer definition 805 | layer = { 806 | 'type': 'Input', 807 | 'input_shape': input_shape, 808 | } 809 | LAYER_STACK = [layer] 810 | return (LAYER_STACK,) 811 | 812 | class NntDefineNormLayer: 813 | """ 814 | Node for defining normalization layers. 815 | """ 816 | 817 | @classmethod 818 | def INPUT_TYPES(cls): 819 | return { 820 | "required": { 821 | "norm_type": (LAYER_NORM_TYPES, { 822 | "default": "BatchNorm2d" 823 | }), 824 | "num_features": ("INT", { 825 | "default": 64, 826 | "min": 1, 827 | "max": 2048, 828 | "step": 1 829 | }), 830 | "eps": ("FLOAT", { 831 | "default": 1e-5, 832 | "min": 1e-10, 833 | "max": 1e-3, 834 | "step": 1e-6 835 | }), 836 | "momentum": ("FLOAT", { 837 | "default": 0.1, 838 | "min": 0.0, 839 | "max": 1.0, 840 | "step": 0.1 841 | }), 842 | "affine": (["True", "False"], { 843 | "default": "True" 844 | }), 845 | "track_running_stats": (["True", "False"], { 846 | "default": "True" 847 | }), 848 | }, 849 | "optional": { 850 | "LAYER_STACK": ("LIST",), 851 | }, 852 | } 853 | 854 | RETURN_TYPES = ("LIST",) 855 | RETURN_NAMES = ("LAYER_STACK",) 856 | FUNCTION = "define_norm_layer" 857 | CATEGORY = "NNT Neural Network Toolkit/Layers" 858 | 859 | def define_norm_layer(self, norm_type, num_features, eps, momentum, 860 | affine, track_running_stats, LAYER_STACK=None): 861 | # Initialize or copy the layer stack 862 | if LAYER_STACK is None: 863 | LAYER_STACK = [] 864 | else: 865 | LAYER_STACK = LAYER_STACK.copy() 866 | 867 | # Create the layer definition 868 | layer = { 869 | 'type': norm_type, 870 | 'num_features': num_features, 871 | 'eps': float(eps), 872 | 'momentum': float(momentum), 873 | 'affine': affine == 'True', 874 | 'track_running_stats': track_running_stats == 'True' 875 | } 876 | 877 | # Append the layer definition 878 | LAYER_STACK.append(layer.copy()) 879 | 880 | return (LAYER_STACK,) 881 | 882 | class NntDefineActivationLayer: 883 | """ 884 | Node for defining activation layers. 885 | """ 886 | 887 | @classmethod 888 | def INPUT_TYPES(cls): 889 | return { 890 | "required": { 891 | "activation_type": (ACTIVATION_FUNCTIONS, { 892 | "default": "ReLU" 893 | }), 894 | "inplace": (["True", "False"], { 895 | "default": "False" 896 | }), 897 | "negative_slope": ("FLOAT", { 898 | "default": 0.01, 899 | "min": 0.0, 900 | "max": 1.0, 901 | "step": 0.01 902 | }), 903 | "num_parameters": ("INT", { 904 | "default": 1, 905 | "min": 1, 906 | "max": 2048, 907 | "step": 1 908 | }), 909 | "alpha": ("FLOAT", { 910 | "default": 1.0, 911 | "min": 0.0, 912 | "max": 10.0, 913 | "step": 0.1 914 | }), 915 | }, 916 | "optional": { 917 | "LAYER_STACK": ("LIST",), 918 | }, 919 | } 920 | 921 | RETURN_TYPES = ("LIST",) 922 | RETURN_NAMES = ("LAYER_STACK",) 923 | FUNCTION = "define_activation_layer" 924 | CATEGORY = "NNT Neural Network Toolkit/Layers" 925 | 926 | def define_activation_layer(self, activation_type, inplace, negative_slope, 927 | num_parameters, alpha, LAYER_STACK=None): 928 | # Initialize or copy the layer stack 929 | if LAYER_STACK is None: 930 | LAYER_STACK = [] 931 | else: 932 | LAYER_STACK = LAYER_STACK.copy() 933 | 934 | # Create the layer definition 935 | layer = { 936 | 'type': 'Activation', 937 | 'activation_type': activation_type, 938 | 'inplace': inplace == 'True', 939 | 'negative_slope': float(negative_slope), 940 | 'num_parameters': num_parameters, 941 | 'alpha': float(alpha) 942 | } 943 | 944 | # Append the layer definition 945 | LAYER_STACK.append(layer.copy()) 946 | 947 | return (LAYER_STACK,) 948 | 949 | class NntDefineLSTMLayer: 950 | @classmethod 951 | def INPUT_TYPES(cls): 952 | return { 953 | "required": { 954 | "input_size": ("INT", { 955 | "default": 10, 956 | "min": 1, 957 | "max": 2048, 958 | "step": 1 959 | }), 960 | "hidden_size": ("INT", { 961 | "default": 20, 962 | "min": 1, 963 | "max": 2048, 964 | "step": 1 965 | }), 966 | "num_layers": ("INT", { 967 | "default": 1, 968 | "min": 1, 969 | "max": 10, 970 | "step": 1 971 | }), 972 | "bias": (["True", "False"], {"default": "True"}), 973 | "batch_first": (["True", "False"], {"default": "True"}), 974 | "dropout": ("FLOAT", { 975 | "default": 0.0, 976 | "min": 0.0, 977 | "max": 1.0, 978 | "step": 0.1 979 | }), 980 | "bidirectional": (["True", "False"], {"default": "False"}), 981 | }, 982 | "optional": { 983 | "LAYER_STACK": ("LIST",), 984 | }, 985 | } 986 | 987 | RETURN_TYPES = ("LIST",) 988 | RETURN_NAMES = ("LAYER_STACK",) 989 | FUNCTION = "define_lstm_layer" 990 | CATEGORY = "NNT Neural Network Toolkit/Layers" 991 | 992 | def define_lstm_layer(self, input_size, hidden_size, num_layers, bias, 993 | batch_first, dropout, bidirectional, LAYER_STACK=None): 994 | if LAYER_STACK is None: 995 | LAYER_STACK = [] 996 | else: 997 | LAYER_STACK = LAYER_STACK.copy() 998 | 999 | layer = { 1000 | 'type': 'LSTM', 1001 | 'input_size': input_size, 1002 | 'hidden_size': hidden_size, 1003 | 'num_layers': num_layers, 1004 | 'bias': bias == 'True', 1005 | 'batch_first': batch_first == 'True', 1006 | 'dropout': dropout, 1007 | 'bidirectional': bidirectional == 'True' 1008 | } 1009 | 1010 | LAYER_STACK.append(layer) 1011 | return (LAYER_STACK,) 1012 | 1013 | class NntShowLayerStack: 1014 | @classmethod 1015 | def INPUT_TYPES(cls): 1016 | return { 1017 | "required": { 1018 | "LAYER_STACK": ("LIST",), 1019 | "show_details": (["Basic", "Detailed"], {"default": "Basic"}) 1020 | } 1021 | } 1022 | 1023 | RETURN_TYPES = ("STRING",) 1024 | RETURN_NAMES = ("layer_stack_report") 1025 | FUNCTION = "show_layer_stack" 1026 | OUTPUT_NODE = True 1027 | CATEGORY = "NNT Neural Network Toolkit/Layers" 1028 | 1029 | def format_layer_params(self, params): 1030 | """Helper function to format parameter dictionaries.""" 1031 | return ", ".join(f"{k}={v}" for k, v in params.items() if v is not None and v != "None" and v != "" and str(v) != "0.0") 1032 | 1033 | def show_layer_stack(self, LAYER_STACK, show_details): 1034 | stack_info = [] 1035 | 1036 | for idx, layer in enumerate(LAYER_STACK): 1037 | layer_type = layer.get('type', 'Unknown') 1038 | basic_info = [f"\nLayer {idx + 1}: Type={layer_type}"] 1039 | 1040 | # Input Layer 1041 | if layer_type == 'Input': 1042 | basic_info.append(f"Shape={layer.get('input_shape', 'N/A')}") 1043 | 1044 | # Dense/Linear Layer 1045 | elif layer_type == 'Linear': 1046 | basic_info.extend([ 1047 | f"Nodes={layer.get('num_nodes', 'N/A')}", 1048 | f"Activation={layer.get('activation', 'N/A')}" 1049 | ]) 1050 | if show_details == "Detailed": 1051 | detailed_info = { 1052 | 'Use Bias': layer.get('use_bias'), 1053 | 'Weight Init': layer.get('weight_init'), 1054 | 'Init Gain': layer.get('weight_init_gain'), 1055 | 'Init Mode': layer.get('weight_init_mode'), 1056 | 'Init NonLin': layer.get('weight_init_nonlinearity'), 1057 | 'Normalization': layer.get('normalization'), 1058 | 'Norm Eps': layer.get('norm_eps'), 1059 | 'Norm Momentum': layer.get('norm_momentum'), 1060 | 'Norm Affine': layer.get('norm_affine'), 1061 | 'Dropout': layer.get('dropout_rate') 1062 | } 1063 | basic_info.append(f"Details: {self.format_layer_params(detailed_info)}") 1064 | 1065 | # Convolutional Layers 1066 | elif layer_type in ['Conv1d', 'Conv2d', 'Conv3d', 'ConvTranspose1d', 'ConvTranspose2d', 'ConvTranspose3d']: 1067 | basic_info.extend([ 1068 | f"Out Channels={layer.get('out_channels', 'N/A')}", 1069 | f"Kernel={layer.get('kernel_size', 'N/A')}", 1070 | f"Stride={layer.get('stride', 'N/A')}", 1071 | f"Padding={layer.get('padding', 'N/A')}" 1072 | ]) 1073 | if show_details == "Detailed": 1074 | detailed_info = { 1075 | 'Padding Mode': layer.get('padding_mode'), 1076 | 'Dilation': layer.get('dilation'), 1077 | 'Groups': layer.get('groups'), 1078 | 'Output Padding': layer.get('output_padding'), 1079 | 'Activation': layer.get('activation'), 1080 | 'Use Bias': layer.get('use_bias'), 1081 | 'Weight Init': layer.get('weight_init'), 1082 | 'Init Gain': layer.get('weight_init_gain'), 1083 | 'Normalization': layer.get('normalization'), 1084 | 'Dropout': layer.get('dropout_rate') 1085 | } 1086 | basic_info.append(f"Details: {self.format_layer_params(detailed_info)}") 1087 | 1088 | # Pooling Layers 1089 | elif any(x in layer_type for x in ['Pool1d', 'Pool2d', 'Pool3d']): 1090 | basic_info.extend([ 1091 | f"Type={layer_type}", 1092 | f"Kernel={layer.get('kernel_size', 'N/A')}", 1093 | f"Stride={layer.get('stride', 'N/A')}" 1094 | ]) 1095 | if show_details == "Detailed": 1096 | detailed_info = { 1097 | 'Padding': layer.get('padding'), 1098 | 'Dilation': layer.get('dilation'), 1099 | 'Ceil Mode': layer.get('ceil_mode'), 1100 | 'Return Indices': layer.get('return_indices'), 1101 | 'Count Include Pad': layer.get('count_include_pad'), 1102 | 'Output Size': layer.get('output_size'), 1103 | 'Flatten Output': layer.get('flatten_output') 1104 | } 1105 | basic_info.append(f"Details: {self.format_layer_params(detailed_info)}") 1106 | 1107 | # Recurrent Layers (LSTM, GRU, RNN) 1108 | elif layer_type in ['LSTM', 'GRU', 'RNN']: 1109 | basic_info.extend([ 1110 | f"Input Size={layer.get('input_size', 'N/A')}", 1111 | f"Hidden Size={layer.get('hidden_size', 'N/A')}", 1112 | f"Num Layers={layer.get('num_layers', 'N/A')}" 1113 | ]) 1114 | if show_details == "Detailed": 1115 | detailed_info = { 1116 | 'Bias': layer.get('bias'), 1117 | 'Batch First': layer.get('batch_first'), 1118 | 'Dropout': layer.get('dropout'), 1119 | 'Bidirectional': layer.get('bidirectional'), 1120 | 'Nonlinearity': layer.get('nonlinearity') # For RNN 1121 | } 1122 | basic_info.append(f"Details: {self.format_layer_params(detailed_info)}") 1123 | 1124 | # Normalization Layers 1125 | elif any(x in layer_type for x in ['BatchNorm', 'LayerNorm', 'InstanceNorm', 'GroupNorm']): 1126 | basic_info.extend([ 1127 | f"Num Features={layer.get('num_features', 'N/A')}" 1128 | ]) 1129 | if show_details == "Detailed": 1130 | detailed_info = { 1131 | 'Eps': layer.get('eps'), 1132 | 'Momentum': layer.get('momentum'), 1133 | 'Affine': layer.get('affine'), 1134 | 'Track Running Stats': layer.get('track_running_stats') 1135 | } 1136 | basic_info.append(f"Details: {self.format_layer_params(detailed_info)}") 1137 | 1138 | # Activation Layers 1139 | elif layer_type == 'Activation': 1140 | basic_info.extend([ 1141 | f"Function={layer.get('activation_type', 'N/A')}" 1142 | ]) 1143 | if show_details == "Detailed": 1144 | detailed_info = { 1145 | 'Inplace': layer.get('inplace'), 1146 | 'Negative Slope': layer.get('negative_slope'), 1147 | 'Num Parameters': layer.get('num_parameters'), 1148 | 'Alpha': layer.get('alpha') 1149 | } 1150 | basic_info.append(f"Details: {self.format_layer_params(detailed_info)}") 1151 | 1152 | 1153 | stack_info.append(" | ".join(basic_info)) 1154 | 1155 | if not stack_info: 1156 | return ("No layers defined yet.",) 1157 | 1158 | return ("\n".join(stack_info),) 1159 | 1160 | class NntDefineFlattenLayer: 1161 | @classmethod 1162 | def INPUT_TYPES(cls): 1163 | return { 1164 | "required": { 1165 | "LAYER_STACK": ("LIST",), 1166 | } 1167 | } 1168 | 1169 | RETURN_TYPES = ("LIST",) 1170 | FUNCTION = "define_flatten_layer" 1171 | CATEGORY = "NNT Neural Network Toolkit/Layers" 1172 | 1173 | def define_flatten_layer(self, LAYER_STACK=None): 1174 | if LAYER_STACK is None: 1175 | LAYER_STACK = [] 1176 | else: 1177 | LAYER_STACK = LAYER_STACK.copy() 1178 | 1179 | layer = { 1180 | 'type': 'Flatten', 1181 | 'start_dim': 1, 1182 | 'end_dim': -1 1183 | } 1184 | 1185 | LAYER_STACK.append(layer) 1186 | return (LAYER_STACK,) 1187 | 1188 | class NntDefineReshapeLayer: 1189 | @classmethod 1190 | def INPUT_TYPES(cls): 1191 | return { 1192 | "required": { 1193 | "target_shape": ("STRING", { 1194 | "default": "[8,7,7]", 1195 | "multiline": False, 1196 | "placeholder": "e.g., [8,7,7] or [-1,8,7,7]" 1197 | }), 1198 | }, 1199 | "optional": { 1200 | "LAYER_STACK": ("LIST",), 1201 | }, 1202 | } 1203 | 1204 | RETURN_TYPES = ("LIST",) 1205 | RETURN_NAMES = ("LAYER_STACK",) 1206 | FUNCTION = "define_reshape_layer" 1207 | CATEGORY = "NNT Neural Network Toolkit/Layers" 1208 | 1209 | def define_reshape_layer(self, target_shape, LAYER_STACK=None): 1210 | if LAYER_STACK is None: 1211 | LAYER_STACK = [] 1212 | else: 1213 | LAYER_STACK = LAYER_STACK.copy() 1214 | 1215 | # Parse the shape string into a list 1216 | try: 1217 | shape = eval(target_shape) 1218 | if not isinstance(shape, (list, tuple)): 1219 | raise ValueError("Target shape must be a list or tuple") 1220 | except Exception as e: 1221 | raise ValueError(f"Invalid shape format: {str(e)}") 1222 | 1223 | layer = { 1224 | 'type': 'Reshape', 1225 | 'target_shape': shape 1226 | } 1227 | 1228 | LAYER_STACK.append(layer) 1229 | return (LAYER_STACK,) -------------------------------------------------------------------------------- /nnt_transformers.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import math 4 | import os 5 | 6 | # Transformer configuration constants 7 | TRANSFORMER_ACTIVATIONS = [ 8 | "relu", 9 | "gelu", 10 | "silu", 11 | "tanh" 12 | ] 13 | 14 | TRANSFORMER_ENCODING_TYPES = [ 15 | "sinusoidal", 16 | "learned", 17 | "rotary", 18 | "alibi" 19 | ] 20 | 21 | ATTENTION_TYPES = [ 22 | "dot_product", 23 | "additive", 24 | "scaled_dot_product", 25 | "relative", 26 | "local" 27 | ] 28 | 29 | # Model dimension ranges 30 | MODEL_DIM_CONFIG = { 31 | "d_model": { 32 | "default": 512, 33 | "min": 64, 34 | "max": 2048, 35 | "step": 64 36 | }, 37 | "embed_dim": { 38 | "default": 512, 39 | "min": 64, 40 | "max": 2048, 41 | "step": 64 42 | }, 43 | "dim_feedforward": { 44 | "default": 2048, 45 | "min": 128, 46 | "max": 8192, 47 | "step": 128 48 | }, 49 | "max_seq_length": { 50 | "default": 512, 51 | "min": 16, 52 | "max": 2048, 53 | "step": 16 54 | } 55 | } 56 | 57 | # Attention configuration ranges 58 | ATTENTION_CONFIG = { 59 | "num_heads": { 60 | "default": 8, 61 | "min": 1, 62 | "max": 32, 63 | "step": 1 64 | }, 65 | "dropout": { 66 | "default": 0.1, 67 | "min": 0.0, 68 | "max": 0.9, 69 | "step": 0.1 70 | }, 71 | "window_size": { 72 | "default": 128, 73 | "min": 16, 74 | "max": 512, 75 | "step": 16 76 | } 77 | } 78 | 79 | class NntDefineTransformerEncoderLayer: 80 | @classmethod 81 | def INPUT_TYPES(cls): 82 | return { 83 | "required": { 84 | "d_model": ("INT", MODEL_DIM_CONFIG["d_model"]), 85 | "nhead": ("INT", ATTENTION_CONFIG["num_heads"]), 86 | "dim_feedforward": ("INT", MODEL_DIM_CONFIG["dim_feedforward"]), 87 | "dropout": ("FLOAT", ATTENTION_CONFIG["dropout"]), 88 | "activation": (TRANSFORMER_ACTIVATIONS, { 89 | "default": "relu" 90 | }), 91 | "batch_first": (["True", "False"], { 92 | "default": "True" 93 | }), 94 | "norm_first": (["True", "False"], { 95 | "default": "False" 96 | }), 97 | }, 98 | "optional": { 99 | "LAYER_STACK": ("LIST",), 100 | }, 101 | } 102 | 103 | RETURN_TYPES = ("LIST",) 104 | FUNCTION = "define_transformer_layer" 105 | CATEGORY = "NNT Neural Network Toolkit/Transformers" 106 | 107 | def define_transformer_layer(self, d_model, nhead, dim_feedforward, dropout, 108 | activation, batch_first, norm_first, LAYER_STACK=None): 109 | if LAYER_STACK is None: 110 | LAYER_STACK = [] 111 | else: 112 | LAYER_STACK = LAYER_STACK.copy() 113 | 114 | layer = { 115 | 'type': 'TransformerEncoder', 116 | 'd_model': d_model, 117 | 'nhead': nhead, 118 | 'dim_feedforward': dim_feedforward, 119 | 'dropout': dropout, 120 | 'activation': activation, 121 | 'batch_first': batch_first == "True", 122 | 'norm_first': norm_first == "True" 123 | } 124 | 125 | LAYER_STACK.append(layer) 126 | return (LAYER_STACK,) 127 | 128 | class NntDefineVanillaAttention: 129 | @classmethod 130 | def INPUT_TYPES(cls): 131 | return { 132 | "required": { 133 | "embed_dim": ("INT", MODEL_DIM_CONFIG["embed_dim"]), 134 | "attention_type": (ATTENTION_TYPES, { 135 | "default": "scaled_dot_product" 136 | }), 137 | "dropout": ("FLOAT", ATTENTION_CONFIG["dropout"]), 138 | "use_bias": (["True", "False"], { 139 | "default": "True" 140 | }), 141 | "add_zero_attn": (["True", "False"], { 142 | "default": "False" 143 | }), 144 | "batch_first": (["True", "False"], { 145 | "default": "True" 146 | }), 147 | }, 148 | "optional": { 149 | "LAYER_STACK": ("LIST",), 150 | }, 151 | } 152 | 153 | RETURN_TYPES = ("LIST",) 154 | FUNCTION = "define_vanilla_attention" 155 | CATEGORY = "NNT Neural Network Toolkit/Transformers" 156 | 157 | def define_vanilla_attention(self, embed_dim, attention_type, dropout, use_bias, 158 | add_zero_attn, batch_first, LAYER_STACK=None): 159 | if LAYER_STACK is None: 160 | LAYER_STACK = [] 161 | else: 162 | LAYER_STACK = LAYER_STACK.copy() 163 | 164 | layer = { 165 | 'type': 'VanillaAttention', 166 | 'embed_dim': embed_dim, 167 | 'attention_type': attention_type, 168 | 'dropout': dropout, 169 | 'use_bias': use_bias == "True", 170 | 'add_zero_attn': add_zero_attn == "True", 171 | 'batch_first': batch_first == "True" 172 | } 173 | 174 | LAYER_STACK.append(layer) 175 | return (LAYER_STACK,) 176 | 177 | class NntDefineLinearAttention: 178 | @classmethod 179 | def INPUT_TYPES(cls): 180 | return { 181 | "required": { 182 | "embed_dim": ("INT", MODEL_DIM_CONFIG["embed_dim"]), 183 | "num_heads": ("INT", ATTENTION_CONFIG["num_heads"]), 184 | "feature_map": (["elu", "relu", "softmax"], { 185 | "default": "elu" 186 | }), 187 | "eps": ("FLOAT", { 188 | "default": 1e-6, 189 | "min": 1e-12, 190 | "max": 1e-3, 191 | "step": 1e-6 192 | }), 193 | "causal": (["True", "False"], { 194 | "default": "False" 195 | }), 196 | "dropout": ("FLOAT", ATTENTION_CONFIG["dropout"]), 197 | "batch_first": (["True", "False"], { 198 | "default": "True" 199 | }), 200 | }, 201 | "optional": { 202 | "LAYER_STACK": ("LIST",), 203 | }, 204 | } 205 | 206 | RETURN_TYPES = ("LIST",) 207 | FUNCTION = "define_linear_attention" 208 | CATEGORY = "NNT Neural Network Toolkit/Transformers" 209 | 210 | def define_linear_attention(self, embed_dim, num_heads, feature_map, eps, 211 | causal, dropout, batch_first, LAYER_STACK=None): 212 | if LAYER_STACK is None: 213 | LAYER_STACK = [] 214 | else: 215 | LAYER_STACK = LAYER_STACK.copy() 216 | 217 | layer = { 218 | 'type': 'LinearAttention', 219 | 'embed_dim': embed_dim, 220 | 'num_heads': num_heads, 221 | 'feature_map': feature_map, 222 | 'eps': eps, 223 | 'causal': causal == "True", 224 | 'dropout': dropout, 225 | 'batch_first': batch_first == "True" 226 | } 227 | 228 | LAYER_STACK.append(layer) 229 | return (LAYER_STACK,) 230 | 231 | class NntDefineTransformerXLAttention: 232 | @classmethod 233 | def INPUT_TYPES(cls): 234 | return { 235 | "required": { 236 | "d_model": ("INT", MODEL_DIM_CONFIG["d_model"]), 237 | "num_heads": ("INT", ATTENTION_CONFIG["num_heads"]), 238 | "mem_len": ("INT", { 239 | "default": 512, 240 | "min": 0, 241 | "max": 2048, 242 | "step": 16 243 | }), 244 | "same_length": (["True", "False"], { 245 | "default": "False" 246 | }), 247 | "clamp_len": ("INT", { 248 | "default": -1, 249 | "min": -1, 250 | "max": 2048, 251 | "step": 1 252 | }), 253 | "dropout": ("FLOAT", ATTENTION_CONFIG["dropout"]), 254 | "batch_first": (["True", "False"], { 255 | "default": "True" 256 | }), 257 | }, 258 | "optional": { 259 | "LAYER_STACK": ("LIST",), 260 | }, 261 | } 262 | 263 | RETURN_TYPES = ("LIST",) 264 | FUNCTION = "define_transformer_xl_attention" 265 | CATEGORY = "NNT Neural Network Toolkit/Transformers" 266 | 267 | def define_transformer_xl_attention(self, d_model, num_heads, mem_len, same_length, 268 | clamp_len, dropout, batch_first, LAYER_STACK=None): 269 | if LAYER_STACK is None: 270 | LAYER_STACK = [] 271 | else: 272 | LAYER_STACK = LAYER_STACK.copy() 273 | 274 | layer = { 275 | 'type': 'TransformerXLAttention', 276 | 'd_model': d_model, 277 | 'num_heads': num_heads, 278 | 'mem_len': mem_len, 279 | 'same_length': same_length == "True", 280 | 'clamp_len': clamp_len, 281 | 'dropout': dropout, 282 | 'batch_first': batch_first == "True" 283 | } 284 | 285 | LAYER_STACK.append(layer) 286 | return (LAYER_STACK,) 287 | 288 | class NntDefineReformerAttention: 289 | @classmethod 290 | def INPUT_TYPES(cls): 291 | return { 292 | "required": { 293 | "embed_dim": ("INT", MODEL_DIM_CONFIG["embed_dim"]), 294 | "num_heads": ("INT", ATTENTION_CONFIG["num_heads"]), 295 | "num_buckets": ("INT", { 296 | "default": 32, 297 | "min": 8, 298 | "max": 128, 299 | "step": 8 300 | }), 301 | "bucket_size": ("INT", { 302 | "default": 64, 303 | "min": 16, 304 | "max": 256, 305 | "step": 16 306 | }), 307 | "num_hashes": ("INT", { 308 | "default": 8, 309 | "min": 1, 310 | "max": 16, 311 | "step": 1 312 | }), 313 | "causal": (["True", "False"], { 314 | "default": "False" 315 | }), 316 | "dropout": ("FLOAT", ATTENTION_CONFIG["dropout"]), 317 | "batch_first": (["True", "False"], { 318 | "default": "True" 319 | }), 320 | }, 321 | "optional": { 322 | "LAYER_STACK": ("LIST",), 323 | }, 324 | } 325 | 326 | RETURN_TYPES = ("LIST",) 327 | FUNCTION = "define_reformer_attention" 328 | CATEGORY = "NNT Neural Network Toolkit/Transformers" 329 | 330 | def define_reformer_attention(self, embed_dim, num_heads, num_buckets, bucket_size, 331 | num_hashes, causal, dropout, batch_first, LAYER_STACK=None): 332 | if LAYER_STACK is None: 333 | LAYER_STACK = [] 334 | else: 335 | LAYER_STACK = LAYER_STACK.copy() 336 | 337 | layer = { 338 | 'type': 'ReformerAttention', 339 | 'embed_dim': embed_dim, 340 | 'num_heads': num_heads, 341 | 'num_buckets': num_buckets, 342 | 'bucket_size': bucket_size, 343 | 'num_hashes': num_hashes, 344 | 'causal': causal == "True", 345 | 'dropout': dropout, 346 | 'batch_first': batch_first == "True" 347 | } 348 | 349 | LAYER_STACK.append(layer) 350 | return (LAYER_STACK,) 351 | 352 | class NntDefineLocalAttention: 353 | @classmethod 354 | def INPUT_TYPES(cls): 355 | return { 356 | "required": { 357 | "embed_dim": ("INT", MODEL_DIM_CONFIG["embed_dim"]), 358 | "num_heads": ("INT", ATTENTION_CONFIG["num_heads"]), 359 | "window_size": ("INT", ATTENTION_CONFIG["window_size"]), 360 | "look_behind": ("INT", { 361 | "default": 64, 362 | "min": 0, 363 | "max": 256, 364 | "step": 16 365 | }), 366 | "look_ahead": ("INT", { 367 | "default": 0, 368 | "min": 0, 369 | "max": 256, 370 | "step": 16 371 | }), 372 | "dropout": ("FLOAT", ATTENTION_CONFIG["dropout"]), 373 | "autopad": (["True", "False"], { 374 | "default": "True" 375 | }), 376 | "batch_first": (["True", "False"], { 377 | "default": "True" 378 | }), 379 | }, 380 | "optional": { 381 | "LAYER_STACK": ("LIST",), 382 | }, 383 | } 384 | 385 | RETURN_TYPES = ("LIST",) 386 | FUNCTION = "define_local_attention" 387 | CATEGORY = "NNT Neural Network Toolkit/Transformers" 388 | 389 | def define_local_attention(self, embed_dim, num_heads, window_size, look_behind, 390 | look_ahead, dropout, autopad, batch_first, LAYER_STACK=None): 391 | if LAYER_STACK is None: 392 | LAYER_STACK = [] 393 | else: 394 | LAYER_STACK = LAYER_STACK.copy() 395 | 396 | layer = { 397 | 'type': 'LocalAttention', 398 | 'embed_dim': embed_dim, 399 | 'num_heads': num_heads, 400 | 'window_size': window_size, 401 | 'look_behind': look_behind, 402 | 'look_ahead': look_ahead, 403 | 'dropout': dropout, 404 | 'autopad': autopad == "True", 405 | 'batch_first': batch_first == "True" 406 | } 407 | 408 | LAYER_STACK.append(layer) 409 | return (LAYER_STACK,) 410 | 411 | class NntDefinePositionalEncoding: 412 | @classmethod 413 | def INPUT_TYPES(cls): 414 | return { 415 | "required": { 416 | "d_model": ("INT", MODEL_DIM_CONFIG["d_model"]), 417 | "max_seq_length": ("INT", MODEL_DIM_CONFIG["max_seq_length"]), 418 | "dropout": ("FLOAT", ATTENTION_CONFIG["dropout"]), 419 | "encoding_type": (TRANSFORMER_ENCODING_TYPES, { 420 | "default": "sinusoidal" 421 | }), 422 | "learnable": (["True", "False"], { 423 | "default": "False" 424 | }), 425 | "normalize": (["True", "False"], { 426 | "default": "True" 427 | }), 428 | }, 429 | "optional": { 430 | "LAYER_STACK": ("LIST",), 431 | }, 432 | } 433 | 434 | RETURN_TYPES = ("LIST",) 435 | FUNCTION = "define_positional_encoding" 436 | CATEGORY = "NNT Neural Network Toolkit/Transformers" 437 | 438 | def define_positional_encoding(self, d_model, max_seq_length, dropout, 439 | encoding_type, learnable, normalize, LAYER_STACK=None): 440 | if LAYER_STACK is None: 441 | LAYER_STACK = [] 442 | else: 443 | LAYER_STACK = LAYER_STACK.copy() 444 | 445 | layer = { 446 | 'type': 'PositionalEncoding', 447 | 'd_model': d_model, 448 | 'max_seq_length': max_seq_length, 449 | 'dropout': dropout, 450 | 'encoding_type': encoding_type, 451 | 'learnable': learnable == "True", 452 | 'normalize': normalize == "True" 453 | } 454 | 455 | LAYER_STACK.append(layer) 456 | return (LAYER_STACK,) 457 | 458 | class NntDefineMultiheadAttention: 459 | @classmethod 460 | def INPUT_TYPES(cls): 461 | return { 462 | "required": { 463 | "embed_dim": ("INT", MODEL_DIM_CONFIG["embed_dim"]), 464 | "num_heads": ("INT", ATTENTION_CONFIG["num_heads"]), 465 | "dropout": ("FLOAT", ATTENTION_CONFIG["dropout"]), 466 | "bias": (["True", "False"], { 467 | "default": "True" 468 | }), 469 | "add_bias_kv": (["True", "False"], { 470 | "default": "False" 471 | }), 472 | "add_zero_attn": (["True", "False"], { 473 | "default": "False" 474 | }), 475 | "batch_first": (["True", "False"], { 476 | "default": "True" 477 | }), 478 | "kdim": ("INT", { 479 | "default": 0, 480 | "min": 0, 481 | "max": 2048, 482 | "step": 64 483 | }), 484 | "vdim": ("INT", { 485 | "default": 0, 486 | "min": 0, 487 | "max": 2048, 488 | "step": 64 489 | }), 490 | }, 491 | "optional": { 492 | "LAYER_STACK": ("LIST",), 493 | }, 494 | } 495 | 496 | RETURN_TYPES = ("LIST",) 497 | FUNCTION = "define_attention" 498 | CATEGORY = "NNT Neural Network Toolkit/Transformers" 499 | 500 | def define_attention(self, embed_dim, num_heads, dropout, bias, add_bias_kv, 501 | add_zero_attn, batch_first, kdim, vdim, LAYER_STACK=None): 502 | if LAYER_STACK is None: 503 | LAYER_STACK = [] 504 | else: 505 | LAYER_STACK = LAYER_STACK.copy() 506 | 507 | layer = { 508 | 'type': 'MultiheadAttention', 509 | 'embed_dim': embed_dim, 510 | 'num_heads': num_heads, 511 | 'dropout': dropout, 512 | 'bias': bias == "True", 513 | 'add_bias_kv': add_bias_kv == "True", 514 | 'add_zero_attn': add_zero_attn == "True", 515 | 'batch_first': batch_first == "True", 516 | 'kdim': kdim if kdim > 0 else None, 517 | 'vdim': vdim if vdim > 0 else None 518 | } 519 | 520 | LAYER_STACK.append(layer) 521 | return (LAYER_STACK,) 522 | 523 | class NntDefineRelativePositionBias: 524 | @classmethod 525 | def INPUT_TYPES(cls): 526 | return { 527 | "required": { 528 | "num_buckets": ("INT", { 529 | "default": 32, 530 | "min": 8, 531 | "max": 128, 532 | "step": 8 533 | }), 534 | "max_distance": ("INT", { 535 | "default": 128, 536 | "min": 16, 537 | "max": 512, 538 | "step": 16 539 | }), 540 | "num_heads": ("INT", ATTENTION_CONFIG["num_heads"]), 541 | "causal": (["True", "False"], { 542 | "default": "False" 543 | }), 544 | }, 545 | "optional": { 546 | "LAYER_STACK": ("LIST",), 547 | }, 548 | } 549 | 550 | RETURN_TYPES = ("LIST",) 551 | FUNCTION = "define_relative_position_bias" 552 | CATEGORY = "NNT Neural Network Toolkit/Transformers" 553 | 554 | def define_relative_position_bias(self, num_buckets, max_distance, num_heads, 555 | causal, LAYER_STACK=None): 556 | if LAYER_STACK is None: 557 | LAYER_STACK = [] 558 | else: 559 | LAYER_STACK = LAYER_STACK.copy() 560 | 561 | layer = { 562 | 'type': 'RelativePositionBias', 563 | 'num_buckets': num_buckets, 564 | 'max_distance': max_distance, 565 | 'num_heads': num_heads, 566 | 'causal': causal == "True" 567 | } 568 | 569 | LAYER_STACK.append(layer) 570 | return (LAYER_STACK,) 571 | 572 | class NntDefineAlibiPositionalBias: 573 | @classmethod 574 | def INPUT_TYPES(cls): 575 | return { 576 | "required": { 577 | "num_heads": ("INT", ATTENTION_CONFIG["num_heads"]), 578 | "max_seq_length": ("INT", MODEL_DIM_CONFIG["max_seq_length"]), 579 | "causal": (["True", "False"], { 580 | "default": "False" 581 | }), 582 | "slope_multiplier": ("FLOAT", { 583 | "default": 1.0, 584 | "min": 0.1, 585 | "max": 10.0, 586 | "step": 0.1 587 | }), 588 | }, 589 | "optional": { 590 | "LAYER_STACK": ("LIST",), 591 | }, 592 | } 593 | 594 | RETURN_TYPES = ("LIST",) 595 | FUNCTION = "define_alibi_bias" 596 | CATEGORY = "NNT Neural Network Toolkit/Transformers" 597 | 598 | def define_alibi_bias(self, num_heads, max_seq_length, causal, 599 | slope_multiplier, LAYER_STACK=None): 600 | if LAYER_STACK is None: 601 | LAYER_STACK = [] 602 | else: 603 | LAYER_STACK = LAYER_STACK.copy() 604 | 605 | layer = { 606 | 'type': 'AlibiPositionalBias', 607 | 'num_heads': num_heads, 608 | 'max_seq_length': max_seq_length, 609 | 'causal': causal == "True", 610 | 'slope_multiplier': slope_multiplier 611 | } 612 | 613 | LAYER_STACK.append(layer) 614 | return (LAYER_STACK,) 615 | 616 | class NntDefineRotaryPositionalEmbedding: 617 | @classmethod 618 | def INPUT_TYPES(cls): 619 | return { 620 | "required": { 621 | "dim": ("INT", MODEL_DIM_CONFIG["d_model"]), 622 | "max_freq": ("FLOAT", { 623 | "default": 10.0, 624 | "min": 1.0, 625 | "max": 100.0, 626 | "step": 1.0 627 | }), 628 | "base": ("FLOAT", { 629 | "default": 10000.0, 630 | "min": 100.0, 631 | "max": 100000.0, 632 | "step": 100.0 633 | }), 634 | "interpolation_factor": ("FLOAT", { 635 | "default": 1.0, 636 | "min": 0.1, 637 | "max": 10.0, 638 | "step": 0.1 639 | }), 640 | }, 641 | "optional": { 642 | "LAYER_STACK": ("LIST",), 643 | }, 644 | } 645 | 646 | RETURN_TYPES = ("LIST",) 647 | FUNCTION = "define_rotary_embedding" 648 | CATEGORY = "NNT Neural Network Toolkit/Transformers" 649 | 650 | def define_rotary_embedding(self, dim, max_freq, base, 651 | interpolation_factor, LAYER_STACK=None): 652 | if LAYER_STACK is None: 653 | LAYER_STACK = [] 654 | else: 655 | LAYER_STACK = LAYER_STACK.copy() 656 | 657 | layer = { 658 | 'type': 'RotaryPositionalEmbedding', 659 | 'dim': dim, 660 | 'max_freq': max_freq, 661 | 'base': base, 662 | 'interpolation_factor': interpolation_factor 663 | } 664 | 665 | LAYER_STACK.append(layer) 666 | return (LAYER_STACK,) 667 | 668 | class NntTextBatchProcessor: 669 | @classmethod 670 | def INPUT_TYPES(cls): 671 | return { 672 | "required": { 673 | "texts": ("STRING", { 674 | "multiline": True, 675 | "default": "Text 1\n---\nText 2\n---\nText 3" 676 | }), 677 | "separator": ("STRING", { 678 | "default": "---", 679 | "multiline": False 680 | }), 681 | "max_length": ("INT", { 682 | "default": 256, 683 | "min": 16, 684 | "max": 2048, 685 | "step": 1 686 | }), 687 | "batch_size": ("INT", { 688 | "default": 32, 689 | "min": 1, 690 | "max": 512, 691 | "step": 1 692 | }), 693 | "tokenizer": (["bert-base-uncased", "distilbert-base-uncased"], { 694 | "default": "bert-base-uncased" 695 | }), 696 | "output_dtype": (["float32", "float64", "long", "int32"], { 697 | "default": "long" 698 | }) 699 | } 700 | } 701 | 702 | RETURN_TYPES = ("TENSOR", "INT", "STRING") 703 | RETURN_NAMES = ("token_batches", "num_batches", "info") 704 | FUNCTION = "process_batch" 705 | CATEGORY = "NNT Neural Network Toolkit/Text" 706 | 707 | def _convert_dtype(self, tensor, dtype_str): 708 | dtype_map = { 709 | "float32": torch.float32, 710 | "float64": torch.float64, 711 | "long": torch.long, 712 | "int32": torch.int32 713 | } 714 | return tensor.to(dtype_map[dtype_str]) 715 | 716 | def process_batch(self, texts, separator, max_length, batch_size, tokenizer, output_dtype): 717 | try: 718 | from transformers import AutoTokenizer 719 | import torch 720 | 721 | # Split texts 722 | text_list = [t.strip() for t in texts.split(separator) if t.strip()] 723 | 724 | # Initialize tokenizer 725 | tokenizer = AutoTokenizer.from_pretrained(tokenizer) 726 | 727 | # Process in batches 728 | all_batches = [] 729 | for i in range(0, len(text_list), batch_size): 730 | batch_texts = text_list[i:i + batch_size] 731 | inputs = tokenizer( 732 | batch_texts, 733 | max_length=max_length, 734 | padding='max_length', 735 | truncation=True, 736 | return_tensors='pt' 737 | ) 738 | # Convert to requested dtype 739 | all_batches.append(self._convert_dtype(inputs['input_ids'], output_dtype)) 740 | 741 | # Stack all batches 742 | if all_batches: 743 | batched_tokens = torch.cat(all_batches, dim=0) 744 | else: 745 | batched_tokens = torch.zeros(1, max_length, dtype=self._convert_dtype(torch.tensor([0]), output_dtype).dtype) 746 | 747 | info = f"Processed {len(text_list)} texts in {len(all_batches)} batches\n" 748 | info += f"Token shape: {batched_tokens.shape}\n" 749 | info += f"Output dtype: {output_dtype}\n" 750 | info += f"Tokenizer: {tokenizer.name_or_path}" 751 | 752 | return (batched_tokens, len(all_batches), info) 753 | 754 | except Exception as e: 755 | import traceback 756 | error_msg = f"Error processing batch: {str(e)}\n{traceback.format_exc()}" 757 | return (torch.zeros(1, max_length, dtype=self._convert_dtype(torch.tensor([0]), output_dtype).dtype), 0, error_msg) -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "nnt" 3 | description = "Neural Network Toolkit (NNT) for ComfyUI is an extensive set of custom ComfyUI nodes for designing, training, and fine-tuning neural networks. This toolkit allows defining models, layers, training workflows, transformers, and tensor operations in a visual manner using nodes." 4 | version = "1.0.3" 5 | license = {file = "LICENSE"} 6 | dependencies = ["# Core dependencies", "torch>=2.0.0", "numpy>=1.21.0", "pandas>=1.3.0", "matplotlib>=3.4.0", "scikit-learn>=1.0.0", "# Deep Learning and Model Tools", "transformers>=4.30.0", "datasets>=2.12.0", "onnx>=1.14.0", "safetensors>=0.3.1", "torchvision>=0.15.0", "# Time Series Analysis", "statsmodels>=0.13.0", "scipy>=1.7.0", "# Visualization", "seaborn>=0.11.0", "graphviz>=0.20.0", "torchview>=0.2.0", "# Audio Processing (optional)", "librosa>=0.10.0", "# Image Processing", "Pillow>=9.0.0", "# Machine Learning Interpretability", "shap>=0.41.0", "# Model saving and loading", "joblib>=1.1.0", "h5py>=3.7.0", "# HuggingFace Hub", "huggingface-hub>=0.16.0"] 7 | 8 | [project.urls] 9 | Repository = "https://github.com/inventorado/ComfyUI_NNT" 10 | # Used by Comfy Registry https://comfyregistry.org 11 | 12 | [tool.comfy] 13 | PublisherId = "inventorado" 14 | DisplayName = "ComfyUI Neural Network Toolkit NNT " 15 | Icon = "" 16 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # Core dependencies 2 | torch>=2.0.0 3 | numpy>=1.21.0 4 | pandas>=1.3.0 5 | matplotlib>=3.4.0 6 | scikit-learn>=1.0.0 7 | 8 | # Deep Learning and Model Tools 9 | transformers>=4.30.0 10 | datasets>=2.12.0 11 | onnx>=1.14.0 12 | safetensors>=0.3.1 13 | torchvision>=0.15.0 14 | 15 | # Time Series Analysis 16 | statsmodels>=0.13.0 17 | scipy>=1.7.0 18 | 19 | # Visualization 20 | seaborn>=0.11.0 21 | graphviz>=0.20.0 22 | torchview>=0.2.0 23 | 24 | # Image Processing 25 | Pillow>=9.0.0 26 | 27 | # Machine Learning Interpretability 28 | shap==0.41.0 29 | slicer>=0.0.7 # Required for shap 30 | numba>=0.55.1 # Required for shap 31 | cloudpickle>=2.2.0 # Required for shap 32 | 33 | # Audio Processing (optional) 34 | librosa>=0.10.0 35 | 36 | # Model saving and loading 37 | joblib>=1.1.0 38 | h5py>=3.7.0 39 | 40 | # HuggingFace Hub 41 | huggingface-hub>=0.16.0 42 | 43 | # Additional dependencies 44 | tqdm>=4.65.0 # Progress bars 45 | protobuf>=3.20.0 # Required for onnx -------------------------------------------------------------------------------- /workflows/NNT_conv_CIFAR10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inventorado/ComfyUI_NNT/baad4aba273f65f52868e060509c2e4769ce4ee9/workflows/NNT_conv_CIFAR10.png -------------------------------------------------------------------------------- /workflows/NNT_conv_MNIST.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inventorado/ComfyUI_NNT/baad4aba273f65f52868e060509c2e4769ce4ee9/workflows/NNT_conv_MNIST.png -------------------------------------------------------------------------------- /workflows/NNT_linear_regression.json: -------------------------------------------------------------------------------- 1 | { 2 | "last_node_id": 80, 3 | "last_link_id": 168, 4 | "nodes": [ 5 | { 6 | "id": 12, 7 | "type": "JjkShowText", 8 | "pos": [ 9 | 1946.7943115234375, 10 | -1190.1474609375 11 | ], 12 | "size": [ 13 | 425.01275634765625, 14 | 357.3470153808594 15 | ], 16 | "flags": {}, 17 | "order": 11, 18 | "mode": 0, 19 | "inputs": [ 20 | { 21 | "name": "text", 22 | "type": "STRING", 23 | "link": 40, 24 | "widget": { 25 | "name": "text" 26 | } 27 | } 28 | ], 29 | "outputs": [ 30 | { 31 | "name": "text", 32 | "type": "STRING", 33 | "links": null, 34 | "shape": 6 35 | } 36 | ], 37 | "title": "Model Script", 38 | "properties": { 39 | "Node name for S&R": "JjkShowText" 40 | }, 41 | "widgets_values": [ 42 | "import torch\nimport torch.nn as nn\nimport math\n\nclass GeneratedModel(nn.Sequential):\n def __init__(self):\n # Initialize layers\n self.input_shape = [1]\n\n self.linear0 = nn.Linear(\n in_features=1,\n out_features=32,\n bias=True\n )\n self.activation0 = nn.ReLU()\n\n self.linear1 = nn.Linear(\n in_features=32,\n out_features=32,\n bias=True\n )\n self.activation1 = nn.ReLU()\n\n self.linear2 = nn.Linear(\n in_features=32,\n out_features=1,\n bias=True\n )\n\n # Combine layers\n super().__init__(\n self.linear0,\n self.activation0,\n self.linear1,\n self.activation1,\n self.linear2,\n )\n\n# Example usage:\n# -----------------------------\n# model = GeneratedModel()\n# input_tensor = torch.randn(1, 1) # Example input tensor\n# output = model(input_tensor)\n# print(f'Input shape: {list(input_tensor.shape)}')\n# print(f'Output shape: {list(output.shape)}')" 43 | ] 44 | }, 45 | { 46 | "id": 15, 47 | "type": "JjkShowText", 48 | "pos": [ 49 | 2395.5498046875, 50 | -1299.7584228515625 51 | ], 52 | "size": [ 53 | 566.7725219726562, 54 | 436.4400329589844 55 | ], 56 | "flags": {}, 57 | "order": 12, 58 | "mode": 0, 59 | "inputs": [ 60 | { 61 | "name": "text", 62 | "type": "STRING", 63 | "link": 15, 64 | "widget": { 65 | "name": "text" 66 | } 67 | } 68 | ], 69 | "outputs": [ 70 | { 71 | "name": "text", 72 | "type": "STRING", 73 | "links": null, 74 | "shape": 6 75 | } 76 | ], 77 | "title": "Model Analysis", 78 | "properties": { 79 | "Node name for S&R": "JjkShowText" 80 | }, 81 | "widgets_values": [ 82 | "Model Analysis for input shape [1, 28, 28]:\nTotal Parameters: 1,153\nTrainable Parameters: 1,153\nMemory Usage:\n Parameters: 0.00 MB\n Buffers: 0.00 MB\n Total: 0.00 MB\n\nModel Architecture:\nLayer 0: Activation=Sequential\nLayer 1: Type=Linear, In Features=1, Out Features=32, Use Bias=True, Weight Init=default, Bias Init=default\nLayer 2: Activation=ReLU\nLayer 3: Type=Linear, In Features=32, Out Features=32, Use Bias=True, Weight Init=default, Bias Init=default\nLayer 4: Activation=ReLU\nLayer 5: Type=Linear, In Features=32, Out Features=1, Use Bias=True, Weight Init=default, Bias Init=default" 83 | ] 84 | }, 85 | { 86 | "id": 1, 87 | "type": "NntInputLayer", 88 | "pos": [ 89 | 1480.18994140625, 90 | -1946.6785888671875 91 | ], 92 | "size": [ 93 | 315, 94 | 58 95 | ], 96 | "flags": {}, 97 | "order": 0, 98 | "mode": 0, 99 | "inputs": [], 100 | "outputs": [ 101 | { 102 | "name": "LAYER_STACK", 103 | "type": "LIST", 104 | "links": [ 105 | 131 106 | ], 107 | "slot_index": 0 108 | } 109 | ], 110 | "properties": { 111 | "Node name for S&R": "NntInputLayer" 112 | }, 113 | "widgets_values": [ 114 | "[1]" 115 | ] 116 | }, 117 | { 118 | "id": 11, 119 | "type": "JjkShowText", 120 | "pos": [ 121 | 2580.087890625, 122 | -1830.6612548828125 123 | ], 124 | "size": [ 125 | 524.8604736328125, 126 | 320.6192626953125 127 | ], 128 | "flags": {}, 129 | "order": 8, 130 | "mode": 0, 131 | "inputs": [ 132 | { 133 | "name": "text", 134 | "type": "STRING", 135 | "link": 14, 136 | "widget": { 137 | "name": "text" 138 | } 139 | } 140 | ], 141 | "outputs": [ 142 | { 143 | "name": "text", 144 | "type": "STRING", 145 | "links": null, 146 | "shape": 6 147 | } 148 | ], 149 | "title": "Layer Stack Report", 150 | "properties": { 151 | "Node name for S&R": "JjkShowText" 152 | }, 153 | "widgets_values": [ 154 | "\nLayer 1: Type=Input | Shape=[1]\n\nLayer 2: Type=Linear | Nodes=32 | Activation=ReLU | Details: Use Bias=True, Weight Init=kaiming_normal, Init Gain=1.0, Init Mode=fan_in, Init NonLin=relu, Norm Eps=1e-05, Norm Momentum=0.1, Norm Affine=True\n\nLayer 3: Type=Linear | Nodes=32 | Activation=ReLU | Details: Use Bias=True, Weight Init=kaiming_normal, Init Gain=1.0, Init Mode=fan_in, Init NonLin=relu, Norm Eps=1e-05, Norm Momentum=0.1, Norm Affine=True\n\nLayer 4: Type=Linear | Nodes=1 | Activation=None | Details: Use Bias=True, Weight Init=kaiming_normal, Init Gain=1.0, Init Mode=fan_in, Init NonLin=relu, Norm Eps=1e-05, Norm Momentum=0.1, Norm Affine=True" 155 | ] 156 | }, 157 | { 158 | "id": 8, 159 | "type": "NntCompileModel", 160 | "pos": [ 161 | 1517.7828369140625, 162 | -1283.7760009765625 163 | ], 164 | "size": [ 165 | 400, 166 | 236 167 | ], 168 | "flags": {}, 169 | "order": 7, 170 | "mode": 0, 171 | "inputs": [ 172 | { 173 | "name": "LAYER_STACK", 174 | "type": "LIST", 175 | "link": 41 176 | }, 177 | { 178 | "name": "hyperparameters", 179 | "type": "DICT", 180 | "link": null, 181 | "shape": 7 182 | } 183 | ], 184 | "outputs": [ 185 | { 186 | "name": "model", 187 | "type": "MODEL", 188 | "links": [ 189 | 16, 190 | 150 191 | ], 192 | "slot_index": 0 193 | }, 194 | { 195 | "name": "report", 196 | "type": "STRING", 197 | "links": [] 198 | }, 199 | { 200 | "name": "script", 201 | "type": "STRING", 202 | "links": [ 203 | 40 204 | ], 205 | "slot_index": 2 206 | } 207 | ], 208 | "properties": { 209 | "Node name for S&R": "NntCompileModel" 210 | }, 211 | "widgets_values": [ 212 | "Compile", 213 | "ReLU", 214 | "None", 215 | "zeros", 216 | "kaiming_normal", 217 | "{}", 218 | [ 219 | false, 220 | true 221 | ] 222 | ] 223 | }, 224 | { 225 | "id": 14, 226 | "type": "NntAnalyzeModel", 227 | "pos": [ 228 | 1981.102783203125, 229 | -1320.96923828125 230 | ], 231 | "size": [ 232 | 315, 233 | 82 234 | ], 235 | "flags": {}, 236 | "order": 9, 237 | "mode": 0, 238 | "inputs": [ 239 | { 240 | "name": "MODEL", 241 | "type": "MODEL", 242 | "link": 16 243 | } 244 | ], 245 | "outputs": [ 246 | { 247 | "name": "STRING", 248 | "type": "STRING", 249 | "links": [ 250 | 15 251 | ] 252 | } 253 | ], 254 | "properties": { 255 | "Node name for S&R": "NntAnalyzeModel" 256 | }, 257 | "widgets_values": [ 258 | "[1,28, 28]", 259 | 1 260 | ] 261 | }, 262 | { 263 | "id": 13, 264 | "type": "NntShowLayerStack", 265 | "pos": [ 266 | 2607.244873046875, 267 | -1960.485107421875 268 | ], 269 | "size": [ 270 | 315, 271 | 58 272 | ], 273 | "flags": {}, 274 | "order": 6, 275 | "mode": 0, 276 | "inputs": [ 277 | { 278 | "name": "LAYER_STACK", 279 | "type": "LIST", 280 | "link": 20 281 | } 282 | ], 283 | "outputs": [ 284 | { 285 | "name": "l", 286 | "type": "STRING", 287 | "links": [ 288 | 14 289 | ], 290 | "slot_index": 0 291 | } 292 | ], 293 | "properties": { 294 | "Node name for S&R": "NntShowLayerStack" 295 | }, 296 | "widgets_values": [ 297 | "Detailed" 298 | ] 299 | }, 300 | { 301 | "id": 21, 302 | "type": "PreviewImage", 303 | "pos": [ 304 | 1880.4833984375, 305 | -317.6536560058594 306 | ], 307 | "size": [ 308 | 425.15338134765625, 309 | 319.64093017578125 310 | ], 311 | "flags": {}, 312 | "order": 19, 313 | "mode": 0, 314 | "inputs": [ 315 | { 316 | "name": "images", 317 | "type": "IMAGE", 318 | "link": 26 319 | } 320 | ], 321 | "outputs": [], 322 | "title": "Training Metrics", 323 | "properties": { 324 | "Node name for S&R": "PreviewImage" 325 | }, 326 | "widgets_values": [] 327 | }, 328 | { 329 | "id": 69, 330 | "type": "NntTrainModel", 331 | "pos": [ 332 | 1502.57666015625, 333 | -576.2748413085938 334 | ], 335 | "size": [ 336 | 355.20001220703125, 337 | 646 338 | ], 339 | "flags": {}, 340 | "order": 10, 341 | "mode": 0, 342 | "inputs": [ 343 | { 344 | "name": "MODEL", 345 | "type": "MODEL", 346 | "link": 150 347 | }, 348 | { 349 | "name": "training_data", 350 | "type": "TENSOR", 351 | "link": 151 352 | }, 353 | { 354 | "name": "target_data", 355 | "type": "TENSOR", 356 | "link": 152 357 | }, 358 | { 359 | "name": "hyperparameters", 360 | "type": "DICT", 361 | "link": null, 362 | "shape": 7 363 | } 364 | ], 365 | "outputs": [ 366 | { 367 | "name": "model", 368 | "type": "MODEL", 369 | "links": [ 370 | 156 371 | ], 372 | "slot_index": 0 373 | }, 374 | { 375 | "name": "training_log", 376 | "type": "STRING", 377 | "links": [ 378 | 154 379 | ], 380 | "slot_index": 1 381 | }, 382 | { 383 | "name": "metrics", 384 | "type": "DICT", 385 | "links": [ 386 | 155 387 | ], 388 | "slot_index": 2 389 | } 390 | ], 391 | "properties": { 392 | "Node name for S&R": "NntTrainModel" 393 | }, 394 | "widgets_values": [ 395 | "training_experiment", 396 | 16, 397 | 100, 398 | "Adam", 399 | 0.0005, 400 | 0.0001, 401 | 0.9, 402 | "MSELoss", 403 | "mean", 404 | "False", 405 | "[]", 406 | 0, 407 | "False", 408 | "ReduceLROnPlateau", 409 | 3, 410 | 0.1, 411 | 0.000001, 412 | "True", 413 | 5, 414 | 0.001, 415 | "False", 416 | "[-1]", 417 | "False" 418 | ] 419 | }, 420 | { 421 | "id": 62, 422 | "type": "NntTextToTensor", 423 | "pos": [ 424 | 929.3640747070312, 425 | -633.7505493164062 426 | ], 427 | "size": [ 428 | 400, 429 | 200 430 | ], 431 | "flags": {}, 432 | "order": 1, 433 | "mode": 0, 434 | "inputs": [ 435 | { 436 | "name": "input_text", 437 | "type": "STRING", 438 | "link": null, 439 | "widget": { 440 | "name": "input_text" 441 | }, 442 | "shape": 7 443 | } 444 | ], 445 | "outputs": [ 446 | { 447 | "name": "TENSOR", 448 | "type": "TENSOR", 449 | "links": [ 450 | 151, 451 | 164, 452 | 166 453 | ], 454 | "slot_index": 0 455 | } 456 | ], 457 | "title": "NNT Text To Tensor X", 458 | "properties": { 459 | "Node name for S&R": "NntTextToTensor" 460 | }, 461 | "widgets_values": [ 462 | "float32", 463 | true, 464 | "cpu", 465 | "[[-5],[-4],[-3],[-2],[-1],[0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10]]", 466 | "", 467 | [ 468 | false, 469 | true 470 | ] 471 | ] 472 | }, 473 | { 474 | "id": 63, 475 | "type": "NntTextToTensor", 476 | "pos": [ 477 | 926.7279663085938, 478 | -360.1746826171875 479 | ], 480 | "size": [ 481 | 400, 482 | 200 483 | ], 484 | "flags": {}, 485 | "order": 2, 486 | "mode": 0, 487 | "inputs": [ 488 | { 489 | "name": "input_text", 490 | "type": "STRING", 491 | "link": null, 492 | "widget": { 493 | "name": "input_text" 494 | }, 495 | "shape": 7 496 | } 497 | ], 498 | "outputs": [ 499 | { 500 | "name": "TENSOR", 501 | "type": "TENSOR", 502 | "links": [ 503 | 152, 504 | 167 505 | ], 506 | "slot_index": 0 507 | } 508 | ], 509 | "title": "NNT Text To Tensor Y", 510 | "properties": { 511 | "Node name for S&R": "NntTextToTensor" 512 | }, 513 | "widgets_values": [ 514 | "float32", 515 | false, 516 | "cpu", 517 | "[[11],[9],[7],[5],[3],[1],[3],[5], [7], [9],[11],[13],[15],[17],[19],[21]]", 518 | "", 519 | [ 520 | false, 521 | true 522 | ] 523 | ] 524 | }, 525 | { 526 | "id": 80, 527 | "type": "JjkText", 528 | "pos": [ 529 | 931.6897583007812, 530 | -2027.9530029296875 531 | ], 532 | "size": [ 533 | 438.13824462890625, 534 | 474.7139587402344 535 | ], 536 | "flags": {}, 537 | "order": 3, 538 | "mode": 0, 539 | "inputs": [], 540 | "outputs": [ 541 | { 542 | "name": "text", 543 | "type": "STRING", 544 | "links": null 545 | } 546 | ], 547 | "title": "Workflow Description", 548 | "properties": { 549 | "Node name for S&R": "JjkText" 550 | }, 551 | "widgets_values": [ 552 | "This workflow demonstrates training a neural network to approximate a V-shaped function: y = abs(x) + 1\n\nThe network learns to map scalar inputs to their corresponding V-shaped outputs using:\n- Input: 16 data points from x=-5 to x=10\n- Target: V-shaped values following y = abs(x) + 1\n- Architecture: 3-layer network (1 → 32 → 32 → 1) with ReLU activations\n- Training: Adam optimizer, MSE loss, batch training\n\nCurrent configuration achieves MSE of ~0.004, showing excellent approximation of the non-linear function.\n\nExperiment suggestions:\n1. Architecture modifications:\n - Change number of hidden layers (try 1 or 3)\n - Adjust number of nodes (try 16 or 64)\n - Test different activation functions (try tanh or GELU)\n - Add dropout or batch normalization\n\n2. Training parameters:\n - Modify learning rate (try 0.001 or 0.0001)\n - Change batch size\n - Test different optimizers (try SGD or RMSprop)\n - Add weight decay for regularization\n \n3. Data modifications:\n - Change input range or number of points\n - Add noise to training data\n - Create different non-linear functions (try parabola or sine)\n\nThis workflow serves as a basic template for function approximation tasks and demonstrates\nthe capability of neural networks to learn non-linear relationships.", 553 | [ 554 | false, 555 | true 556 | ] 557 | ] 558 | }, 559 | { 560 | "id": 70, 561 | "type": "NntInference", 562 | "pos": [ 563 | 2462.094970703125, 564 | -679.666015625 565 | ], 566 | "size": [ 567 | 380.4000244140625, 568 | 286 569 | ], 570 | "flags": {}, 571 | "order": 13, 572 | "mode": 0, 573 | "inputs": [ 574 | { 575 | "name": "MODEL", 576 | "type": "MODEL", 577 | "link": 156 578 | }, 579 | { 580 | "name": "input_tensor", 581 | "type": "TENSOR", 582 | "link": 164 583 | } 584 | ], 585 | "outputs": [ 586 | { 587 | "name": "output_tensor", 588 | "type": "TENSOR", 589 | "links": [ 590 | 158, 591 | 165 592 | ], 593 | "slot_index": 0 594 | }, 595 | { 596 | "name": "confidence_scores", 597 | "type": "TENSOR", 598 | "links": [], 599 | "slot_index": 1 600 | }, 601 | { 602 | "name": "inference_info", 603 | "type": "STRING", 604 | "links": [ 605 | 160 606 | ], 607 | "slot_index": 2 608 | }, 609 | { 610 | "name": "metrics", 611 | "type": "DICT", 612 | "links": null 613 | } 614 | ], 615 | "properties": { 616 | "Node name for S&R": "NntInference" 617 | }, 618 | "widgets_values": [ 619 | "batch", 620 | 0, 621 | 32, 622 | "raw", 623 | "True", 624 | "cuda", 625 | "[]", 626 | "None" 627 | ] 628 | }, 629 | { 630 | "id": 78, 631 | "type": "NntPlotTensors", 632 | "pos": [ 633 | 2501.994384765625, 634 | -333.5119934082031 635 | ], 636 | "size": [ 637 | 316.3163757324219, 638 | 268.0643310546875 639 | ], 640 | "flags": {}, 641 | "order": 17, 642 | "mode": 0, 643 | "inputs": [ 644 | { 645 | "name": "x_tensor", 646 | "type": "TENSOR", 647 | "link": 166 648 | }, 649 | { 650 | "name": "y_tensor", 651 | "type": "TENSOR", 652 | "link": 167 653 | }, 654 | { 655 | "name": "y_tensor2", 656 | "type": "TENSOR", 657 | "link": 165, 658 | "shape": 7 659 | } 660 | ], 661 | "outputs": [ 662 | { 663 | "name": "IMAGE", 664 | "type": "IMAGE", 665 | "links": [ 666 | 168 667 | ] 668 | } 669 | ], 670 | "properties": { 671 | "Node name for S&R": "NntPlotTensors" 672 | }, 673 | "widgets_values": [ 674 | "scatter", 675 | "X Value", 676 | "Y Value", 677 | 800, 678 | 600, 679 | "False", 680 | "Yhat" 681 | ] 682 | }, 683 | { 684 | "id": 74, 685 | "type": "JjkShowText", 686 | "pos": [ 687 | 2872.977294921875, 688 | -675.5271606445312 689 | ], 690 | "size": [ 691 | 341.5340576171875, 692 | 96.3813705444336 693 | ], 694 | "flags": {}, 695 | "order": 18, 696 | "mode": 0, 697 | "inputs": [ 698 | { 699 | "name": "text", 700 | "type": "STRING", 701 | "link": 160, 702 | "widget": { 703 | "name": "text" 704 | } 705 | } 706 | ], 707 | "outputs": [ 708 | { 709 | "name": "text", 710 | "type": "STRING", 711 | "links": null, 712 | "shape": 6 713 | } 714 | ], 715 | "title": "Log", 716 | "properties": { 717 | "Node name for S&R": "JjkShowText" 718 | }, 719 | "widgets_values": [ 720 | "Inference completed on 16 samples\nProcessing time: 0.001s\nAverage confidence: 1.000\nOutput shape: [16, 1]" 721 | ] 722 | }, 723 | { 724 | "id": 72, 725 | "type": "NntTensorToText", 726 | "pos": [ 727 | 2868.791259765625, 728 | -523.1990356445312 729 | ], 730 | "size": [ 731 | 315, 732 | 106 733 | ], 734 | "flags": {}, 735 | "order": 16, 736 | "mode": 0, 737 | "inputs": [ 738 | { 739 | "name": "tensor", 740 | "type": "TENSOR", 741 | "link": 158 742 | } 743 | ], 744 | "outputs": [ 745 | { 746 | "name": "text_output", 747 | "type": "STRING", 748 | "links": [ 749 | 159 750 | ], 751 | "slot_index": 0 752 | } 753 | ], 754 | "properties": { 755 | "Node name for S&R": "NntTensorToText" 756 | }, 757 | "widgets_values": [ 758 | "plain_text", 759 | 4, 760 | 100 761 | ] 762 | }, 763 | { 764 | "id": 79, 765 | "type": "PreviewImage", 766 | "pos": [ 767 | 2863.052490234375, 768 | -347.6282958984375 769 | ], 770 | "size": [ 771 | 307.7291259765625, 772 | 256.1304626464844 773 | ], 774 | "flags": {}, 775 | "order": 22, 776 | "mode": 0, 777 | "inputs": [ 778 | { 779 | "name": "images", 780 | "type": "IMAGE", 781 | "link": 168 782 | } 783 | ], 784 | "outputs": [], 785 | "properties": { 786 | "Node name for S&R": "PreviewImage" 787 | }, 788 | "widgets_values": [] 789 | }, 790 | { 791 | "id": 73, 792 | "type": "JjkShowText", 793 | "pos": [ 794 | 3225.277099609375, 795 | -392.8951721191406 796 | ], 797 | "size": [ 798 | 365.89422607421875, 799 | 294.38818359375 800 | ], 801 | "flags": {}, 802 | "order": 21, 803 | "mode": 0, 804 | "inputs": [ 805 | { 806 | "name": "text", 807 | "type": "STRING", 808 | "link": 159, 809 | "widget": { 810 | "name": "text" 811 | } 812 | } 813 | ], 814 | "outputs": [ 815 | { 816 | "name": "text", 817 | "type": "STRING", 818 | "links": null, 819 | "shape": 6 820 | } 821 | ], 822 | "title": "Output", 823 | "properties": { 824 | "Node name for S&R": "JjkShowText" 825 | }, 826 | "widgets_values": [ 827 | "[[10.2435],\n [ 8.9257],\n [ 7.1438],\n [ 5.1206],\n [ 3.2185],\n [ 2.2866],\n [ 2.9942],\n [ 4.7896],\n [ 6.7192],\n [ 8.776 ],\n [10.865 ],\n [12.954 ],\n [15.0431],\n [17.0729],\n [19.0395],\n [21.0581]]" 828 | ] 829 | }, 830 | { 831 | "id": 10, 832 | "type": "JjkShowText", 833 | "pos": [ 834 | 1900.0418701171875, 835 | 62.550987243652344 836 | ], 837 | "size": [ 838 | 323.057861328125, 839 | 190.40328979492188 840 | ], 841 | "flags": {}, 842 | "order": 14, 843 | "mode": 0, 844 | "inputs": [ 845 | { 846 | "name": "text", 847 | "type": "STRING", 848 | "link": 154, 849 | "widget": { 850 | "name": "text" 851 | } 852 | } 853 | ], 854 | "outputs": [ 855 | { 856 | "name": "text", 857 | "type": "STRING", 858 | "links": null, 859 | "shape": 6 860 | } 861 | ], 862 | "title": "Training Log", 863 | "properties": { 864 | "Node name for S&R": "JjkShowText" 865 | }, 866 | "widgets_values": [ 867 | "Training Results (0.38s):\n--------------------------------------------------\nEpoch 1/100: MSE Loss = 11.7855\nEpoch 2/100: MSE Loss = 10.3805\nEpoch 3/100: MSE Loss = 9.1218\nEpoch 4/100: MSE Loss = 7.9928\nEpoch 5/100: MSE Loss = 6.9892\nEpoch 6/100: MSE Loss = 6.1103\nEpoch 7/100: MSE Loss = 5.3525\nEpoch 8/100: MSE Loss = 4.7116\nEpoch 9/100: MSE Loss = 4.1814\nEpoch 10/100: MSE Loss = 3.7551\nEpoch 11/100: MSE Loss = 3.4150\nEpoch 12/100: MSE Loss = 3.1565\nEpoch 13/100: MSE Loss = 2.9621\nEpoch 14/100: MSE Loss = 2.8155\nEpoch 15/100: MSE Loss = 2.7041\nEpoch 16/100: MSE Loss = 2.6156\nEpoch 17/100: MSE Loss = 2.5401\nEpoch 18/100: MSE Loss = 2.4691\nEpoch 19/100: MSE Loss = 2.3951\nEpoch 20/100: MSE Loss = 2.3146\nEpoch 21/100: MSE Loss = 2.2265\nEpoch 22/100: MSE Loss = 2.1314\nEpoch 23/100: MSE Loss = 2.0276\nEpoch 24/100: MSE Loss = 1.9174\nEpoch 25/100: MSE Loss = 1.8039\nEpoch 26/100: MSE Loss = 1.6901\nEpoch 27/100: MSE Loss = 1.5790\nEpoch 28/100: MSE Loss = 1.4736\nEpoch 29/100: MSE Loss = 1.3763\nEpoch 30/100: MSE Loss = 1.2889\nEpoch 31/100: MSE Loss = 1.2121\nEpoch 32/100: MSE Loss = 1.1460\nEpoch 33/100: MSE Loss = 1.0902\nEpoch 34/100: MSE Loss = 1.0435\nEpoch 35/100: MSE Loss = 1.0045\nEpoch 36/100: MSE Loss = 0.9712\nEpoch 37/100: MSE Loss = 0.9419\nEpoch 38/100: MSE Loss = 0.9147\nEpoch 39/100: MSE Loss = 0.8883\nEpoch 40/100: MSE Loss = 0.8616\nEpoch 41/100: MSE Loss = 0.8358\nEpoch 42/100: MSE Loss = 0.8098\nEpoch 43/100: MSE Loss = 0.7838\nEpoch 44/100: MSE Loss = 0.7580\nEpoch 45/100: MSE Loss = 0.7327\nEpoch 46/100: MSE Loss = 0.7083\nEpoch 47/100: MSE Loss = 0.6851\nEpoch 48/100: MSE Loss = 0.6633\nEpoch 49/100: MSE Loss = 0.6430\nEpoch 50/100: MSE Loss = 0.6241\nEpoch 51/100: MSE Loss = 0.6063\nEpoch 52/100: MSE Loss = 0.5893\nEpoch 53/100: MSE Loss = 0.5734\nEpoch 54/100: MSE Loss = 0.5590\nEpoch 55/100: MSE Loss = 0.5446\nEpoch 56/100: MSE Loss = 0.5302\nEpoch 57/100: MSE Loss = 0.5157\nEpoch 58/100: MSE Loss = 0.5011\nEpoch 59/100: MSE Loss = 0.4866\nEpoch 60/100: MSE Loss = 0.4722\nEpoch 61/100: MSE Loss = 0.4584\nEpoch 62/100: MSE Loss = 0.4452\nEpoch 63/100: MSE Loss = 0.4325\nEpoch 64/100: MSE Loss = 0.4204\nEpoch 65/100: MSE Loss = 0.4088\nEpoch 66/100: MSE Loss = 0.3976\nEpoch 67/100: MSE Loss = 0.3868\nEpoch 68/100: MSE Loss = 0.3758\nEpoch 69/100: MSE Loss = 0.3649\nEpoch 70/100: MSE Loss = 0.3541\nEpoch 71/100: MSE Loss = 0.3435\nEpoch 72/100: MSE Loss = 0.3333\nEpoch 73/100: MSE Loss = 0.3238\nEpoch 74/100: MSE Loss = 0.3147\nEpoch 75/100: MSE Loss = 0.3063\nEpoch 76/100: MSE Loss = 0.2983\nEpoch 77/100: MSE Loss = 0.2904\nEpoch 78/100: MSE Loss = 0.2825\nEpoch 79/100: MSE Loss = 0.2746\nEpoch 80/100: MSE Loss = 0.2670\nEpoch 81/100: MSE Loss = 0.2595\nEpoch 82/100: MSE Loss = 0.2526\nEpoch 83/100: MSE Loss = 0.2462\nEpoch 84/100: MSE Loss = 0.2399\nEpoch 85/100: MSE Loss = 0.2338\nEpoch 86/100: MSE Loss = 0.2278\nEpoch 87/100: MSE Loss = 0.2220\nEpoch 88/100: MSE Loss = 0.2162\nEpoch 89/100: MSE Loss = 0.2104\nEpoch 90/100: MSE Loss = 0.2047\nEpoch 91/100: MSE Loss = 0.1994\nEpoch 92/100: MSE Loss = 0.1945\nEpoch 93/100: MSE Loss = 0.1899\nEpoch 94/100: MSE Loss = 0.1855\nEpoch 95/100: MSE Loss = 0.1811\nEpoch 96/100: MSE Loss = 0.1768\nEpoch 97/100: MSE Loss = 0.1727\nEpoch 98/100: MSE Loss = 0.1686\nEpoch 99/100: MSE Loss = 0.1648\nEpoch 100/100: MSE Loss = 0.1611\n--------------------------------------------------\nFinal Loss: 0.1611, Best Loss: 0.1611\nFinal Learning Rate: 0.000500" 868 | ] 869 | }, 870 | { 871 | "id": 20, 872 | "type": "NntVisualizeTrainingMetrics", 873 | "pos": [ 874 | 1895.82177734375, 875 | -693.7979736328125 876 | ], 877 | "size": [ 878 | 378, 879 | 126 880 | ], 881 | "flags": {}, 882 | "order": 15, 883 | "mode": 0, 884 | "inputs": [ 885 | { 886 | "name": "metrics", 887 | "type": "DICT", 888 | "link": 155 889 | } 890 | ], 891 | "outputs": [ 892 | { 893 | "name": "IMAGE", 894 | "type": "IMAGE", 895 | "links": [ 896 | 26 897 | ] 898 | }, 899 | { 900 | "name": "STRING", 901 | "type": "STRING", 902 | "links": [ 903 | 27 904 | ], 905 | "slot_index": 1 906 | } 907 | ], 908 | "properties": { 909 | "Node name for S&R": "NntVisualizeTrainingMetrics" 910 | }, 911 | "widgets_values": [ 912 | 1024, 913 | 768, 914 | "all_metrics" 915 | ] 916 | }, 917 | { 918 | "id": 22, 919 | "type": "JjkShowText", 920 | "pos": [ 921 | 1890.637451171875, 922 | -513.4630126953125 923 | ], 924 | "size": [ 925 | 298.3199768066406, 926 | 150.43316650390625 927 | ], 928 | "flags": {}, 929 | "order": 20, 930 | "mode": 0, 931 | "inputs": [ 932 | { 933 | "name": "text", 934 | "type": "STRING", 935 | "link": 27, 936 | "widget": { 937 | "name": "text" 938 | } 939 | } 940 | ], 941 | "outputs": [ 942 | { 943 | "name": "text", 944 | "type": "STRING", 945 | "links": null, 946 | "shape": 6 947 | } 948 | ], 949 | "title": "Training Metrics", 950 | "properties": { 951 | "Node name for S&R": "JjkShowText" 952 | }, 953 | "widgets_values": [ 954 | "Training Metrics Summary:\n-------------------------\nFinal Loss: 0.1611\nBest Loss: 0.1611\nInitial LR: 0.000500\nFinal LR: 0.000500" 955 | ] 956 | }, 957 | { 958 | "id": 42, 959 | "type": "NntDefineDenseLayer", 960 | "pos": [ 961 | 1859.3665771484375, 962 | -1968.9541015625 963 | ], 964 | "size": [ 965 | 315, 966 | 438 967 | ], 968 | "flags": {}, 969 | "order": 4, 970 | "mode": 0, 971 | "inputs": [ 972 | { 973 | "name": "LAYER_STACK", 974 | "type": "LIST", 975 | "link": 131, 976 | "shape": 7 977 | } 978 | ], 979 | "outputs": [ 980 | { 981 | "name": "LAYER_STACK", 982 | "type": "LIST", 983 | "links": [ 984 | 122 985 | ], 986 | "slot_index": 0 987 | }, 988 | { 989 | "name": "num_nodes", 990 | "type": "INT", 991 | "links": null 992 | } 993 | ], 994 | "properties": { 995 | "Node name for S&R": "NntDefineDenseLayer" 996 | }, 997 | "widgets_values": [ 998 | 32, 999 | "ReLU", 1000 | "True", 1001 | "kaiming_normal", 1002 | 1, 1003 | "fan_in", 1004 | "relu", 1005 | "ones", 1006 | 0, 1007 | "None", 1008 | 0.00001, 1009 | 0.1, 1010 | "True", 1011 | 0, 1012 | 0.01, 1013 | 2 1014 | ] 1015 | }, 1016 | { 1017 | "id": 17, 1018 | "type": "NntDefineDenseLayer", 1019 | "pos": [ 1020 | 2225.26904296875, 1021 | -1965.5374755859375 1022 | ], 1023 | "size": [ 1024 | 315, 1025 | 438 1026 | ], 1027 | "flags": {}, 1028 | "order": 5, 1029 | "mode": 0, 1030 | "inputs": [ 1031 | { 1032 | "name": "LAYER_STACK", 1033 | "type": "LIST", 1034 | "link": 122, 1035 | "shape": 7 1036 | } 1037 | ], 1038 | "outputs": [ 1039 | { 1040 | "name": "LAYER_STACK", 1041 | "type": "LIST", 1042 | "links": [ 1043 | 20, 1044 | 41 1045 | ], 1046 | "slot_index": 0 1047 | }, 1048 | { 1049 | "name": "num_nodes", 1050 | "type": "INT", 1051 | "links": null 1052 | } 1053 | ], 1054 | "properties": { 1055 | "Node name for S&R": "NntDefineDenseLayer" 1056 | }, 1057 | "widgets_values": [ 1058 | 1, 1059 | "None", 1060 | "True", 1061 | "kaiming_normal", 1062 | 1, 1063 | "fan_in", 1064 | "relu", 1065 | "ones", 1066 | 0, 1067 | "None", 1068 | 0.00001, 1069 | 0.1, 1070 | "True", 1071 | 0, 1072 | 0.01, 1073 | 1 1074 | ] 1075 | } 1076 | ], 1077 | "links": [ 1078 | [ 1079 | 14, 1080 | 13, 1081 | 0, 1082 | 11, 1083 | 0, 1084 | "STRING" 1085 | ], 1086 | [ 1087 | 15, 1088 | 14, 1089 | 0, 1090 | 15, 1091 | 0, 1092 | "STRING" 1093 | ], 1094 | [ 1095 | 16, 1096 | 8, 1097 | 0, 1098 | 14, 1099 | 0, 1100 | "MODEL" 1101 | ], 1102 | [ 1103 | 20, 1104 | 17, 1105 | 0, 1106 | 13, 1107 | 0, 1108 | "LIST" 1109 | ], 1110 | [ 1111 | 26, 1112 | 20, 1113 | 0, 1114 | 21, 1115 | 0, 1116 | "IMAGE" 1117 | ], 1118 | [ 1119 | 27, 1120 | 20, 1121 | 1, 1122 | 22, 1123 | 0, 1124 | "STRING" 1125 | ], 1126 | [ 1127 | 40, 1128 | 8, 1129 | 2, 1130 | 12, 1131 | 0, 1132 | "STRING" 1133 | ], 1134 | [ 1135 | 41, 1136 | 17, 1137 | 0, 1138 | 8, 1139 | 0, 1140 | "LIST" 1141 | ], 1142 | [ 1143 | 122, 1144 | 42, 1145 | 0, 1146 | 17, 1147 | 0, 1148 | "LIST" 1149 | ], 1150 | [ 1151 | 131, 1152 | 1, 1153 | 0, 1154 | 42, 1155 | 0, 1156 | "LIST" 1157 | ], 1158 | [ 1159 | 150, 1160 | 8, 1161 | 0, 1162 | 69, 1163 | 0, 1164 | "MODEL" 1165 | ], 1166 | [ 1167 | 151, 1168 | 62, 1169 | 0, 1170 | 69, 1171 | 1, 1172 | "TENSOR" 1173 | ], 1174 | [ 1175 | 152, 1176 | 63, 1177 | 0, 1178 | 69, 1179 | 2, 1180 | "TENSOR" 1181 | ], 1182 | [ 1183 | 154, 1184 | 69, 1185 | 1, 1186 | 10, 1187 | 0, 1188 | "STRING" 1189 | ], 1190 | [ 1191 | 155, 1192 | 69, 1193 | 2, 1194 | 20, 1195 | 0, 1196 | "DICT" 1197 | ], 1198 | [ 1199 | 156, 1200 | 69, 1201 | 0, 1202 | 70, 1203 | 0, 1204 | "MODEL" 1205 | ], 1206 | [ 1207 | 158, 1208 | 70, 1209 | 0, 1210 | 72, 1211 | 0, 1212 | "TENSOR" 1213 | ], 1214 | [ 1215 | 159, 1216 | 72, 1217 | 0, 1218 | 73, 1219 | 0, 1220 | "STRING" 1221 | ], 1222 | [ 1223 | 160, 1224 | 70, 1225 | 2, 1226 | 74, 1227 | 0, 1228 | "STRING" 1229 | ], 1230 | [ 1231 | 164, 1232 | 62, 1233 | 0, 1234 | 70, 1235 | 1, 1236 | "TENSOR" 1237 | ], 1238 | [ 1239 | 165, 1240 | 70, 1241 | 0, 1242 | 78, 1243 | 2, 1244 | "TENSOR" 1245 | ], 1246 | [ 1247 | 166, 1248 | 62, 1249 | 0, 1250 | 78, 1251 | 0, 1252 | "TENSOR" 1253 | ], 1254 | [ 1255 | 167, 1256 | 63, 1257 | 0, 1258 | 78, 1259 | 1, 1260 | "TENSOR" 1261 | ], 1262 | [ 1263 | 168, 1264 | 78, 1265 | 0, 1266 | 79, 1267 | 0, 1268 | "IMAGE" 1269 | ] 1270 | ], 1271 | "groups": [ 1272 | { 1273 | "id": 1, 1274 | "title": "Training Data (Down)loading", 1275 | "bounding": [ 1276 | 895.2645874023438, 1277 | -721.7744750976562, 1278 | 485.5682678222656, 1279 | 646.4544677734375 1280 | ], 1281 | "color": "#3f789e", 1282 | "font_size": 24, 1283 | "flags": {} 1284 | }, 1285 | { 1286 | "id": 2, 1287 | "title": "Training", 1288 | "bounding": [ 1289 | 1446.56689453125, 1290 | -778.8362426757812, 1291 | 890.0584716796875, 1292 | 1044.245849609375 1293 | ], 1294 | "color": "#A88", 1295 | "font_size": 24, 1296 | "flags": {} 1297 | }, 1298 | { 1299 | "id": 3, 1300 | "title": "Compile Model", 1301 | "bounding": [ 1302 | 1488.9532470703125, 1303 | -1402.0770263671875, 1304 | 1488.9796142578125, 1305 | 589.4373779296875 1306 | ], 1307 | "color": "#b58b2a", 1308 | "font_size": 24, 1309 | "flags": {} 1310 | }, 1311 | { 1312 | "id": 4, 1313 | "title": "Define NN Layers", 1314 | "bounding": [ 1315 | 1402.089599609375, 1316 | -2075.822265625, 1317 | 1725.9791259765625, 1318 | 615.7461547851562 1319 | ], 1320 | "color": "#8A8", 1321 | "font_size": 24, 1322 | "flags": {} 1323 | }, 1324 | { 1325 | "id": 7, 1326 | "title": "NNT Linear Regression - V-shaped Function Approximation", 1327 | "bounding": [ 1328 | 1408.0574951171875, 1329 | -2201.8720703125, 1330 | 1255.240478515625, 1331 | 80 1332 | ], 1333 | "color": "#3f789e", 1334 | "font_size": 40, 1335 | "flags": {} 1336 | }, 1337 | { 1338 | "id": 8, 1339 | "title": "Inference/Testing", 1340 | "bounding": [ 1341 | 2424.606689453125, 1342 | -773.8356323242188, 1343 | 1192.913818359375, 1344 | 725.2371215820312 1345 | ], 1346 | "color": "#A88", 1347 | "font_size": 24, 1348 | "flags": {} 1349 | } 1350 | ], 1351 | "config": {}, 1352 | "extra": { 1353 | "ds": { 1354 | "scale": 0.826446280991736, 1355 | "offset": [ 1356 | -729.703352193144, 1357 | 2222.37104919489 1358 | ] 1359 | } 1360 | }, 1361 | "version": 0.4 1362 | } -------------------------------------------------------------------------------- /workflows/NNT_linear_regression.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inventorado/ComfyUI_NNT/baad4aba273f65f52868e060509c2e4769ce4ee9/workflows/NNT_linear_regression.png -------------------------------------------------------------------------------- /workflows/NNT_load_infer_MNIST.json: -------------------------------------------------------------------------------- 1 | { 2 | "last_node_id": 97, 3 | "last_link_id": 190, 4 | "nodes": [ 5 | { 6 | "id": 73, 7 | "type": "JjkShowText", 8 | "pos": [ 9 | 1512.5333251953125, 10 | -2567.87890625 11 | ], 12 | "size": [ 13 | 314.85723876953125, 14 | 164.4139862060547 15 | ], 16 | "flags": {}, 17 | "order": 4, 18 | "mode": 0, 19 | "inputs": [ 20 | { 21 | "name": "text", 22 | "type": "STRING", 23 | "link": 173, 24 | "widget": { 25 | "name": "text" 26 | } 27 | } 28 | ], 29 | "outputs": [ 30 | { 31 | "name": "text", 32 | "type": "STRING", 33 | "links": null, 34 | "shape": 6 35 | } 36 | ], 37 | "title": "Loading Log", 38 | "properties": { 39 | "Node name for S&R": "JjkShowText" 40 | }, 41 | "widgets_values": [ 42 | "Model loaded from D:\\AI\\MOJECOMFY\\ComfyUI_windows_portable\\ComfyUI\\models\\nnt_models\\MNIST_trained_model.pth" 43 | ] 44 | }, 45 | { 46 | "id": 88, 47 | "type": "JjkShowText", 48 | "pos": [ 49 | 2041.628662109375, 50 | -2194.4306640625 51 | ], 52 | "size": [ 53 | 294.73846435546875, 54 | 105.06466674804688 55 | ], 56 | "flags": {}, 57 | "order": 9, 58 | "mode": 0, 59 | "inputs": [ 60 | { 61 | "name": "text", 62 | "type": "STRING", 63 | "link": 180, 64 | "widget": { 65 | "name": "text" 66 | } 67 | } 68 | ], 69 | "outputs": [ 70 | { 71 | "name": "text", 72 | "type": "STRING", 73 | "links": null, 74 | "shape": 6 75 | } 76 | ], 77 | "properties": { 78 | "Node name for S&R": "JjkShowText" 79 | }, 80 | "widgets_values": [ 81 | "Inference completed on 1 samples\nProcessing time: 0.001s\nAverage confidence: 0.839\nOutput shape: [1, 10]" 82 | ] 83 | }, 84 | { 85 | "id": 84, 86 | "type": "NntTensorToText", 87 | "pos": [ 88 | 2436.859619140625, 89 | -2560.5751953125 90 | ], 91 | "size": [ 92 | 315, 93 | 106 94 | ], 95 | "flags": {}, 96 | "order": 7, 97 | "mode": 0, 98 | "inputs": [ 99 | { 100 | "name": "tensor", 101 | "type": "TENSOR", 102 | "link": 178 103 | } 104 | ], 105 | "outputs": [ 106 | { 107 | "name": "text_output", 108 | "type": "STRING", 109 | "links": [ 110 | 179 111 | ], 112 | "slot_index": 0 113 | } 114 | ], 115 | "properties": { 116 | "Node name for S&R": "NntTensorToText" 117 | }, 118 | "widgets_values": [ 119 | "formatted_text", 120 | 4, 121 | 100 122 | ] 123 | }, 124 | { 125 | "id": 78, 126 | "type": "NntInference", 127 | "pos": [ 128 | 2002.21044921875, 129 | -2573.375244140625 130 | ], 131 | "size": [ 132 | 380.4000244140625, 133 | 286 134 | ], 135 | "flags": {}, 136 | "order": 5, 137 | "mode": 0, 138 | "inputs": [ 139 | { 140 | "name": "MODEL", 141 | "type": "MODEL", 142 | "link": 177 143 | }, 144 | { 145 | "name": "input_tensor", 146 | "type": "TENSOR", 147 | "link": 176 148 | } 149 | ], 150 | "outputs": [ 151 | { 152 | "name": "output_tensor", 153 | "type": "TENSOR", 154 | "links": [ 155 | 178 156 | ], 157 | "slot_index": 0 158 | }, 159 | { 160 | "name": "confidence_scores", 161 | "type": "TENSOR", 162 | "links": [ 163 | 189 164 | ], 165 | "slot_index": 1 166 | }, 167 | { 168 | "name": "inference_info", 169 | "type": "STRING", 170 | "links": [ 171 | 180 172 | ], 173 | "slot_index": 2 174 | }, 175 | { 176 | "name": "metrics", 177 | "type": "DICT", 178 | "links": [ 179 | 187 180 | ], 181 | "slot_index": 3 182 | } 183 | ], 184 | "properties": { 185 | "Node name for S&R": "NntInference" 186 | }, 187 | "widgets_values": [ 188 | "single", 189 | 0, 190 | 1, 191 | "probabilities", 192 | "True", 193 | "cuda", 194 | "[]", 195 | "None" 196 | ] 197 | }, 198 | { 199 | "id": 96, 200 | "type": "NntVisualizeConfidenceScores", 201 | "pos": [ 202 | 2008.7713623046875, 203 | -1972.5482177734375 204 | ], 205 | "size": [ 206 | 390.5999755859375, 207 | 150 208 | ], 209 | "flags": {}, 210 | "order": 8, 211 | "mode": 0, 212 | "inputs": [ 213 | { 214 | "name": "confidence_scores", 215 | "type": "TENSOR", 216 | "link": 189 217 | } 218 | ], 219 | "outputs": [ 220 | { 221 | "name": "IMAGE", 222 | "type": "IMAGE", 223 | "links": [ 224 | 190 225 | ], 226 | "slot_index": 0 227 | }, 228 | { 229 | "name": "STRING", 230 | "type": "STRING", 231 | "links": null 232 | } 233 | ], 234 | "properties": { 235 | "Node name for S&R": "NntVisualizeConfidenceScores" 236 | }, 237 | "widgets_values": [ 238 | 1024, 239 | 768, 240 | "combined", 241 | 0.5 242 | ] 243 | }, 244 | { 245 | "id": 95, 246 | "type": "PreviewImage", 247 | "pos": [ 248 | 2837.328857421875, 249 | -2360.85986328125 250 | ], 251 | "size": [ 252 | 210, 253 | 246 254 | ], 255 | "flags": {}, 256 | "order": 14, 257 | "mode": 0, 258 | "inputs": [ 259 | { 260 | "name": "images", 261 | "type": "IMAGE", 262 | "link": 188 263 | } 264 | ], 265 | "outputs": [], 266 | "properties": { 267 | "Node name for S&R": "PreviewImage" 268 | }, 269 | "widgets_values": [] 270 | }, 271 | { 272 | "id": 94, 273 | "type": "NntAnalyzeInferenceMetrics", 274 | "pos": [ 275 | 2426.166259765625, 276 | -2125.17724609375 277 | ], 278 | "size": [ 279 | 365.4000244140625, 280 | 126 281 | ], 282 | "flags": {}, 283 | "order": 10, 284 | "mode": 0, 285 | "inputs": [ 286 | { 287 | "name": "metrics", 288 | "type": "DICT", 289 | "link": 187 290 | } 291 | ], 292 | "outputs": [ 293 | { 294 | "name": "IMAGE", 295 | "type": "IMAGE", 296 | "links": [ 297 | 188 298 | ] 299 | }, 300 | { 301 | "name": "STRING", 302 | "type": "STRING", 303 | "links": null 304 | } 305 | ], 306 | "properties": { 307 | "Node name for S&R": "NntAnalyzeInferenceMetrics" 308 | }, 309 | "widgets_values": [ 310 | 1024, 311 | 768, 312 | "combined" 313 | ] 314 | }, 315 | { 316 | "id": 87, 317 | "type": "JjkShowText", 318 | "pos": [ 319 | 2439.52392578125, 320 | -2384.2822265625 321 | ], 322 | "size": [ 323 | 303.8973388671875, 324 | 204.98123168945312 325 | ], 326 | "flags": {}, 327 | "order": 12, 328 | "mode": 0, 329 | "inputs": [ 330 | { 331 | "name": "text", 332 | "type": "STRING", 333 | "link": 179, 334 | "widget": { 335 | "name": "text" 336 | } 337 | } 338 | ], 339 | "outputs": [ 340 | { 341 | "name": "text", 342 | "type": "STRING", 343 | "links": null, 344 | "shape": 6 345 | } 346 | ], 347 | "properties": { 348 | "Node name for S&R": "JjkShowText" 349 | }, 350 | "widgets_values": [ 351 | "[[0.0004, 0.0004, 0.0000, 0.1605, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,\n 0.8387]]" 352 | ] 353 | }, 354 | { 355 | "id": 79, 356 | "type": "LoadImage", 357 | "pos": [ 358 | 1128.4766845703125, 359 | -2219.810302734375 360 | ], 361 | "size": [ 362 | 315, 363 | 314 364 | ], 365 | "flags": {}, 366 | "order": 0, 367 | "mode": 0, 368 | "inputs": [], 369 | "outputs": [ 370 | { 371 | "name": "IMAGE", 372 | "type": "IMAGE", 373 | "links": [ 374 | 175 375 | ], 376 | "slot_index": 0 377 | }, 378 | { 379 | "name": "MASK", 380 | "type": "MASK", 381 | "links": null 382 | } 383 | ], 384 | "properties": { 385 | "Node name for S&R": "LoadImage" 386 | }, 387 | "widgets_values": [ 388 | "large_nine.png", 389 | "image" 390 | ] 391 | }, 392 | { 393 | "id": 83, 394 | "type": "NntImageToTensor", 395 | "pos": [ 396 | 1516.781982421875, 397 | -2226.56494140625 398 | ], 399 | "size": [ 400 | 315, 401 | 154 402 | ], 403 | "flags": {}, 404 | "order": 3, 405 | "mode": 0, 406 | "inputs": [ 407 | { 408 | "name": "image", 409 | "type": "IMAGE", 410 | "link": 175 411 | } 412 | ], 413 | "outputs": [ 414 | { 415 | "name": "TENSOR", 416 | "type": "TENSOR", 417 | "links": [ 418 | 176, 419 | 185 420 | ], 421 | "slot_index": 0 422 | } 423 | ], 424 | "properties": { 425 | "Node name for S&R": "NntImageToTensor" 426 | }, 427 | "widgets_values": [ 428 | 28, 429 | 28, 430 | "True", 431 | "Grayscale", 432 | "False" 433 | ] 434 | }, 435 | { 436 | "id": 74, 437 | "type": "NntLoadModel", 438 | "pos": [ 439 | 1128.051513671875, 440 | -2549.447265625 441 | ], 442 | "size": [ 443 | 315, 444 | 150 445 | ], 446 | "flags": {}, 447 | "order": 1, 448 | "mode": 0, 449 | "inputs": [], 450 | "outputs": [ 451 | { 452 | "name": "model", 453 | "type": "MODEL", 454 | "links": [ 455 | 177 456 | ], 457 | "slot_index": 0 458 | }, 459 | { 460 | "name": "report", 461 | "type": "STRING", 462 | "links": [ 463 | 173 464 | ], 465 | "slot_index": 1 466 | } 467 | ], 468 | "properties": { 469 | "Node name for S&R": "NntLoadModel" 470 | }, 471 | "widgets_values": [ 472 | "MNIST_trained_model.pth", 473 | "", 474 | "PyTorch Model", 475 | "False" 476 | ] 477 | }, 478 | { 479 | "id": 97, 480 | "type": "PreviewImage", 481 | "pos": [ 482 | 2436.82177734375, 483 | -1943.3037109375 484 | ], 485 | "size": [ 486 | 210, 487 | 246 488 | ], 489 | "flags": {}, 490 | "order": 13, 491 | "mode": 0, 492 | "inputs": [ 493 | { 494 | "name": "images", 495 | "type": "IMAGE", 496 | "link": 190 497 | } 498 | ], 499 | "outputs": [], 500 | "properties": { 501 | "Node name for S&R": "PreviewImage" 502 | }, 503 | "widgets_values": [] 504 | }, 505 | { 506 | "id": 89, 507 | "type": "NntTensorElementToImage", 508 | "pos": [ 509 | 1535.230224609375, 510 | -2025.45166015625 511 | ], 512 | "size": [ 513 | 340.20001220703125, 514 | 202 515 | ], 516 | "flags": {}, 517 | "order": 6, 518 | "mode": 0, 519 | "inputs": [ 520 | { 521 | "name": "tensor", 522 | "type": "TENSOR", 523 | "link": 185 524 | } 525 | ], 526 | "outputs": [ 527 | { 528 | "name": "IMAGE", 529 | "type": "IMAGE", 530 | "links": [ 531 | 186 532 | ], 533 | "slot_index": 0 534 | } 535 | ], 536 | "properties": { 537 | "Node name for S&R": "NntTensorElementToImage" 538 | }, 539 | "widgets_values": [ 540 | 0, 541 | "RGB", 542 | "True", 543 | "False", 544 | 1, 545 | 28, 546 | 28 547 | ] 548 | }, 549 | { 550 | "id": 93, 551 | "type": "PreviewImage", 552 | "pos": [ 553 | 1601.4024658203125, 554 | -1773.5513916015625 555 | ], 556 | "size": [ 557 | 210, 558 | 246 559 | ], 560 | "flags": {}, 561 | "order": 11, 562 | "mode": 0, 563 | "inputs": [ 564 | { 565 | "name": "images", 566 | "type": "IMAGE", 567 | "link": 186 568 | } 569 | ], 570 | "outputs": [], 571 | "properties": { 572 | "Node name for S&R": "PreviewImage" 573 | }, 574 | "widgets_values": [] 575 | }, 576 | { 577 | "id": 75, 578 | "type": "JjkText", 579 | "pos": [ 580 | 370.58221435546875, 581 | -2580.73681640625 582 | ], 583 | "size": [ 584 | 662.6279907226562, 585 | 486.77655029296875 586 | ], 587 | "flags": {}, 588 | "order": 2, 589 | "mode": 0, 590 | "inputs": [], 591 | "outputs": [ 592 | { 593 | "name": "text", 594 | "type": "STRING", 595 | "links": null 596 | } 597 | ], 598 | "title": "Workflow Description", 599 | "properties": { 600 | "Node name for S&R": "JjkText" 601 | }, 602 | "widgets_values": [ 603 | "NNT Model Loading and Inference Example Workflow for MNIST\n\nThis workflow demonstrates how to load a trained neural network model and perform inference on a sample number image. It is designed to be a flexible example that can be adapted for different models and input types.\n\nSteps in the Workflow:\n\nModel Loading:\n\nThe trained model (created using another sample workflow) is loaded from the specified directory.\nThe default path for the model is: ComfyUI/models/nnt_models.\n\nInput Preparation:\n\nA sample image of a handwritten number (white digit on a black background) is provided.\nThe image is processed as follows:\nResized to 28×28 pixels to match the MNIST model's input size.\nConverted to Grayscale (single-channel image) for compatibility with the model's expected input format.\n\nTensor Preview:\n\nThe processed image is converted into a tensor and previewed to ensure it is correctly formatted for inference.\n\nModel Inference:\n\nThe tensor is fed into the trained model for prediction.\nThe model returns an output tensor, which represents probabilities for each digit (0–9). For example:\n[[0.0004, 0.0004, 0.0000, 0.1605, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.8387]]\nThe output tensor is interpreted as:\nThe model is 84% confident the input digit is \"9\".\nThere is also a 16% chance it is \"3\".\n\nInterpretation and Feedback:\n\nThe results are displayed, showing the predicted digit and confidence levels for further analysis or debugging." 604 | ] 605 | } 606 | ], 607 | "links": [ 608 | [ 609 | 173, 610 | 74, 611 | 1, 612 | 73, 613 | 0, 614 | "STRING" 615 | ], 616 | [ 617 | 175, 618 | 79, 619 | 0, 620 | 83, 621 | 0, 622 | "IMAGE" 623 | ], 624 | [ 625 | 176, 626 | 83, 627 | 0, 628 | 78, 629 | 1, 630 | "TENSOR" 631 | ], 632 | [ 633 | 177, 634 | 74, 635 | 0, 636 | 78, 637 | 0, 638 | "MODEL" 639 | ], 640 | [ 641 | 178, 642 | 78, 643 | 0, 644 | 84, 645 | 0, 646 | "TENSOR" 647 | ], 648 | [ 649 | 179, 650 | 84, 651 | 0, 652 | 87, 653 | 0, 654 | "STRING" 655 | ], 656 | [ 657 | 180, 658 | 78, 659 | 2, 660 | 88, 661 | 0, 662 | "STRING" 663 | ], 664 | [ 665 | 185, 666 | 83, 667 | 0, 668 | 89, 669 | 0, 670 | "TENSOR" 671 | ], 672 | [ 673 | 186, 674 | 89, 675 | 0, 676 | 93, 677 | 0, 678 | "IMAGE" 679 | ], 680 | [ 681 | 187, 682 | 78, 683 | 3, 684 | 94, 685 | 0, 686 | "DICT" 687 | ], 688 | [ 689 | 188, 690 | 94, 691 | 0, 692 | 95, 693 | 0, 694 | "IMAGE" 695 | ], 696 | [ 697 | 189, 698 | 78, 699 | 1, 700 | 96, 701 | 0, 702 | "TENSOR" 703 | ], 704 | [ 705 | 190, 706 | 96, 707 | 0, 708 | 97, 709 | 0, 710 | "IMAGE" 711 | ] 712 | ], 713 | "groups": [ 714 | { 715 | "id": 6, 716 | "title": "Inference", 717 | "bounding": [ 718 | 1960.54248046875, 719 | -2678.12744140625, 720 | 1123.3770751953125, 721 | 1035.0626220703125 722 | ], 723 | "color": "#8AA", 724 | "font_size": 24, 725 | "flags": {} 726 | }, 727 | { 728 | "id": 7, 729 | "title": "NNT Model Loading and Inference Example Workflow for MNIST", 730 | "bounding": [ 731 | 1116.7808837890625, 732 | -2813.18359375, 733 | 1266.5797119140625, 734 | 80 735 | ], 736 | "color": "#3f789e", 737 | "font_size": 40, 738 | "flags": {} 739 | }, 740 | { 741 | "id": 8, 742 | "title": "Load Trained Model", 743 | "bounding": [ 744 | 1100.5465087890625, 745 | -2683.1494140625, 746 | 792.96875, 747 | 340.9006652832031 748 | ], 749 | "color": "#88A", 750 | "font_size": 24, 751 | "flags": {} 752 | }, 753 | { 754 | "id": 9, 755 | "title": "Load and Prepare Image", 756 | "bounding": [ 757 | 1093.382568359375, 758 | -2308.281494140625, 759 | 838.7692260742188, 760 | 796.2186889648438 761 | ], 762 | "color": "#3f789e", 763 | "font_size": 24, 764 | "flags": {} 765 | } 766 | ], 767 | "config": {}, 768 | "extra": { 769 | "ds": { 770 | "scale": 0.5209868481924438, 771 | "offset": [ 772 | 263.0338039760523, 773 | 2959.1341721936055 774 | ] 775 | } 776 | }, 777 | "version": 0.4 778 | } -------------------------------------------------------------------------------- /workflows/NNT_load_infer_MNIST.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inventorado/ComfyUI_NNT/baad4aba273f65f52868e060509c2e4769ce4ee9/workflows/NNT_load_infer_MNIST.png -------------------------------------------------------------------------------- /workflows/rnn-FashionMNIST-autoencoder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inventorado/ComfyUI_NNT/baad4aba273f65f52868e060509c2e4769ce4ee9/workflows/rnn-FashionMNIST-autoencoder.png -------------------------------------------------------------------------------- /workflows/sample_data/MNIST_four.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inventorado/ComfyUI_NNT/baad4aba273f65f52868e060509c2e4769ce4ee9/workflows/sample_data/MNIST_four.png -------------------------------------------------------------------------------- /workflows/sample_data/MNIST_nine.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inventorado/ComfyUI_NNT/baad4aba273f65f52868e060509c2e4769ce4ee9/workflows/sample_data/MNIST_nine.png -------------------------------------------------------------------------------- /workflows/sample_data/MNIST_one.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inventorado/ComfyUI_NNT/baad4aba273f65f52868e060509c2e4769ce4ee9/workflows/sample_data/MNIST_one.png -------------------------------------------------------------------------------- /workflows/sample_data/hoodie.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inventorado/ComfyUI_NNT/baad4aba273f65f52868e060509c2e4769ce4ee9/workflows/sample_data/hoodie.jpg -------------------------------------------------------------------------------- /workflows/sample_data/large_nine.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inventorado/ComfyUI_NNT/baad4aba273f65f52868e060509c2e4769ce4ee9/workflows/sample_data/large_nine.png --------------------------------------------------------------------------------