Run this model with HF Jobs
Run houyuanchen/MT-Forcing on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/houyuanchen/MT-Forcing. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/houyuanchen/MT-Forcing on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use houyuanchen/MT-Forcing with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use houyuanchen/MT-Forcing with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline from diffusers.utils import load_image # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("houyuanchen/MT-Forcing", dtype=torch.bfloat16, device_map="cuda") prompt = "Turn this cat into a dog" input_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cat.png") image = pipe(image=input_image, prompt=prompt).images[0] - Notebooks
- Google Colab
- Kaggle
Publish a weights-only release with a concise model card
Browse filesFiles changed (18)
- README.md+12-83
- assets/method.pngDeleted
- assets/puppy-ours-01.webpDeleted
- assets/puppy-ours-03.webpDeleted
- assets/puppy-ours-08.webpDeleted
- assets/puppy-source.webpDeleted
- comfyui/LICENSEDeleted-674
- comfyui/comfy/checkpoint_convert.pyDeleted-31
- comfyui/comfy/ldm/sensenova/__init__.pyDeleted-1
- comfyui/comfy/ldm/sensenova/conditioning.pyDeleted-272
- comfyui/comfy/ldm/sensenova/model.pyDeleted-801
- comfyui/comfy/ldm/sensenova/sampling.pyDeleted-69
- comfyui/comfy/text_encoders/sensenova.pyDeleted-315
- comfyui/comfy_extras/nodes_sensenova.pyDeleted-530
- examples/comfyui_mt_forcing_3turn_api.jsonDeleted-198
- examples/mt_forcing_test_input.jpgDeleted
- examples/run_comfyui_workflow.pyDeleted-72
- scripts/convert_to_comfyui.pyDeleted-510
2 unmodified lines34567893 unmodified lines1314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041052 unmodified lineslicense: apache-2.0tags:- comfyui# Hub download accounting for direct downloads of the root-level UI checkpoint.- diffusers- image-editing- multi-turn-image-editing3 unmodified lines# MT Forcing**Multi-turn image editing with SenseNova U1.5 8B MoT** · BF16 · 35.07 GB[Project gallery](https://houyuanchen111.github.io/mt-forcing.github.io/#explore) · [Paper](https://arxiv.org/pdf/2610.25404) · [GitHub](https://github.com/houyuanchen111/MT-Forcing) · [Original checkpoint](./model.safetensors) · [ComfyUI v0.1 checkpoint](./SenseNova-U1.5-8B-MoT-MT-Forcing-BF16-v0.1-ComfyUI.safetensors)## A kitten across 15 edits<video controls playsinline loop muted preload="metadata" width="100%" poster="https://houyuanchen111.github.io/mt-forcing.github.io/videos/kitten_15turn_poster.webp" src="https://houyuanchen111.github.io/mt-forcing.github.io/videos/kitten_15turn_comparison_12s.mp4"></video>Both panels follow the same sequence of edits. **Left:** SenseNova U1.5. **Right:** SenseNova U1.5 with MT Forcing. [Open the video in a new tab](https://houyuanchen111.github.io/mt-forcing.github.io/videos/kitten_15turn_comparison_12s.mp4).## A puppy across eight edits| Source | Turn 1 · Teal quilt | Turn 3 · Gold collar tag | Turn 8 · Fairy lights || :---: | :---: | :---: | :---: ||  |  |  |  |The collar appears in the second edit. In the third, “add a round gold tag to the collar” refers to something that did not exist in the source image. MT Forcing carries the earlier instructions and images into each new turn. [Explore all eight edits](https://houyuanchen111.github.io/mt-forcing.github.io/#explore).## Run three edits in ComfyUIThe included portrait workflow changes a yellow shirt to sage green, replaces a copper mug with a navy ceramic one, then adds an ivory headband. Each turn saves its own image so you can inspect how well the earlier edits hold. [Input portrait](examples/mt_forcing_test_input.jpg) · [Three-turn API workflow](examples/comfyui_mt_forcing_3turn_api.json)### 1. Set up ComfyUIUse a fresh ComfyUI checkout at the revision below. Run these commands from the directory containing this model card. The two copy commands install the model code and the **multi-turn edit** option in the **SenseNova Conditioning** node.```bashgit clone https://github.com/Comfy-Org/ComfyUI.git ../ComfyUI-MT-ForcingCOMFY_DIR="$(cd ../ComfyUI-MT-Forcing && pwd)"git -C "$COMFY_DIR" checkout --detach 7c78b5641ab2d6cb7f7766a183a8a43a59de0a8bcp -R comfyui/comfy/. "$COMFY_DIR/comfy/"cp -R comfyui/comfy_extras/. "$COMFY_DIR/comfy_extras/"```Install the dependencies for this checkout using the [ComfyUI installation guide](https://docs.comfy.org/installation/manual_install).### 2. Place the checkpoint and input imageThe workflow uses **Load Checkpoint** (`CheckpointLoaderSimple`). The commands below link the [BF16 checkpoint](./SenseNova-U1.5-8B-MoT-MT-Forcing-BF16-v0.1-ComfyUI.safetensors) into the loader’s search directory and copy the portrait under the filename the workflow expects.```bashMODEL=SenseNova-U1.5-8B-MoT-MT-Forcing-BF16-v0.1-ComfyUI.safetensorsmkdir -p "$COMFY_DIR/models/checkpoints" "$COMFY_DIR/input"ln -s "$PWD/$MODEL" "$COMFY_DIR/models/checkpoints/$MODEL"cp examples/mt_forcing_test_input.jpg "$COMFY_DIR/input/"```### 3. Submit the workflowStart ComfyUI with `python main.py` from its checkout. In a second terminal, run the following command from this model repository.```bashpython examples/run_comfyui_workflow.py \--server http://127.0.0.1:8188 \--workflow examples/comfyui_mt_forcing_3turn_api.json```The three images appear under `ComfyUI-MT-Forcing/output/mt_forcing_native_verify/`. The example uses **8 Euler steps**, the **simple** scheduler, **CFG 1.0** and **shift 3.0** per turn.**Use your own image.** Place it in ComfyUI’s `input/` folder and set its filename in node `3` of the JSON. Edit the three instructions in nodes `10`, `20` and `30`. To add another turn, connect the preceding **SenseNova Conditioning** output to `task.previous` and the preceding **KSampler** output to `task.samples`.## How well do earlier edits hold?On MTEdit-Bench, the paper evaluates 100 sessions of eight edits each. At **turn eight**, content consistency scores **7.68/10** with MT Forcing and **3.22/10** with the SenseNova U1.5 baseline. The table gives the paper’s averages across **all eight turns**. [Paper, Tables 1–2](https://arxiv.org/html/2610.25404v2#S4) · [Per-turn results](https://houyuanchen111.github.io/mt-forcing.github.io/#results)| Model | Instruction following ↑ /10 | Content consistency ↑ /10 | Drift resistance ↑ /5 | Matched-point displacement ↓ || :--- | ---: | ---: | ---: | ---: || SenseNova U1.5 | 8.47 | 7.09 | 3.83 | 6.34 px || **+ MT Forcing** | **9.66** | **8.40** | **4.30** | **0.74 px** |## How MT Forcing is trainedDuring **Single-Turn Distribution Matching Distillation**, the student edits its own previous outputs. A teacher starts from the original image and applies the instructions accumulated so far in one pass. **Teacher-Forcing Guidance** uses reference edit sequences to teach the student which details should carry forward. Both are training procedures. At inference, ComfyUI runs the released checkpoint. [Method in the paper](https://arxiv.org/html/2610.25404v2#S3)## Checkpoint conversion and citationThe model file is ready to load. To reproduce it from the original weights, use the [conversion script](scripts/convert_to_comfyui.py) with `--input`, `--output` and `--dtype bf16`. Pass `--validate-comfyui /path/to/ComfyUI` to check tensor keys and shapes. The bundled ComfyUI source corresponds to commit `e77af5f591ae6cebbd554f157c3d4599ca8ef12b` and includes its [license](comfyui/LICENSE).```bibtex@misc{chen2026mtforcing,title = {{MT Forcing}: Towards Stable and Consistent Multi-Turn Image Editing with Autoregressive Diffusion},author = {Houyuan Chen and Fanzhou Wang and Xiangyu Fan and Zesong Qiu and Yukun Wei and Songlin Yang and Zhitao Yang and Lvmin Zhang and Pei Yang and Hao Zhao and Dahua Lin and Lei Yang and Anyi Rao},year = {2026},eprint = {2610.25404},archivePrefix = {arXiv},primaryClass = {cs.CV}}```2 unmodified lines3456783 unmodified lines12131415161718192021222324252627282930313233342 unmodified lineslicense: apache-2.0tags:- comfyui- diffusers- image-editing- multi-turn-image-editing3 unmodified lines# MT Forcing**Multi-turn image editing with SenseNova U1.5 8B MoT**MT Forcing edits an image over a sequence of instructions. Each turn uses the previous instructions and images so the model can build on earlier changes while preserving details outside the requested edit. [Paper](https://arxiv.org/pdf/2610.25404) · [Project gallery](https://houyuanchen111.github.io/mt-forcing.github.io/) · [Inference code](https://github.com/houyuanchen111/MT-Forcing)## Download the weightsBoth files contain BF16 weights for the same model. Choose the format your inference software expects.| Format | Download | Usage || --- | --- | --- || Original checkpoint | [model.safetensors · 35.07 GB](https://huggingface.co/houyuanchen/MT-Forcing/resolve/main/model.safetensors?download=true) | Load with the [MT Forcing inference code](https://github.com/houyuanchen111/MT-Forcing/blob/main/docs/INFERENCE.md). || ComfyUI v0.1 | [ComfyUI checkpoint · 35.07 GB](https://huggingface.co/houyuanchen/MT-Forcing/resolve/main/SenseNova-U1.5-8B-MoT-MT-Forcing-BF16-v0.1-ComfyUI.safetensors?download=true) | Place in `ComfyUI/models/checkpoints/` and select it in **Load Checkpoint**. Multi-turn editing requires **SenseNova Conditioning** with the **multi-turn edit** option. |## Fifteen edits to the same image<video controls playsinline loop muted preload="metadata" width="100%" poster="https://houyuanchen111.github.io/mt-forcing.github.io/videos/kitten_15turn_poster.webp" src="https://houyuanchen111.github.io/mt-forcing.github.io/videos/kitten_15turn_comparison_12s.mp4"></video>The left panel follows a kitten through 15 edits with SenseNova U1.5. The right panel follows the same instructions with MT Forcing. [Watch the comparison](https://houyuanchen111.github.io/mt-forcing.github.io/videos/kitten_15turn_comparison_12s.mp4).On MTEdit-Bench, content consistency at the eighth edit rises from **3.22/10** with SenseNova U1.5 to **7.68/10** with MT Forcing. [Per-turn results](https://houyuanchen111.github.io/mt-forcing.github.io/#results)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license forsoftware and other kinds of works.
The licenses for most software and other practical works are designedto take away your freedom to share and change the works. By contrast,the GNU General Public License is intended to guarantee your freedom toshare and change all versions of a program--to make sure it remains freesoftware for all its users. We, the Free Software Foundation, use theGNU General Public License for most of our software; it applies also toany other work released this way by its authors. You can apply it toyour programs, too.
When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthem if you wish), that you receive source code or can get it if youwant it, that you can change the software or use pieces of it in newfree programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying youthese rights or asking you to surrender the rights. Therefore, you havecertain responsibilities if you distribute copies of the software, or ifyou modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whethergratis or for a fee, you must pass on to the recipients the samefreedoms that you received. You must make sure that they, too, receiveor can get the source code. And you must show them these terms so theyknow their rights.
Developers that use the GNU GPL protect your rights with two steps:(1) assert copyright on the software, and (2) offer you this Licensegiving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explainsthat there is no warranty for this free software. For both users' andauthors' sake, the GPL requires that modified versions be marked aschanged, so that their problems will not be attributed erroneously toauthors of previous versions.
Some devices are designed to deny users access to install or runmodified versions of the software inside them, although the manufacturercan do so. This is fundamentally incompatible with the aim ofprotecting users' freedom to change the software. The systematicpattern of such abuse occurs in the area of products for individuals touse, which is precisely where it is most unacceptable. Therefore, wehave designed this version of the GPL to prohibit the practice for thoseproducts. If such problems arise substantially in other domains, westand ready to extend this provision to those domains in future versionsof the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.States should not allow patents to restrict development and use ofsoftware on general-purpose computers, but in those that do, we wish toavoid the special danger that patents applied to a free program couldmake it effectively proprietary. To prevent this, the GPL assures thatpatents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution andmodification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds ofworks, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under thisLicense. Each licensee is addressed as "you". "Licensees" and"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the workin a fashion requiring copyright permission, other than the making of anexact copy. The resulting work is called a "modified version" of theearlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work basedon the Program.
To "propagate" a work means to do anything with it that, withoutpermission, would make you directly or secondarily liable forinfringement under applicable copyright law, except executing it on acomputer or modifying a private copy. Propagation includes copying,distribution (with or without modification), making available to thepublic, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables otherparties to make or receive copies. Mere interaction with a user througha computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"to the extent that it includes a convenient and prominently visiblefeature that (1) displays an appropriate copyright notice, and (2)tells the user that there is no warranty for the work (except to theextent that warranties are provided), that licensees may convey thework under this License, and how to view a copy of this License. Ifthe interface presents a list of user commands or options, such as amenu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the workfor making modifications to it. "Object code" means any non-sourceform of a work.
A "Standard Interface" means an interface that either is an officialstandard defined by a recognized standards body, or, in the case ofinterfaces specified for a particular programming language, one thatis widely used among developers working in that language.
The "System Libraries" of an executable work include anything, otherthan the work as a whole, that (a) is included in the normal form ofpackaging a Major Component, but which is not part of that MajorComponent, and (b) serves only to enable use of the work with thatMajor Component, or to implement a Standard Interface for which animplementation is available to the public in source code form. A"Major Component", in this context, means a major essential component(kernel, window system, and so on) of the specific operating system(if any) on which the executable work runs, or a compiler used toproduce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means allthe source code needed to generate, install, and (for an executablework) run the object code and to modify the work, including scripts tocontrol those activities. However, it does not include the work'sSystem Libraries, or general-purpose tools or generally available freeprograms which are used unmodified in performing those activities butwhich are not part of the work. For example, Corresponding Sourceincludes interface definition files associated with source files forthe work, and the source code for shared libraries and dynamicallylinked subprograms that the work is specifically designed to require,such as by intimate data communication or control flow between thosesubprograms and other parts of the work.
The Corresponding Source need not include anything that userscan regenerate automatically from other parts of the CorrespondingSource.
The Corresponding Source for a work in source code form is thatsame work.
2. Basic Permissions.
All rights granted under this License are granted for the term ofcopyright on the Program, and are irrevocable provided the statedconditions are met. This License explicitly affirms your unlimitedpermission to run the unmodified Program. The output from running acovered work is covered by this License only if the output, given itscontent, constitutes a covered work. This License acknowledges yourrights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do notconvey, without conditions so long as your license otherwise remainsin force. You may convey covered works to others for the sole purposeof having them make modifications exclusively for you, or provide youwith facilities for running those works, provided that you comply withthe terms of this License in conveying all material for which you donot control copyright. Those thus making or running the covered worksfor you must do so exclusively on your behalf, under your directionand control, on terms that prohibit them from making any copies ofyour copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely underthe conditions stated below. Sublicensing is not allowed; section 10makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technologicalmeasure under any applicable law fulfilling obligations under article11 of the WIPO copyright treaty adopted on 20 December 1996, orsimilar laws prohibiting or restricting circumvention of suchmeasures.
When you convey a covered work, you waive any legal power to forbidcircumvention of technological measures to the extent such circumventionis effected by exercising rights under this License with respect tothe covered work, and you disclaim any intention to limit operation ormodification of the work as a means of enforcing, against the work'susers, your or third parties' legal rights to forbid circumvention oftechnological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as youreceive it, in any medium, provided that you conspicuously andappropriately publish on each copy an appropriate copyright notice;keep intact all notices stating that this License and anynon-permissive terms added in accord with section 7 apply to the code;keep intact all notices of the absence of any warranty; and give allrecipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications toproduce it from the Program, in the form of source code under theterms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independentworks, which are not by their nature extensions of the covered work,and which are not combined with it such as to form a larger program,in or on a volume of a storage or distribution medium, is called an"aggregate" if the compilation and its resulting copyright are notused to limit the access or legal rights of the compilation's usersbeyond what the individual works permit. Inclusion of a covered workin an aggregate does not cause this License to apply to the otherparts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the termsof sections 4 and 5, provided that you also convey themachine-readable Corresponding Source under the terms of this License,in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excludedfrom the Corresponding Source as a System Library, need not beincluded in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means anytangible personal property which is normally used for personal, family,or household purposes, or (2) anything designed or sold for incorporationinto a dwelling. In determining whether a product is a consumer product,doubtful cases shall be resolved in favor of coverage. For a particularproduct received by a particular user, "normally used" refers to atypical or common use of that class of product, regardless of the statusof the particular user or of the way in which the particular useractually uses, or expects or is expected to use, the product. A productis a consumer product regardless of whether the product has substantialcommercial, industrial or non-consumer uses, unless such uses representthe only significant mode of use of the product.
"Installation Information" for a User Product means any methods,procedures, authorization keys, or other information required to installand execute modified versions of a covered work in that User Product froma modified version of its Corresponding Source. The information mustsuffice to ensure that the continued functioning of the modified objectcode is in no case prevented or interfered with solely becausemodification has been made.
If you convey an object code work under this section in, or with, orspecifically for use in, a User Product, and the conveying occurs aspart of a transaction in which the right of possession and use of theUser Product is transferred to the recipient in perpetuity or for afixed term (regardless of how the transaction is characterized), theCorresponding Source conveyed under this section must be accompaniedby the Installation Information. But this requirement does not applyif neither you nor any third party retains the ability to installmodified object code on the User Product (for example, the work hasbeen installed in ROM).
The requirement to provide Installation Information does not include arequirement to continue to provide support service, warranty, or updatesfor a work that has been modified or installed by the recipient, or forthe User Product in which it has been modified or installed. Access to anetwork may be denied when the modification itself materially andadversely affects the operation of the network or violates the rules andprotocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,in accord with this section must be in a format that is publiclydocumented (and with an implementation available to the public insource code form), and must require no special password or key forunpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of thisLicense by making exceptions from one or more of its conditions.Additional permissions that are applicable to the entire Program shallbe treated as though they were included in this License, to the extentthat they are valid under applicable law. If additional permissionsapply only to part of the Program, that part may be used separatelyunder those permissions, but the entire Program remains governed bythis License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your optionremove any additional permissions from that copy, or from any part ofit. (Additional permissions may be written to require their ownremoval in certain cases when you modify the work.) You may placeadditional permissions on material, added by you to a covered work,for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material youadd to a covered work, you may (if authorized by the copyright holders ofthat material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "furtherrestrictions" within the meaning of section 10. If the Program as youreceived it, or any part of it, contains a notice stating that it isgoverned by this License along with a term that is a furtherrestriction, you may remove that term. If a license document containsa further restriction but permits relicensing or conveying under thisLicense, you may add to a covered work material governed by the termsof that license document, provided that the further restriction doesnot survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, youmust place, in the relevant source files, a statement of theadditional terms that apply to those files, or a notice indicatingwhere to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in theform of a separately written license, or stated as exceptions;the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expresslyprovided under this License. Any attempt otherwise to propagate ormodify it is void, and will automatically terminate your rights underthis License (including any patent licenses granted under the thirdparagraph of section 11).
However, if you cease all violation of this License, then yourlicense from a particular copyright holder is reinstated (a)provisionally, unless and until the copyright holder explicitly andfinally terminates your license, and (b) permanently, if the copyrightholder fails to notify you of the violation by some reasonable meansprior to 60 days after the cessation.
Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.
Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, you do not qualify to receive new licenses for the samematerial under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive orrun a copy of the Program. Ancillary propagation of a covered workoccurring solely as a consequence of using peer-to-peer transmissionto receive a copy likewise does not require acceptance. However,nothing other than this License grants you permission to propagate ormodify any covered work. These actions infringe copyright if you donot accept this License. Therefore, by modifying or propagating acovered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automaticallyreceives a license from the original licensors, to run, modify andpropagate that work, subject to this License. You are not responsiblefor enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of anorganization, or substantially all assets of one, or subdividing anorganization, or merging organizations. If propagation of a coveredwork results from an entity transaction, each party to thattransaction who receives a copy of the work also receives whateverlicenses to the work the party's predecessor in interest had or couldgive under the previous paragraph, plus a right to possession of theCorresponding Source of the work from the predecessor in interest, ifthe predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of therights granted or affirmed under this License. For example, you maynot impose a license fee, royalty, or other charge for exercise ofrights granted under this License, and you may not initiate litigation(including a cross-claim or counterclaim in a lawsuit) alleging thatany patent claim is infringed by making, using, selling, offering forsale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under thisLicense of the Program or a work on which the Program is based. Thework thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claimsowned or controlled by the contributor, whether already acquired orhereafter acquired, that would be infringed by some manner, permittedby this License, of making, using, or selling its contributor version,but do not include claims that would be infringed only as aconsequence of further modification of the contributor version. Forpurposes of this definition, "control" includes the right to grantpatent sublicenses in a manner consistent with the requirements ofthis License.
Each contributor grants you a non-exclusive, worldwide, royalty-freepatent license under the contributor's essential patent claims, tomake, use, sell, offer for sale, import and otherwise run, modify andpropagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any expressagreement or commitment, however denominated, not to enforce a patent(such as an express permission to practice a patent or covenant not tosue for patent infringement). To "grant" such a patent license to aparty means to make such an agreement or commitment not to enforce apatent against the party.
If you convey a covered work, knowingly relying on a patent license,and the Corresponding Source of the work is not available for anyoneto copy, free of charge and under the terms of this License, through apublicly available network server or other readily accessible means,then you must either (1) cause the Corresponding Source to be soavailable, or (2) arrange to deprive yourself of the benefit of thepatent license for this particular work, or (3) arrange, in a mannerconsistent with the requirements of this License, to extend the patentlicense to downstream recipients. "Knowingly relying" means you haveactual knowledge that, but for the patent license, your conveying thecovered work in a country, or your recipient's use of the covered workin a country, would infringe one or more identifiable patents in thatcountry that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction orarrangement, you convey, or propagate by procuring conveyance of, acovered work, and grant a patent license to some of the partiesreceiving the covered work authorizing them to use, propagate, modifyor convey a specific copy of the covered work, then the patent licenseyou grant is automatically extended to all recipients of the coveredwork and works based on it.
A patent license is "discriminatory" if it does not include withinthe scope of its coverage, prohibits the exercise of, or isconditioned on the non-exercise of one or more of the rights that arespecifically granted under this License. You may not convey a coveredwork if you are a party to an arrangement with a third party that isin the business of distributing software, under which you make paymentto the third party based on the extent of your activity of conveyingthe work, and under which the third party grants, to any of theparties who would receive the covered work from you, a discriminatorypatent license (a) in connection with copies of the covered workconveyed by you (or copies made from those copies), or (b) primarilyfor and in connection with specific products or compilations thatcontain the covered work, unless you entered into that arrangement,or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limitingany implied license or other defenses to infringement that mayotherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannot convey acovered work so as to satisfy simultaneously your obligations under thisLicense and any other pertinent obligations, then as a consequence you maynot convey it at all. For example, if you agree to terms that obligate youto collect a royalty for further conveying from those to whom you conveythe Program, the only way you could satisfy both those terms and thisLicense would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you havepermission to link or combine any covered work with a work licensedunder version 3 of the GNU Affero General Public License into a singlecombined work, and to convey the resulting work. The terms of thisLicense will continue to apply to the part which is the covered work,but the special requirements of the GNU Affero General Public License,section 13, concerning interaction through a network will apply to thecombination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions ofthe GNU General Public License from time to time. Such new versions willbe similar in spirit to the present version, but may differ in detail toaddress new problems or concerns.
Each version is given a distinguishing version number. If theProgram specifies that a certain numbered version of the GNU GeneralPublic License "or any later version" applies to it, you have theoption of following the terms and conditions either of that numberedversion or of any later version published by the Free SoftwareFoundation. If the Program does not specify a version number of theGNU General Public License, you may choose any version ever publishedby the Free Software Foundation.
If the Program specifies that a proxy can decide which futureversions of the GNU General Public License can be used, that proxy'spublic statement of acceptance of a version permanently authorizes youto choose that version for the Program.
Later license versions may give you additional or differentpermissions. However, no additional obligations are imposed on anyauthor or copyright holder as a result of your choosing to follow alater version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BYAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHTHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTYOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAMIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OFALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITINGWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYSTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANYGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THEUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OFDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRDPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OFSUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability providedabove cannot be given local legal effect according to their terms,reviewing courts shall apply local law that most closely approximatesan absolute waiver of all civil liability in connection with theProgram, unless a warranty or assumption of liability accompanies acopy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelystate the exclusion of warranty; and each file should have at leastthe "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a shortnotice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriateparts of the General Public License. Of course, your program's commandsmight be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,if any, to sign a "copyright disclaimer" for the program, if necessary.For more information on this, and how to apply and follow the GNU GPL, see<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your programinto proprietary programs. If your program is a subroutine library, youmay consider it more useful to permit linking proprietary applications withthe library. If this is what you want to do, use the GNU Lesser GeneralPublic License instead of this License. But first, please read<https://www.gnu.org/licenses/why-not-lgpl.html>.12345678910111213141516171819202122232425262728293031import torch
def convert_sensenova(state_dict, prefix): out = {} for key, value in state_dict.items(): name = key.removeprefix(prefix) if name.startswith("vision_model.") or (name.startswith("language_model.") and "_mot_gen" not in name): target = "text_encoders." name = name.replace("vision_model.embeddings.", "vision_model.", 1) else: target = "model.diffusion_model." name = name.removeprefix("language_model.model.").removeprefix("fm_modules.") name = name.replace("vision_model_mot_gen.embeddings.", "patch_embed.").replace("fm_head.", "head.").replace("_mot_gen", "") out[target + name] = value out["vae.pixel_space_vae"] = torch.tensor(1.0) return out
def convert_checkpoint(state_dict): sensenova_keys = ( "fm_modules.vision_model_mot_gen.embeddings.patch_embedding.weight", "fm_modules.fm_head.conv1.weight", "language_model.model.layers.0.self_attn.q_proj_mot_gen.weight", "language_model.model.embed_tokens.weight", "language_model.model.norm.weight", ) for prefix in ("", "model.diffusion_model."): if all(prefix + key in state_dict for key in sensenova_keys): return convert_sensenova(state_dict, prefix) return state_dict1"""SenseNova U1.5 model implementation."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272import torch
IMAGE_CONTEXT_ID = 151669IMAGE_START_ID = 151670IMAGE_END_ID = 151671IM_START_ID = 151644IM_END_ID = 151645THINK_START_ID = 151667THINK_END_ID = 151668THINK_SUFFIX_IDS = (271, IMAGE_START_ID)USER_ID = 872ASSISTANT_ID = 77091NEWLINE_ID = 198IMAGE_LABEL_ID = 1906HYPHEN_ID = 12DIGIT_ZERO_ID = 15COLON_ID = 25MERGED_PATCH_SIZE = 32
def preprocess_reference(image): if image.ndim == 3: image = image.unsqueeze(0) image = image[:, :, :, :3].movedim(-1, 1).float() if image.shape[1] == 0: image = image.new_zeros((image.shape[0], 3, *image.shape[-2:])) elif image.shape[1] < 3: repeats = (3 + image.shape[1] - 1) // image.shape[1] image = image.repeat(1, repeats, 1, 1)[:, :3] mean = image.new_tensor((0.485, 0.456, 0.406)).view(1, 3, 1, 1) std = image.new_tensor((0.229, 0.224, 0.225)).view(1, 3, 1, 1) return (image - mean) / std
def split_reference_batches(images): references = [] for image in images: if image.ndim == 3: image = image.unsqueeze(0) references.extend(image[index : index + 1] for index in range(image.shape[0])) return references
def preprocess_references(images): return [preprocess_reference(image) for image in split_reference_batches(images)]
def reference_grid(height, width, patch_size): return ( max(1, (height + patch_size - 1) // patch_size), max(1, (width + patch_size - 1) // patch_size), )
def image_token_mask(input_ids, *, starts_in_image=False): # Image-control IDs generated outside an image block remain text embeddings. positions = torch.arange(input_ids.shape[-1], device=input_ids.device) starts = torch.where(input_ids == IMAGE_START_ID, positions, -1).cummax(dim=-1).values if starts_in_image: starts = starts.clamp_min(0) ends = torch.where(input_ids == IMAGE_END_ID, positions, -1).cummax(dim=-1).values return (input_ids == IMAGE_CONTEXT_ID) & (starts > ends)
def prepare_prefix_inputs( input_ids, reference_images, patch_size, dtype, *, image_only=False, expand_images=True, generated_start=None,): reference_images = preprocess_references(reference_images) if reference_images else [] reference_grids = [ reference_grid(image.shape[-2], image.shape[-1], patch_size) for image in reference_images ] if reference_images and expand_images: input_ids = condition_input_ids(input_ids, reference_grids, image_only=image_only) values = input_ids[0].tolist() image_slots = [] in_image = False for token in values: if token == IMAGE_START_ID: in_image = True elif token == IMAGE_END_ID: in_image = False image_slots.append(token == IMAGE_CONTEXT_ID and in_image) text_start = len(values) if generated_start is None else generated_start expected_slots = sum(height * width for height, width in reference_grids) actual_slots = sum( token == IMAGE_CONTEXT_ID and (index < text_start or image_slots[index]) for index, token in enumerate(values) ) if actual_slots != expected_slots: raise ValueError( f"SenseNova prefix has {actual_slots} image context tokens, " f"but reference images require {expected_slots}." ) starts = [index for index, token in enumerate(values) if token == IMAGE_START_ID] ends = [ index for index, token in enumerate(values) if token == IMAGE_END_ID and (index < text_start or (index > 0 and image_slots[index - 1])) ] if starts and starts[-1] == len(values) - 1: starts.pop() if len(starts) != len(reference_grids) or len(ends) != len(reference_grids): raise ValueError("SenseNova prefix image blocks do not match its reference images.") for index, (start, end, (height, width)) in enumerate(zip(starts, ends, reference_grids), 1): if values[start + 1:end] != [IMAGE_CONTEXT_ID] * (height * width): raise ValueError( f"SenseNova prefix image block {index}: reference images " f"require {height * width} contiguous image context tokens." ) if not reference_images: return input_ids, None, None, None indexes = thw_indexes(input_ids, reference_grids) return input_ids, reference_images, indexes, block_causal_mask(indexes, dtype=dtype)
def _image_tokens(token_height, token_width): return ( [IMAGE_START_ID] + [IMAGE_CONTEXT_ID] * (token_height * token_width) + [IMAGE_END_ID] )
def expand_interleave_inputs( input_ids, reference_images, image_only, *, append_image_start=False, image_newline=True): references = split_reference_batches(reference_images or []) if references or image_only: reference_grids = [ reference_grid(image.shape[-3], image.shape[-2], MERGED_PATCH_SIZE) for image in references ] input_ids = condition_input_ids( input_ids, reference_grids, image_only=image_only, append_image_start=append_image_start, image_labels=False, image_newline=image_newline, ) return input_ids, references
def prepare_interleave_image(latent_samples): if latent_samples.ndim != 4 or latent_samples.shape[0] != 1: raise ValueError("SenseNova interleave requires one BCHW latent image per stage.") if latent_samples.shape[1] != 3: raise ValueError("SenseNova interleave requires a three-channel RGB pixel latent from KSampler.")
image = (latent_samples * 0.5 + 0.5).movedim(1, -1) token_height, token_width = reference_grid(*latent_samples.shape[-2:], MERGED_PATCH_SIZE) return [IMAGE_CONTEXT_ID] * (token_height * token_width) + [IMAGE_END_ID], image
def _image_label_tokens(index): digits = (DIGIT_ZERO_ID + int(digit) for digit in str(index + 1)) return (IMAGE_LABEL_ID, HYPHEN_ID, *digits, COLON_ID)
def condition_input_ids( input_ids, reference_grids, image_only=False, append_image_start=True, image_labels=True, image_newline=True): image_blocks = [_image_tokens(height, width) for height, width in reference_grids] if image_only: values = ( [IM_START_ID, USER_ID, NEWLINE_ID] + [token for block in image_blocks for token in block] + [ IM_END_ID, NEWLINE_ID, IM_START_ID, ASSISTANT_ID, NEWLINE_ID, ] + ([IMAGE_START_ID] if append_image_start else []) ) return torch.tensor([values], dtype=torch.long, device=input_ids.device)
values = input_ids[0].tolist() starts = [index for index, value in enumerate(values) if value == IM_START_ID] insert_at = starts[1] + 3 if len(starts) > 1 else len(values) inserted = [] for index, block in enumerate(image_blocks): if image_labels and len(image_blocks) > 1: inserted.extend(_image_label_tokens(index)) inserted.extend(block) if image_newline: inserted.append(NEWLINE_ID) values[insert_at:insert_at] = inserted return torch.tensor([values], dtype=torch.long, device=input_ids.device)
def thw_indexes(input_ids, reference_grids, *, starts_in_image=False, start_time=0): values = input_ids[0] image_start_shift = torch.cat( ( torch.tensor([int(starts_in_image)], dtype=torch.long, device=values.device), (values == IMAGE_START_ID).long(), ) )[:-1] selected = image_token_mask(input_ids, starts_in_image=starts_in_image)[0] not_image = (~selected).long() time_indexes = (image_start_shift + not_image).cumsum(0) - 1 + start_time height_indexes = torch.zeros_like(time_indexes) width_indexes = torch.zeros_like(time_indexes) height_positions = [] width_positions = [] for token_height, token_width in reference_grids: positions = torch.arange( token_height * token_width, dtype=torch.long, device=values.device ) height_positions.append(positions // token_width) width_positions.append(positions % token_width) if height_positions: height_indexes[selected] = torch.cat(height_positions) width_indexes[selected] = torch.cat(width_positions) return torch.stack((time_indexes, height_indexes, width_indexes)).unsqueeze(0)
def block_causal_mask(time_indexes, dtype=torch.float32): values = time_indexes[0, 0] length = values.shape[0] same_block = values[:, None] == values[None, :] positions = torch.arange(length, device=values.device) causal = positions[None, :] <= positions[:, None] allowed = same_block | causal mask = torch.zeros((1, 1, length, length), dtype=dtype, device=values.device) return mask.masked_fill_(~allowed[None, None], float("-inf"))
def multi_turn_suffix_ids(turn_ids, image_tokens, *, image_only=False): if image_only: next_turn = [ IM_START_ID, USER_ID, NEWLINE_ID, IM_END_ID, NEWLINE_ID, IM_START_ID, ASSISTANT_ID, NEWLINE_ID, IMAGE_START_ID, ] else: values = turn_ids[0].tolist() starts = [index for index, value in enumerate(values) if value == IM_START_ID] user_start = starts[1] if len(starts) > 1 else 0 next_turn = values[user_start:] return turn_ids.new_tensor([*image_tokens, IM_END_ID, NEWLINE_ID, *next_turn]).unsqueeze(0)
def prepare_incremental_prefix_inputs( suffix_ids, reference_images, patch_size, dtype, *, past_length, start_time): references = preprocess_references(reference_images) if reference_images else [] reference_grids = [ reference_grid(image.shape[-2], image.shape[-1], patch_size) for image in references ] starts_in_image = bool(suffix_ids.shape[1] and int(suffix_ids[0, 0]) == IMAGE_CONTEXT_ID) indexes = thw_indexes( suffix_ids, reference_grids, starts_in_image=starts_in_image, start_time=start_time ) suffix_mask = block_causal_mask(indexes, dtype=dtype) if past_length > 0: past_zeros = suffix_mask.new_zeros((1, 1, suffix_ids.shape[1], past_length)) mask = torch.cat((past_zeros, suffix_mask), dim=-1) else: mask = suffix_mask return suffix_ids, references or None, indexes, mask123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801import torchimport torch.nn as nnimport torch.nn.functional as F
import comfy.patcher_extensionimport comfy.model_prefetchimport comfy.opsimport comfy.utilsfrom comfy.ldm.common_dit import pad_to_patch_sizefrom comfy.ldm.flux.math import apply_rope1from comfy.ldm.modules.attention import AttentionTensorContainer, ComfyAttention, optimized_attentionfrom comfy.ldm.modules.diffusionmodules.mmdit import TimestepEmbedderfrom comfy.text_encoders.llama import BaseGenerate, FixedKVfrom comfy.text_encoders.token_stream import report_generated_tokens
from .conditioning import IMAGE_CONTEXT_ID, IM_END_ID, MERGED_PATCH_SIZE, image_token_maskfrom .sampling import resolution_noise_scale
HIDDEN_SIZE = 4096INTERMEDIATE_SIZE = 12288NUM_LAYERS = 42NUM_HEADS = 32NUM_KV_HEADS = 8HEAD_DIM = 128VOCAB_SIZE = 151936
def _use_host_rows(embed): return ( hasattr(embed, "_v") and not (embed.weight.device.type == "cpu" and embed.weight.dtype in comfy.model_management.FLOAT8_TYPES) and embed.weight_lowvram_function is None and len(embed.weight_function) == 0 and comfy.ops.vbar_above_watermark(embed) )
def _pad_to_merged_patch_size(value): height, width = value.shape[-2:] height_pad = max(16 - height, 0) width_pad = max(16 - width, 0) if height_pad or width_pad: value = F.pad( value, (0, width_pad, 0, height_pad), mode="replicate" if height > 0 and width > 0 else "constant", ) return pad_to_patch_size(value, (MERGED_PATCH_SIZE, MERGED_PATCH_SIZE))
def _generation_batch_size(total_batch, prefix_batch): if prefix_batch < 1 or total_batch < 1 or total_batch % prefix_batch != 0: raise ValueError( "SenseNova generation batch must be a positive multiple of the prefix batch " f"(generation={total_batch}, prefix={prefix_batch})" ) return total_batch // prefix_batch
def _expand_prefix_batch(value, generation_batch): """Repeat each guidance branch's prefix KV for its generated variants.""" if generation_batch == 1: return value prefix_batch = value.shape[0] return ( value.unsqueeze(1) .expand(prefix_batch, generation_batch, *value.shape[1:]) .reshape(prefix_batch * generation_batch, *value.shape[1:]) )
def _prepare_llm_rope(positions, dim, theta, device, dtype): frequencies = theta ** ( -torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim ) positions = positions.to(device=device, dtype=torch.float32) if positions.ndim == 1: positions = positions.unsqueeze(0) angles = positions.unsqueeze(-1) * frequencies embedding = torch.cat((angles, angles), dim=-1).unsqueeze(1) return embedding.cos().to(dtype), embedding.sin().to(dtype)
def _prepare_mrope(indexes, device, dtype): return ( _prepare_llm_rope(indexes[0], HEAD_DIM // 2, 5000000.0, device, dtype), _prepare_llm_rope(indexes[1], HEAD_DIM // 4, 10000.0, device, dtype), _prepare_llm_rope(indexes[2], HEAD_DIM // 4, 10000.0, device, dtype), )
def _apply_llm_rope(query, key, rope): cosine, sine = rope
def rotate_half(value): first, second = value.chunk(2, dim=-1) return torch.cat((-second, first), dim=-1)
# Keep this split-half RoPE on the reference PyTorch formula. The # comfy-kitchen CUDA kernel is selected automatically on CUDA 13 builds; # on Blackwell it can return finite but numerically incorrect values, which # corrupts the generated image without raising an execution error. return ( query * cosine + rotate_half(query) * sine, key * cosine + rotate_half(key) * sine, )
def _apply_interleaved_rope(value, positions, theta): dim = value.shape[-1] frequencies = theta ** ( -torch.arange(0, dim, 2, dtype=torch.float32, device=value.device) / dim ) angles = ( positions.to(device=value.device, dtype=torch.float32).unsqueeze(-1) * frequencies ) cosine = angles.cos() sine = angles.sin() # comfy-kitchen acceleration backends use the canonical four-dimensional # input and six-dimensional rotation layout. SenseNova's vision patches # have no head axis, so add a singleton one instead of relying on the eager # backend's more permissive rank handling. rotation = torch.stack((cosine, -sine, sine, cosine), dim=-1).reshape( 1, 1, *angles.shape, 2, 2 ) return apply_rope1(value.float().unsqueeze(1), rotation).squeeze(1)
class VisionEmbeddings(nn.Module): def __init__(self, device=None, dtype=None, operations=None): super().__init__() self.patch_embedding = operations.Conv2d( 3, 1024, kernel_size=16, stride=16, device=device, dtype=dtype ) self.dense_embedding = operations.Conv2d( 1024, HIDDEN_SIZE, kernel_size=2, stride=2, device=device, dtype=dtype ) self.gelu = nn.GELU()
def forward(self, image): patches = self.gelu(self.patch_embedding(image)) batch, channels, height, width = patches.shape patches = patches.flatten(2).transpose(1, 2) indexes = torch.arange(height * width, device=patches.device) x_positions = indexes % width y_positions = indexes // width first = _apply_interleaved_rope( patches[..., : channels // 2], x_positions, 10000.0 ) second = _apply_interleaved_rope( patches[..., channels // 2 :], y_positions, 10000.0 ) patches = torch.cat((first, second), dim=-1).to(image.dtype) patches = patches.transpose(1, 2).reshape(batch, channels, height, width) patches = self.dense_embedding(patches) return patches.flatten(2).transpose(1, 2)
class MLP(nn.Module): def __init__(self, device=None, dtype=None, operations=None, combine_projections=False): super().__init__() self.gate_proj = operations.Linear( HIDDEN_SIZE, INTERMEDIATE_SIZE, bias=False, device=device, dtype=dtype ) self.up_proj = operations.Linear( HIDDEN_SIZE, INTERMEDIATE_SIZE, bias=False, device=device, dtype=dtype ) self.combined_gate_up = None if combine_projections: self.combined_gate_up = comfy.ops.CombinedLinear((self.gate_proj, self.up_proj)) self.combined_gate_up.comfy_gemv_optimized = True self.down_proj = operations.Linear( INTERMEDIATE_SIZE, HIDDEN_SIZE, bias=False, device=device, dtype=dtype )
def forward(self, hidden_states): if self.combined_gate_up is not None: gate_up = self.combined_gate_up.forward(hidden_states) if gate_up is not NotImplemented: return comfy.ops.linear_input_act(self.down_proj, gate_up, "swiglu") return self.down_proj(F.silu(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))
class Attention(nn.Module): def __init__(self, device=None, dtype=None, operations=None, combine_projections=False): super().__init__() self.comfy_attention = ComfyAttention() self.q_proj = operations.Linear(HIDDEN_SIZE, NUM_HEADS * HEAD_DIM, bias=False, device=device, dtype=dtype) self.k_proj = operations.Linear(HIDDEN_SIZE, NUM_KV_HEADS * HEAD_DIM, bias=False, device=device, dtype=dtype) self.v_proj = operations.Linear(HIDDEN_SIZE, NUM_KV_HEADS * HEAD_DIM, bias=False, device=device, dtype=dtype) self.combined_qkv = None if combine_projections: self.combined_qkv = comfy.ops.CombinedLinear((self.q_proj, self.k_proj, self.v_proj)) self.combined_qkv.comfy_gemv_optimized = True self.o_proj = operations.Linear(NUM_HEADS * HEAD_DIM, HIDDEN_SIZE, bias=False, device=device, dtype=dtype) self.q_norm = operations.RMSNorm(HEAD_DIM // 2, eps=1e-6, device=device, dtype=dtype) self.q_norm_hw = operations.RMSNorm(HEAD_DIM // 2, eps=1e-6, device=device, dtype=dtype) self.k_norm = operations.RMSNorm(HEAD_DIM // 2, eps=1e-6, device=device, dtype=dtype) self.k_norm_hw = operations.RMSNorm(HEAD_DIM // 2, eps=1e-6, device=device, dtype=dtype)
def _project(self, hidden_states, rope): batch, length, _ = hidden_states.shape qkv = self.combined_qkv.forward(hidden_states) if self.combined_qkv is not None else NotImplemented if qkv is NotImplemented: query, key, value = self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states) else: kv_size = NUM_KV_HEADS * HEAD_DIM query, key, value = qkv.split((NUM_HEADS * HEAD_DIM, kv_size, kv_size), dim=-1) query = query.view(batch, length, NUM_HEADS, HEAD_DIM) key = key.view(batch, length, NUM_KV_HEADS, HEAD_DIM) value = value.view(batch, length, NUM_KV_HEADS, HEAD_DIM).transpose(1, 2) query_t, query_hw = query.chunk(2, dim=-1) key_t, key_hw = key.chunk(2, dim=-1) query_t = self.q_norm(query_t).transpose(1, 2) query_hw = self.q_norm_hw(query_hw).transpose(1, 2) key_t = self.k_norm(key_t).transpose(1, 2) key_hw = self.k_norm_hw(key_hw).transpose(1, 2)
query_t, key_t = _apply_llm_rope(query_t, key_t, rope[0]) if len(rope) == 1: query = torch.cat((query_t, query_hw), dim=-1) key = torch.cat((key_t, key_hw), dim=-1) else: query_h, query_w = query_hw.chunk(2, dim=-1) key_h, key_w = key_hw.chunk(2, dim=-1) query_h, key_h = _apply_llm_rope(query_h, key_h, rope[1]) query_w, key_w = _apply_llm_rope(query_w, key_w, rope[2]) query = torch.cat((query_t, query_h, query_w), dim=-1) key = torch.cat((key_t, key_h, key_w), dim=-1) return query, key, value
def forward_prefix( self, hidden_states, rope, attention_mask, transformer_options, past_key=None, past_value=None, ): query, key, value = self._project(hidden_states, rope) if past_key is not None: key = torch.cat((past_key, key), dim=2) value = torch.cat((past_value, value), dim=2) query = AttentionTensorContainer(query) output = optimized_attention( query, AttentionTensorContainer(key), AttentionTensorContainer(value), NUM_HEADS, mask=attention_mask, skip_reshape=True, transformer_options=transformer_options, enable_gqa=True, preferred_attention=self.comfy_attention, ) return self.o_proj(output), key, value
def forward_generation( self, hidden_states, rope, prefix_key, prefix_value, transformer_options ): query, key, value = self._project(hidden_states, rope) key = torch.cat((prefix_key, key), dim=2) value = torch.cat((prefix_value, value), dim=2) query, key, value = AttentionTensorContainer(query), AttentionTensorContainer(key), AttentionTensorContainer(value) output = optimized_attention( query, key, value, NUM_HEADS, mask=None, skip_reshape=True, transformer_options=transformer_options, enable_gqa=True, preferred_attention=self.comfy_attention, ) return self.o_proj(output)
def forward_decode( self, hidden_states, rope, cache, attention_mask, transformer_options, ): query, key, value = self._project(hidden_states, rope) key, value = key.transpose(1, 2), value.transpose(1, 2) cache.key.index_copy_(1, cache.position, key) cache.value.index_copy_(1, cache.position, value) output = optimized_attention( AttentionTensorContainer(query), AttentionTensorContainer(cache.key.transpose(1, 2)), AttentionTensorContainer(cache.value.transpose(1, 2)), NUM_HEADS, mask=attention_mask, skip_reshape=True, transformer_options=transformer_options, enable_gqa=True, preferred_attention=self.comfy_attention, ) return self.o_proj(output)
class DecoderLayer(nn.Module): def __init__(self, device=None, dtype=None, operations=None, combine_projections=False): super().__init__() self.self_attn = Attention(device=device, dtype=dtype, operations=operations, combine_projections=combine_projections) self.mlp = MLP(device=device, dtype=dtype, operations=operations, combine_projections=combine_projections) self.input_layernorm = operations.RMSNorm(HIDDEN_SIZE, eps=1e-6, device=device, dtype=dtype) self.post_attention_layernorm = operations.RMSNorm(HIDDEN_SIZE, eps=1e-6, device=device, dtype=dtype)
def forward_prefix( self, prefix, prefix_rope, prefix_mask, transformer_options, past_key=None, past_value=None, ): prefix_attention, prefix_key, prefix_value = self.self_attn.forward_prefix( self.input_layernorm(prefix), prefix_rope, prefix_mask, transformer_options, past_key=past_key, past_value=past_value, ) prefix = prefix + prefix_attention prefix = prefix + self.mlp(self.post_attention_layernorm(prefix)) return prefix, prefix_key, prefix_value
def forward_generation( self, image, image_rope, prefix_key, prefix_value, transformer_options ): image_attention = self.self_attn.forward_generation( self.input_layernorm(image), image_rope, prefix_key, prefix_value, transformer_options, ) image = image + image_attention image = image + self.mlp(self.post_attention_layernorm(image)) return image
def forward_decode( self, hidden_states, rope, cache, attention_mask, transformer_options, ): attention = self.self_attn.forward_decode( self.input_layernorm(hidden_states), rope, cache, attention_mask, transformer_options, ) hidden_states = hidden_states + attention hidden_states = hidden_states + self.mlp( self.post_attention_layernorm(hidden_states) ) return hidden_states
class LanguageBackbone(nn.Module): def __init__(self, device=None, dtype=None, operations=None): super().__init__() self.embed_tokens = operations.Embedding(VOCAB_SIZE, HIDDEN_SIZE, padding_idx=151643, device=device, dtype=dtype) self.layers = nn.ModuleList( DecoderLayer(device=device, dtype=dtype, operations=operations, combine_projections=True) for _ in range(NUM_LAYERS) ) self.norm = operations.RMSNorm(HIDDEN_SIZE, eps=1e-6, device=device, dtype=dtype)
class LanguageModel(nn.Module): def __init__(self, has_lm_head=False, device=None, dtype=None, operations=None): super().__init__() self.model = LanguageBackbone(device=device, dtype=dtype, operations=operations) if has_lm_head: self.lm_head = operations.Linear(HIDDEN_SIZE, VOCAB_SIZE, bias=False, device=device, dtype=dtype)
class ConvDecoder(nn.Module): def __init__(self, device=None, dtype=None, operations=None): super().__init__() self.ps1 = nn.PixelShuffle(2) self.conv1 = operations.Conv2d( 1024, 1024, kernel_size=3, padding=1, device=device, dtype=dtype ) self.act1 = nn.GELU() self.ps2 = nn.PixelShuffle(2) self.conv2 = operations.Conv2d( 256, 192, kernel_size=3, padding=1, device=device, dtype=dtype ) self.ps3 = nn.PixelShuffle(8)
def forward(self, hidden_states): hidden_states = self.act1(self.conv1(self.ps1(hidden_states))) return self.ps3(self.conv2(self.ps2(hidden_states)))
class SenseNovaTextModel(nn.Module, BaseGenerate): def __init__(self, has_lm_head=False, device=None, dtype=None, operations=None): super().__init__() self.has_lm_head = has_lm_head self.vision_model = VisionEmbeddings(device=device, dtype=dtype, operations=operations) self.language_model = LanguageModel(has_lm_head=has_lm_head, device=device, dtype=dtype, operations=operations)
def _prepare_prefix( self, text_input_ids, reference_images, prefix_indexes, prefix_mask, text_suffix=None, compute_dtype=None ): prefix_length = text_input_ids.shape[1] all_ids = torch.cat((text_input_ids, text_suffix), dim=1) if text_suffix is not None else text_input_ids embed = self.language_model.model.embed_tokens if _use_host_rows(embed): prefix = embed.host_rows(all_ids, out_dtype=compute_dtype) else: prefix = embed(all_ids).to(dtype=compute_dtype) if reference_images: reference_embeds = [ self.vision_model(_pad_to_merged_patch_size(reference)) for reference in reference_images ] starts_in_image = bool(text_input_ids.shape[1] and int(text_input_ids[0, 0]) == IMAGE_CONTEXT_ID) selected = image_token_mask(text_input_ids, starts_in_image=starts_in_image) prefix = prefix.clone() prefix[:, :prefix_length][selected] = torch.cat(reference_embeds, dim=1).reshape( -1, HIDDEN_SIZE )
if prefix_indexes is None: prefix_positions = torch.arange( prefix_length, dtype=torch.long, device=prefix.device ) zeros = torch.zeros_like(prefix_positions) prefix_indexes = torch.stack((prefix_positions, zeros, zeros)) prefix_mask = torch.full( (prefix_length, prefix_length), float("-inf"), dtype=prefix.dtype, device=prefix.device, ).triu(1) prefix_time = torch.full( (prefix.shape[0],), prefix_length, dtype=torch.long, device=prefix.device, ) else: prefix_indexes = prefix_indexes.transpose(0, 1) prefix_time = prefix_indexes[0].amax(dim=-1) + 1
if text_suffix is not None: # Upstream appends thinking tokens as text, even when their IDs are image markers. suffix_length = text_suffix.shape[1] positions = prefix_time[:, None] + torch.arange(suffix_length, device=prefix.device) zeros = torch.zeros_like(positions) suffix_indexes = torch.stack((positions, zeros, zeros)) if prefix_indexes.ndim == 2: suffix_indexes = suffix_indexes[:, 0] prefix_indexes = torch.cat((prefix_indexes, suffix_indexes), dim=-1) length = prefix_length + suffix_length mask = torch.full( (*prefix_mask.shape[:-2], length, length), float("-inf"), dtype=prefix_mask.dtype, device=prefix.device, ).triu(1) mask[..., :prefix_length, :prefix_length] = prefix_mask prefix_mask = mask prefix_time = prefix_time + suffix_length
return prefix, prefix_indexes, prefix_mask, prefix_time
def _preprocess_prefix_state( self, text_input_ids, reference_images=None, prefix_indexes=None, prefix_mask=None, transformer_options=None, text_suffix=None, compute_dtype=None, interrupt=None, past_keys=None, past_values=None, ): prefix, prefix_indexes, prefix_mask, prefix_time = self._prepare_prefix( text_input_ids, reference_images, prefix_indexes, prefix_mask, text_suffix, compute_dtype ) prefix_keys = [] prefix_values = [] prefix_rope = _prepare_mrope(prefix_indexes, prefix.device, prefix.dtype) if transformer_options is None: transformer_options = {} prefetch = comfy.model_prefetch.make_prefetch_queue( list(self.language_model.model.layers), prefix.device, transformer_options, ) with comfy.model_prefetch.malloc_graph_scope(prefix.device): for layer_index, layer in enumerate(self.language_model.model.layers): if interrupt is not None: interrupt() comfy.model_prefetch.prefetch_queue_pop(prefetch, prefix.device, layer, prefix.dtype, malloc_scope="prefix") transformer_options["block_index"] = layer_index if past_keys is not None: with comfy.model_prefetch.pause_malloc_graph(): past_key = past_keys[layer_index].to(device=prefix.device, dtype=prefix.dtype) past_value = past_values[layer_index].to(device=prefix.device, dtype=prefix.dtype) else: past_key = None past_value = None output, prefix_key, prefix_value = layer.forward_prefix( prefix, prefix_rope, prefix_mask, transformer_options, past_key=past_key, past_value=past_value, ) with comfy.model_prefetch.pause_malloc_graph(): prefix_keys.append(prefix_key.clone()) prefix_values.append(prefix_value.clone()) prefix.copy_(output) del output, prefix_key, prefix_value, past_key, past_value comfy.model_prefetch.prefetch_queue_pop(prefetch, prefix.device, None, malloc_scope="prefix") return prefix, prefix_keys, prefix_values, prefix_time
def preprocess_prefix( self, text_input_ids, reference_images=None, prefix_indexes=None, prefix_mask=None, transformer_options=None, text_suffix=None, compute_dtype=None, past_keys=None, past_values=None, ): _, prefix_keys, prefix_values, prefix_time = ( self._preprocess_prefix_state( text_input_ids, reference_images, prefix_indexes, prefix_mask, transformer_options, text_suffix, compute_dtype, past_keys=past_keys, past_values=past_values, ) ) return prefix_keys, prefix_values, prefix_time
def _next_text_token(self, hidden_states, **sampling): hidden_states = self.language_model.model.norm(hidden_states[:, -1:]) return self.sample_token(self.language_model.lm_head(hidden_states)[:, -1], **sampling).flatten()
def _decode_text_token( self, token, caches, hidden_states, rope, attention_mask, transformer_options=None, ): embed = self.language_model.model.embed_tokens if _use_host_rows(embed): hidden_states.copy_(embed.host_rows(token[:, None], out_dtype=hidden_states.dtype)) else: hidden_states.copy_(embed(token[:, None])) if caches: caches[0].prepare(1) attention_mask[..., caches[0].index].zero_() if transformer_options is None: transformer_options = {} prefetch = comfy.model_prefetch.make_prefetch_queue( list(self.language_model.model.layers), hidden_states.device, transformer_options, ) with comfy.model_prefetch.malloc_graph_scope(hidden_states.device): for layer_index, layer in enumerate(self.language_model.model.layers): transformer_options["block_index"] = layer_index cache = caches[layer_index]
def core(): hidden_states.copy_(layer.forward_decode(hidden_states, rope, cache, attention_mask, transformer_options))
comfy.model_prefetch.prefetch_queue_pop( prefetch, hidden_states.device, layer, hidden_states.dtype, core=core, enable_graph=True, malloc_scope="decode", ) cache.advance(1) comfy.model_prefetch.prefetch_queue_pop(prefetch, hidden_states.device, None, malloc_scope="decode")
def generate_text_tokens( self, text_input_ids, reference_images=None, prefix_indexes=None, prefix_mask=None, *, max_tokens, stop_token_ids, transformer_options=None, progress=None, interrupt=None, compute_dtype=None, do_sample=False, temperature=1.0, top_k=50, top_p=0.95, min_p=0.0, repetition_penalty=1.0, presence_penalty=0.0, seed=None, ): """Return generated IDs and the stop token (None at the token limit).
EOS is excluded from the returned IDs; other stop tokens are included. KV state is local to this call. """
if not self.has_lm_head: raise RuntimeError( "This SenseNova checkpoint does not contain language_model.lm_head.weight, " "which is required for text generation." ) if text_input_ids.shape[0] != 1: raise ValueError("SenseNova text generation currently requires a single prompt batch.")
hidden_states, prefix_keys, prefix_values, prefix_time = ( self._preprocess_prefix_state( text_input_ids, reference_images, prefix_indexes, prefix_mask, transformer_options, compute_dtype=compute_dtype, interrupt=interrupt, ) ) generator = torch.Generator(device=hidden_states.device) if do_sample else None if generator is not None: generator.manual_seed(seed) if seed is not None else generator.seed() history = text_input_ids[0].tolist() sampling = dict(do_sample=do_sample, temperature=temperature, top_k=top_k, top_p=top_p, min_p=min_p, repetition_penalty=repetition_penalty, presence_penalty=presence_penalty, token_history=history, generator=generator) next_token = self._next_text_token(hidden_states, **sampling) decode_hidden = torch.empty_like(hidden_states[:, -1:]) del hidden_states token_ids = [] for step in range(max_tokens): if interrupt is not None: interrupt() token_id = int(next_token.item()) if progress is not None: progress(step + 1) if token_id == IM_END_ID: return token_ids, token_id token_ids.append(token_id) report_generated_tokens(token_ids) history.append(token_id) if token_id in stop_token_ids: return token_ids, token_id if step + 1 == max_tokens: break if step == 0: batch = text_input_ids.shape[0] position = torch.empty((batch,), device=decode_hidden.device, dtype=torch.int64) prefix_length = text_input_ids.shape[1] capacity = prefix_length + max_tokens - 1 seqlen = torch.full((batch,), prefix_length, device=decode_hidden.device, dtype=torch.int32) attention_mask = decode_hidden.new_full((batch, 1, 1, capacity), float("-inf")) attention_mask[..., :prefix_length].zero_() caches = [] for index in range(len(prefix_keys)): key, value = prefix_keys[index], prefix_values[index] _, heads, length, head_dim = key.shape buffer = key.new_zeros((batch, capacity, heads, head_dim)) cache = FixedKV(buffer, torch.zeros_like(buffer), length, position, seqlen) cache.key[:, :length].copy_(key.transpose(1, 2)) cache.value[:, :length].copy_(value.transpose(1, 2)) caches.append(cache) prefix_keys[index] = prefix_values[index] = None del key, value, buffer, cache del prefix_keys, prefix_values positions = prefix_time[:, None] + torch.arange(max_tokens - 1, device=prefix_time.device) temporal = _prepare_llm_rope(positions, HEAD_DIM // 2, 5000000.0, decode_hidden.device, decode_hidden.dtype) rope = (tuple(freq[:, :, :1].clone() for freq in temporal),) else: for dst, src in zip(rope[0], temporal): dst.copy_(src[:, :, step:step + 1]) self._decode_text_token( next_token, caches, decode_hidden, rope, attention_mask, transformer_options, ) next_token = self._next_text_token(decode_hidden, **sampling)
return token_ids, None
class SenseNovaU15(nn.Module): def __init__( self, dtype=None, device=None, operations=None, **kwargs, ): super().__init__() self.dtype = dtype self.layers = nn.ModuleList( DecoderLayer(device=device, dtype=dtype, operations=operations) for _ in range(NUM_LAYERS) ) self.norm = operations.RMSNorm(HIDDEN_SIZE, eps=1e-6, device=device, dtype=dtype) self.patch_embed = VisionEmbeddings(device=device, dtype=dtype, operations=operations) self.timestep_embedder = TimestepEmbedder(HIDDEN_SIZE, device=device, dtype=dtype, operations=operations) self.head = ConvDecoder(device=device, dtype=dtype, operations=operations) self.noise_scale_embedder = TimestepEmbedder(HIDDEN_SIZE, device=device, dtype=dtype, operations=operations)
def forward(self, x, timesteps, context=None, transformer_options={}, **kwargs): return comfy.patcher_extension.WrapperExecutor.new_class_executor( self._forward, self, comfy.patcher_extension.get_all_wrappers( comfy.patcher_extension.WrappersMP.DIFFUSION_MODEL, transformer_options ), ).execute(x, timesteps, context, transformer_options, **kwargs)
def _forward( self, x, timesteps, context=None, transformer_options={}, prefix_keys=None, prefix_values=None, prefix_time=None, **kwargs, ): if prefix_keys is None: raise ValueError("SenseNova-U1.5 requires text conditioning")
original_height, original_width = x.shape[-2:] x = _pad_to_merged_patch_size(x) batch, _, height, width = x.shape prefix_batch = prefix_keys[0].shape[0] if prefix_batch > 0 and batch % prefix_batch: prefix_keys = [comfy.utils.resize_to_batch_size(value, batch) for value in prefix_keys] prefix_values = [comfy.utils.resize_to_batch_size(value, batch) for value in prefix_values] prefix_time = comfy.utils.resize_to_batch_size(prefix_time, batch) prefix_batch = batch generation_batch = _generation_batch_size(batch, prefix_batch) token_height = height // MERGED_PATCH_SIZE token_width = width // MERGED_PATCH_SIZE image_length = token_height * token_width
image = self.patch_embed(x) time_embedding = self.timestep_embedder(timesteps, image.dtype) noise_scale = resolution_noise_scale(height, width) / 16.0 time_embedding = time_embedding + self.noise_scale_embedder( torch.full_like(timesteps, noise_scale), image.dtype ) image = image + time_embedding[:, None, :]
image_time = prefix_time.repeat_interleave(generation_batch)
image_positions = torch.arange(image_length, dtype=torch.long, device=x.device) image_indexes = torch.stack( ( image_time[:, None].expand(batch, image_length), (image_positions // token_width)[None].expand(batch, image_length), (image_positions % token_width)[None].expand(batch, image_length), ) ) image_rope = _prepare_mrope(image_indexes, image.device, image.dtype)
prefetch = comfy.model_prefetch.make_prefetch_queue( list(self.layers), image.device, transformer_options, ) with comfy.model_prefetch.malloc_graph_scope(image.device): for layer_index, layer in enumerate(self.layers): comfy.model_prefetch.prefetch_queue_pop(prefetch, image.device, layer, image.dtype, malloc_scope="generation") transformer_options["block_index"] = layer_index image.copy_(layer.forward_generation( image, image_rope, _expand_prefix_batch(prefix_keys[layer_index], generation_batch), _expand_prefix_batch(prefix_values[layer_index], generation_batch), transformer_options, )) comfy.model_prefetch.prefetch_queue_pop(prefetch, image.device, None, malloc_scope="generation")
image = self.norm(image) image = image.view(batch, token_height, token_width, HIDDEN_SIZE).permute( 0, 3, 1, 2 ) predicted = self.head(image) denominator = (1.0 - timesteps).clamp_min(0.02).view(batch, 1, 1, 1) velocity = (x - predicted) / denominator return velocity[..., :original_height, :original_width]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import math
import torch
import comfy.model_sampling
def time_snr_shift(shift, value): if shift == 1.0: return value return shift * value / (1.0 + (shift - 1.0) * value)
def inverse_time_snr_shift(shift, value): if shift == 1.0: return value return value / (shift - (shift - 1.0) * value)
def upstream_timesteps(steps, shift, device=None): base = torch.linspace(0.0, 1.0, steps + 1, device=device) return 1.0 - time_snr_shift(shift, 1.0 - base)
def upstream_sigmas(steps, shift, device=None): return 1.0 - upstream_timesteps(steps, shift, device=device)
def resolution_noise_scale( height, width, base_seq_len=64, noise_scale=1.0, maximum=16.0): token_height = math.ceil(height / 32) token_width = math.ceil(width / 32) scale = math.sqrt(token_height * token_width / base_seq_len) * noise_scale return min(scale, maximum)
class SenseNovaModelSampling( comfy.model_sampling.ModelSamplingDiscreteFlow, comfy.model_sampling.CONST): def set_parameters(self, shift=1.0, timesteps=1000, multiplier=1000): self.shift = shift self.multiplier = multiplier base_timesteps = torch.linspace(multiplier, 0.0, timesteps + 1) self.register_buffer("sigmas", self.sigma(base_timesteps))
def timestep(self, sigma): base_sigma = inverse_time_snr_shift(self.shift, sigma) return (1.0 - base_sigma) * self.multiplier
def sigma(self, timestep): base_sigma = 1.0 - timestep / self.multiplier return time_snr_shift(self.shift, base_sigma)
def percent_to_sigma(self, percent): if percent <= 0.0: return 1.0 if percent >= 1.0: return 0.0 return float(time_snr_shift(self.shift, 1.0 - percent))
def noise_scaling(self, sigma, noise, latent_image, max_denoise=False): sigma = comfy.model_sampling.reshape_sigma(sigma, noise.ndim) scale = resolution_noise_scale( latent_image.shape[-2], latent_image.shape[-1], noise_scale=self.noise_scale, ) return sigma * (scale * noise) + (1.0 - sigma) * latent_image123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315import osimport re
import torchfrom tqdm import tqdmfrom transformers import Qwen2Tokenizer
from comfy import sd1_clipimport comfy.model_managementimport comfy.model_prefetchimport comfy.opsimport comfy.utilsfrom comfy.ldm.sensenova import model as sensenova_modelfrom comfy.ldm.sensenova.conditioning import ( IMAGE_START_ID, IM_END_ID, MERGED_PATCH_SIZE, prepare_incremental_prefix_inputs, prepare_prefix_inputs, split_reference_batches,)from comfy.text_encoders.llama import generate_dtype
SYSTEM_MESSAGE = ( "You are an image generation and editing assistant that accurately understands and executes " "user intent.\n\nYou support two modes:\n\n1. Think Mode:\nIf the task requires reasoning, you " "MUST start with a <think></think> block. Put all reasoning inside the block using plain text. " "DO NOT include any image tags. Keep it reasonable and directly useful for producing the final " "image.\n\n2. Non-Think Mode:\nIf no reasoning is needed, directly produce the final image.\n\n" "Task Types:\n\nA. Text-to-Image Generation:\n" "- Generate a high-quality image based on the user's description.\n" "- Ensure visual clarity, semantic consistency, and completeness.\n" "- DO NOT introduce elements that contradict or override the user's intent.\n\n" "B. Image Editing:\n" "- Use the provided image(s) as input or reference for modification or transformation.\n" "- The result can be an edited image or a new image based on the reference(s).\n" "- Preserve all unspecified attributes unless explicitly changed.\n\n" "General Rules:\n" "- For any visible text in the image, follow the language specified for the rendered text in " "the user's description, not the language of the prompt. If no language is specified, use the " "user's input language.")
INTERLEAVE_SYSTEM_MESSAGE = ( "You are a multimodal assistant capable of reasoning with both text and images. " "You support two modes:\n\n" "Think Mode: When reasoning is needed, you MUST start with a <think></think> block " "and place all reasoning inside it. You MUST interleave text with generated images " "using tags like <image1>, <image2>. Images can ONLY be generated between <think> and " "</think>, and may be referenced in the final answer.\n\n" "Non-Think Mode: When no reasoning is needed, directly provide the answer without reasoning. " "Do not use tags like <image1>, <image2>; present any images naturally alongside the text.\n\n" "After the think block, always provide a concise, user-facing final answer. " "The answer may include text, images, or both. Match the user's language in both reasoning " "and the final answer.")
def _generation_prompt_parts(text, thinking, mode, system_prompt=None): if mode == "interleave": system = INTERLEAVE_SYSTEM_MESSAGE assistant = "" if thinking else "<think>\n\n</think>\n\n" else: system = SYSTEM_MESSAGE assistant = "<think>\n" if thinking else "<think>\n\n</think>\n\n<img>" system = system_prompt or system return ( f"<|im_start|>system\n{system}<|im_end|>\n<|im_start|>user", "\n" + text, f"<|im_end|>\n<|im_start|>assistant\n{assistant}", )
def build_generation_prompt(text, thinking=False): return "".join(_generation_prompt_parts(text, thinking, "image"))
def build_unconditional_prompt(): return "<|im_start|>user\n<|im_end|>\n<|im_start|>assistant\n<img>"
def build_interleave_unconditional_prompt(): return "<|im_start|>user\n<|im_end|>\n<|im_start|>assistant\n"
class SenseNovaQwen2Tokenizer: @classmethod def from_pretrained(cls, *args, **kwargs): tokenizer = Qwen2Tokenizer.from_pretrained(*args, **kwargs) existing_special_tokens = [ token for _, token in sorted(tokenizer.added_tokens_decoder.items()) if token.special ] extra_tokens = [ "<IMG_CONTEXT>", "<img>", "</img>", "<quad>", "</quad>", "<ref>", "</ref>", "<box>", "</box>", "<|action_start|>", "<|action_end|>", "<|plugin|>", "<|interpreter|>", ] extra_tokens.extend(f"<FAKE_PAD_{index}>" for index in range(254)) tokenizer.add_special_tokens( {"additional_special_tokens": existing_special_tokens + extra_tokens} ) return tokenizer
class SenseNovaQwenTokenizer(sd1_clip.SDTokenizer): def __init__(self, embedding_directory=None, tokenizer_data={}): tokenizer_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), "qwen25_tokenizer" ) super().__init__( tokenizer_path, pad_with_end=False, embedding_size=4096, embedding_key="sensenova_u15", tokenizer_class=SenseNovaQwen2Tokenizer, has_start_token=False, has_end_token=False, pad_to_max_length=False, max_length=99999999, min_length=1, pad_token=151643, tokenizer_data=tokenizer_data, )
class SenseNovaTokenizer(sd1_clip.SD1Tokenizer): def __init__(self, embedding_directory=None, tokenizer_data={}): super().__init__( embedding_directory=embedding_directory, tokenizer_data=tokenizer_data, name="sensenova_u15", tokenizer=SenseNovaQwenTokenizer, )
def tokenize_with_weights(self, text, return_word_ids=False, **kwargs): thinking = kwargs.pop("thinking", False) # Generate Text supplies skip_template; CLIP Text Encode uses the image prompt. mode = kwargs.pop("mode", "interleave" if "skip_template" in kwargs else "image") skip_template = kwargs.get("skip_template", False) if skip_template: parts = (text,) elif text or thinking or kwargs.get("system_prompt"): parts = _generation_prompt_parts(text, thinking, mode, kwargs.get("system_prompt")) else: prompt = ( build_interleave_unconditional_prompt() if mode == "interleave" else build_unconditional_prompt() ) parts = (prompt,) values = [] word_id = 1 for index, part in enumerate(parts): part = sd1_clip.unescape_important(sd1_clip.escape_important(part)) # Preserve SDTokenizer's segmentation even without textual-inversion embeddings. segments = re.split(r"(?<=\s)(?={})".format(re.escape(self.sensenova_u15.embedding_identifier)), part) for segment_index, segment in enumerate(segments): word_id += int(segment_index > 0) # Only the template may introduce protocol IDs; user markers remain text. ids = self.sensenova_u15.tokenizer.encode( segment, add_special_tokens=False, split_special_tokens=index == 1 or skip_template, ) values.extend((token, 1.0, word_id) if return_word_ids else (token, 1.0) for token in ids) tokens = {"sensenova_u15": [values], "sensenova_prompt": text} images = kwargs.get("images") or [] if kwargs.get("image") is not None: images = [kwargs["image"], *images] if images: tokens["reference_latents"] = images return tokens
def clip_parameters(state_dict, prefix=""): return { "has_lm_head": prefix + "language_model.lm_head.weight" in state_dict, "dtype_model": state_dict[prefix + "language_model.model.norm.weight"].dtype, "quantization_metadata": comfy.utils.detect_layer_quantization(state_dict, prefix), }
class SenseNovaTextEncoder(sensenova_model.SenseNovaTextModel): def __init__(self, device="cpu", dtype=None, model_options={}, has_lm_head=False, dtype_model=None, quantization_metadata=None): dtype = dtype_model or dtype operations = model_options.get("custom_operations") if operations is None: operations = comfy.ops.manual_cast if quantization_metadata is None else comfy.ops.mixed_precision_ops(quantization_metadata, dtype, full_precision_mm=True) super().__init__(has_lm_head=has_lm_head, device=device, dtype=dtype, operations=operations) self.dtypes = {dtype} self.execution_device = device
def get_dynamic_vram__units(self): backbone = self.language_model.model units = [*backbone.layers, backbone.norm] if self.has_lm_head: units.append(self.language_model.lm_head) return units, [backbone.embed_tokens]
def reset_clip_options(self): self.execution_device = None
def set_clip_options(self, options): self.execution_device = options.get("execution_device", self.execution_device)
def load_sd(self, sd): return self.load_state_dict(sd, strict=False, assign=getattr(self, "can_assign_sd", False))
def _input_ids(self, tokens): if "text_input_ids" in tokens: return tokens["text_input_ids"] return torch.tensor([[int(value[0]) for value in batch] for batch in tokens["sensenova_u15"]], dtype=torch.long)
def _prefix_arguments(self, tokens, dtype): past_keys = tokens.get("past_prefix_keys") past_values = tokens.get("past_prefix_values") past_time = tokens.get("past_prefix_time") if past_keys is not None and past_values is not None and past_time is not None: suffix_ids, references, indexes, mask = prepare_incremental_prefix_inputs( tokens["suffix_input_ids"], tokens.get("suffix_reference_latents"), MERGED_PATCH_SIZE, dtype, past_length=int(past_keys[0].shape[2]), start_time=int(past_time[0].item()), ) return dict( text_input_ids=suffix_ids.to(self.execution_device), reference_images=[image.to(device=self.execution_device, dtype=dtype) for image in references] if references else None, prefix_indexes=indexes.to(self.execution_device), prefix_mask=mask.to(self.execution_device), text_suffix=None, past_keys=past_keys, past_values=past_values, ) input_ids = self._input_ids(tokens) thinking_start = tokens.get("sensenova_thinking_start") text_suffix = None if thinking_start is not None: text_suffix = input_ids[:, thinking_start:].to(self.execution_device) input_ids = input_ids[:, :thinking_start] input_ids, references, indexes, mask = prepare_prefix_inputs( input_ids, tokens.get("reference_latents"), MERGED_PATCH_SIZE, dtype, image_only=tokens.get("image_only", False), expand_images=not tokens.get("sensenova_interleave_expanded", False), generated_start=tokens.get("sensenova_interleave_start"), ) return dict( text_input_ids=input_ids.to(self.execution_device), reference_images=[image.to(device=self.execution_device, dtype=dtype) for image in references] if references else None, prefix_indexes=indexes.to(self.execution_device) if indexes is not None else None, prefix_mask=mask.to(self.execution_device) if mask is not None else None, text_suffix=text_suffix, )
def encode_token_weights(self, tokens): dtype = generate_dtype(self.execution_device) try: keys, values, time = self.preprocess_prefix( **self._prefix_arguments(tokens, dtype), compute_dtype=dtype, transformer_options={"prefetch_dynamic_vbars": True}, ) device = comfy.model_management.intermediate_device() input_ids = self._input_ids(tokens).to(device) extra = { "text_input_ids": input_ids, "prefix_keys": [key.to(device) for key in keys], "prefix_values": [value.to(device) for value in values], "prefix_time": time.to(device), "sensenova_reference_count": len(split_reference_batches(tokens.get("reference_latents") or [])), } if "sensenova_prompt" in tokens: extra["sensenova_prompt"] = tokens["sensenova_prompt"] if "reference_latents" in tokens: extra["reference_latents"] = tokens["reference_latents"] return input_ids.unsqueeze(-1).float(), None, extra finally: comfy.model_prefetch.cleanup_prefetch_queues()
def generate(self, tokens, do_sample=True, max_length=256, temperature=1.0, top_k=50, top_p=0.95, min_p=0.0, repetition_penalty=1.0, seed=None, presence_penalty=0.0, mtp=True): dtype = generate_dtype(self.execution_device) prefix = self._prefix_arguments(tokens, dtype) prefix.pop("text_suffix") prefix.pop("past_keys", None) prefix.pop("past_values", None) progress = comfy.utils.ProgressBar(max_length) try: with tqdm(total=max_length, desc="Generating tokens", unit="token") as console: def update_progress(value): console.update(value - console.n) progress.update_absolute(value)
progress.update_absolute(0) token_ids, stop = self.generate_text_tokens( **prefix, max_tokens=max_length, stop_token_ids=tokens.get("stop_token_ids", (IMAGE_START_ID,)), do_sample=do_sample, temperature=temperature, top_k=top_k, top_p=top_p, min_p=min_p, repetition_penalty=repetition_penalty, presence_penalty=presence_penalty, seed=seed, compute_dtype=dtype, transformer_options={"prefetch_dynamic_vbars": True}, progress=update_progress, interrupt=comfy.model_management.throw_exception_if_processing_interrupted, ) console.total = console.n progress.update_absolute(console.n, console.n) if stop == IM_END_ID: token_ids.append(stop) return token_ids finally: comfy.model_prefetch.cleanup_prefetch_queues()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530import torchfrom typing_extensions import override
from comfy.ldm.sensenova.conditioning import ( IMAGE_CONTEXT_ID, IMAGE_END_ID, IMAGE_START_ID, IM_END_ID, THINK_END_ID, THINK_START_ID, THINK_SUFFIX_IDS, expand_interleave_inputs, multi_turn_suffix_ids, prepare_interleave_image,)from comfy.ldm.sensenova.sampling import SenseNovaModelSamplingfrom comfy_api.latest import ComfyExtension, io, uifrom comfy_execution.graph_utils import ExecutionBlocker
class SenseNovaSamplingOptions(io.ComfyNode): @classmethod def define_schema(cls) -> io.Schema: return io.Schema( node_id="SenseNovaSamplingOptions", display_name="SenseNova Sampling Options", category="model/patch/sensenova", description="Set the SenseNova flow shift.", inputs=[ io.Model.Input(id="model"), io.Float.Input(id="shift", default=3.0, step=0.01), ], outputs=[io.Model.Output()], )
@classmethod def execute(cls, *, model, shift: float) -> io.NodeOutput: patched = model.clone() model_sampling = SenseNovaModelSampling(patched.model.model_config) model_sampling.set_parameters(shift=shift) patched.add_object_patch("model_sampling", model_sampling) return io.NodeOutput(patched)
class SenseNovaConditioning(io.ComfyNode): @classmethod def define_schema(cls) -> io.Schema: return io.Schema( node_id="SenseNovaConditioning", display_name="SenseNova Conditioning", category="model/sampling/sensenova", description=( "Encode reference images, image thinking, interleaved text, self-correction, or multi-turn editing with CLIP. " "Connect HiDream-O1 Reference Images before this node and use a standard sampler for images. " "Text-to-image without thinking needs only CLIP Text Encode; text-only output can use Generate Text." ), inputs=[ io.Clip.Input("clip", optional=True), io.Conditioning.Input("conditioning"), io.Conditioning.Input("negative", optional=True), io.DynamicCombo.Input("task", options=[ io.DynamicCombo.Option("image", []), io.DynamicCombo.Option("image thinking", []), io.DynamicCombo.Option("interleave", [ io.Boolean.Input("thinking", default=True), io.Latent.Input("samples", optional=True, tooltip="Previous sampler output, connected when continuing after an image request."), ]), io.DynamicCombo.Option("self-correction", [ io.Latent.Input("samples", optional=True, tooltip="Previous sampler output, connected when continuing after an image request."), ]), io.DynamicCombo.Option("multi-turn edit", [ io.Conditioning.Input("previous", optional=True, tooltip="Previous turn conditioning, connected when continuing an editing history."), io.Latent.Input("samples", optional=True, tooltip="Previous sampler output, connected when continuing after an image turn."), ]), ], tooltip="Select the task. Its prompt template and stopping behavior are set automatically."), io.Int.Input("max_tokens", default=1024, min=1, max=8192, advanced=True, tooltip="Maximum tokens generated during this call."), ], outputs=[ io.Conditioning.Output(display_name="conditioning"), io.String.Output(display_name="generated_text", tooltip="Text generated by this call. Use SenseNova Interleave Decode for the complete result."), io.Conditioning.Output(display_name="negative", tooltip="Updated negative conditioning for interleave and self-correction."), io.Boolean.Output(display_name="image_requested"), ], )
@classmethod def execute(cls, *, conditioning, task: io.DynamicCombo.Type, max_tokens, clip=None, negative=None) -> io.NodeOutput: name = task["task"] if name not in ("image", "image thinking", "interleave", "self-correction", "multi-turn edit"): raise ValueError(f"Unknown SenseNova task: {name}") if not conditioning or conditioning[0][1].get("sensenova_interleave_finished"): return io.NodeOutput(conditioning, "", negative or [], False, ui=ui.PreviewText("")) if clip is None: raise ValueError("Connect CLIP to SenseNova Conditioning.") if name == "image": return io.NodeOutput(encode_conditioning(clip, conditioning), "", encode_conditioning(clip, negative or [], image_only=True), True) if name == "multi-turn edit": return cls._execute_multi_turn_edit( clip=clip, positive=conditioning, negative=negative, previous=task.get("previous"), samples=task.get("samples"), ) mode = "interleave" if name == "interleave" else "image" thinking = name == "image thinking" or (name == "interleave" and task["thinking"]) positive = prepare_generation_conditioning(clip, conditioning, mode, thinking) if name == "image thinking": return cls._execute_image(clip=clip, conditioning=positive, max_tokens=max_tokens, negative=negative) negative = prepare_generation_conditioning(clip, negative or [], mode, False) return cls._execute_interleave( clip=clip, positive=positive, negative=negative, samples=task.get("samples"), max_text_tokens=max_tokens, )
@classmethod def _execute_multi_turn_edit( cls, *, clip, positive, negative, previous, samples, ) -> io.NodeOutput: turn_meta = _require_sensenova_metadata(positive, "positive") if negative: neg_turn_meta = _require_sensenova_metadata(negative, "negative") else: neg_turn_meta = None
if previous is None: if samples is not None: raise ValueError("Connect previous conditioning together with samples when continuing an edit.") pos_meta = expand_multi_turn_metadata(turn_meta, image_only=False) updated_positive = encode_conditioning(clip, [[positive[0][0], pos_meta]]) updated_negative = ( encode_conditioning(clip, [[negative[0][0], expand_multi_turn_metadata(neg_turn_meta, image_only=True)]], image_only=True) if neg_turn_meta is not None else [] ) return io.NodeOutput(updated_positive, "", updated_negative, True)
prev_raw = _require_sensenova_metadata(previous, "previous") latent_samples = samples.get("samples") if isinstance(samples, dict) else None if latent_samples is None: raise ValueError("SenseNova multi-turn edit requires samples from the preceding KSampler.")
image_tokens, image = prepare_interleave_image(latent_samples) image = image.clamp(0.0, 1.0)
updated_positive = _encode_multi_turn_continuation( clip, prev_raw, turn_meta, image_tokens, image, image_only=False ) updated_negative = ( _encode_multi_turn_continuation( clip, neg_turn_meta, neg_turn_meta, image_tokens, image, image_only=True ) if neg_turn_meta is not None else [] ) return io.NodeOutput(updated_positive, "", updated_negative, True)
@classmethod def _execute_image(cls, *, clip, conditioning, max_tokens, negative=None) -> io.NodeOutput: if len(conditioning) != 1: raise ValueError("SenseNova Conditioning requires one positive conditioning entry.") metadata = conditioning[0][1] if metadata.get("text_input_ids") is None: raise ValueError("SenseNova Conditioning requires SenseNova text conditioning.") token_ids, stop_token = generate_tokens(clip, metadata, max_tokens, THINK_END_ID) text = _decode_generated_text(clip, token_ids[:-1] if stop_token == THINK_END_ID else token_ids) input_ids = metadata["text_input_ids"] suffix = input_ids.new_tensor([*token_ids, *THINK_SUFFIX_IDS]).unsqueeze(0) updated_metadata = { **metadata, "text_input_ids": torch.cat((input_ids, suffix), dim=1), "sensenova_thinking_start": input_ids.shape[1], } return io.NodeOutput( encode_conditioning(clip, [[conditioning[0][0], updated_metadata]]), text, encode_conditioning(clip, negative or [], image_only=True), True, ui=ui.PreviewText(text), )
@classmethod def _execute_interleave( cls, *, clip, positive, negative, samples, max_text_tokens, ) -> io.NodeOutput: if negative is None or len(positive) != 1 or len(negative) != 1: raise ValueError( "SenseNova interleave requires one positive and one negative conditioning entry." ) if positive[0][1].get("sensenova_interleave_finished"): return io.NodeOutput( positive, "", negative, False, ui=ui.PreviewText("") ) if clip is None: raise ValueError("Connect CLIP to SenseNova Conditioning.") positive_metadata = expand_interleave_metadata(positive[0][1], image_only=False) negative_metadata = expand_interleave_metadata(negative[0][1], image_only=True) pending_image = bool( positive_metadata.get("sensenova_interleave_pending_image") ) if pending_image != bool( negative_metadata.get("sensenova_interleave_pending_image") ): raise ValueError("SenseNova interleave conditioning histories are out of sync.") latent_samples = samples.get("samples") if isinstance(samples, dict) else None if pending_image: if latent_samples is None: raise ValueError( "SenseNova interleave is waiting for samples from the preceding KSampler." ) image_tokens, image = prepare_interleave_image(latent_samples) positive_metadata = append_interleave_image(positive_metadata, image_tokens, image) negative_metadata = append_interleave_image(negative_metadata, image_tokens, image) elif latent_samples is not None: raise ValueError( "SenseNova interleave received samples before requesting an image." )
token_ids, stop_token = generate_tokens(clip, positive_metadata, max_text_tokens, IMAGE_START_ID)
image_requested = stop_token == IMAGE_START_ID positive_metadata = append_interleave_tokens( positive_metadata, token_ids, image_requested ) positive_metadata["sensenova_interleave_finished"] = stop_token == IM_END_ID if image_requested: negative_ids = negative_metadata["text_input_ids"] image_start = [] if negative_ids.shape[1] and negative_ids[0, -1] == IMAGE_START_ID else [IMAGE_START_ID] negative_metadata = append_interleave_tokens( negative_metadata, image_start, True ) history = positive_metadata["text_input_ids"][0, positive_metadata["sensenova_interleave_start"]:].tolist() think_start, think_end = _interleave_thinking_span(clip, history) stage_start = len(history) - len(token_ids) text = _decode_generated_text(clip, [ token for index, token in enumerate(token_ids, start=stage_start) if index not in (think_start, think_end) ]) updated_positive = encode_conditioning(clip, [[positive[0][0], positive_metadata]]) updated_negative = encode_conditioning(clip, [[negative[0][0], negative_metadata]]) return io.NodeOutput( updated_positive, text, updated_negative, image_requested, ui=ui.PreviewText(text), )
def prepare_generation_conditioning(clip, conditioning, mode, thinking): prepared = [] for tensor, metadata in conditioning: if metadata.get("sensenova_interleave_expanded"): prepared.append([tensor, metadata]) continue if "sensenova_prompt" not in metadata: raise ValueError("Use CLIP Text Encode with the SenseNova CLIP output before SenseNova Conditioning.") tokens = clip.tokenize(metadata["sensenova_prompt"], mode=mode, thinking=thinking) input_ids = torch.tensor([[int(value[0]) for value in batch] for batch in tokens["sensenova_u15"]], dtype=torch.long) updated = {**metadata, "text_input_ids": input_ids} updated.pop("sensenova_thinking_start", None) prepared.append([tensor, updated]) return prepared
def _require_sensenova_metadata(conditioning, role): if len(conditioning) != 1 or conditioning[0][1].get("text_input_ids") is None: raise ValueError(f"SenseNova multi-turn edit requires one {role} SenseNova conditioning entry.") return conditioning[0][1]
def expand_multi_turn_metadata(metadata, image_only): if metadata.get("sensenova_interleave_expanded"): return { "text_input_ids": metadata["text_input_ids"], "reference_latents": list(metadata.get("reference_latents") or []), "sensenova_prompt": metadata.get("sensenova_prompt", ""), "sensenova_interleave_expanded": True, } input_ids, references = expand_interleave_inputs( metadata["text_input_ids"], metadata.get("reference_latents"), image_only, append_image_start=True, image_newline=False, ) return { "text_input_ids": input_ids, "reference_latents": references, "sensenova_prompt": "" if image_only else metadata.get("sensenova_prompt", ""), "sensenova_interleave_expanded": True, }
def _encode_multi_turn_continuation(clip, prev_raw, turn_meta, image_tokens, image, *, image_only): prev_meta = expand_multi_turn_metadata(prev_raw, image_only=image_only) suffix_ids = multi_turn_suffix_ids(turn_meta["text_input_ids"], image_tokens, image_only=image_only) prev_ids = prev_meta["text_input_ids"] combined_ids = torch.cat((prev_ids, suffix_ids.to(device=prev_ids.device)), dim=1) combined_refs = [*prev_meta["reference_latents"], image] out_meta = { "text_input_ids": combined_ids, "reference_latents": combined_refs, "sensenova_prompt": "" if image_only else turn_meta.get("sensenova_prompt", ""), "sensenova_interleave_expanded": True, } tokens = conditioning_tokens(out_meta) tokens["image_only"] = image_only past_keys = prev_raw.get("prefix_keys") past_values = prev_raw.get("prefix_values") past_time = prev_raw.get("prefix_time") if ( prev_raw.get("sensenova_interleave_expanded") and past_keys is not None and past_values is not None and past_time is not None and int(past_keys[0].shape[2]) == int(prev_ids.shape[1]) ): tokens["past_prefix_keys"] = past_keys tokens["past_prefix_values"] = past_values tokens["past_prefix_time"] = past_time tokens["suffix_input_ids"] = suffix_ids tokens["suffix_reference_latents"] = [image] output = [] for tensor, encoded in clip.encode_from_tokens_scheduled(tokens): output.append([tensor, {**out_meta, **encoded}]) return output
def expand_interleave_metadata(metadata, image_only): expanded = dict(metadata) if expanded.get("sensenova_interleave_expanded"): return expanded
input_ids = expanded["text_input_ids"] # Image prompts prefill an image request for direct KSampler use. A new # interleave session lets the model request it instead. Never strip a # model-generated request when resuming an already expanded history. if input_ids.shape[1] and input_ids[0, -1] == IMAGE_START_ID: input_ids = input_ids[:, :-1] input_ids, references = expand_interleave_inputs( input_ids, expanded.get("reference_latents"), image_only ) expanded.update( { "text_input_ids": input_ids, "reference_latents": references, "sensenova_interleave_expanded": True, "sensenova_interleave_pending_image": False, "sensenova_interleave_start": input_ids.shape[1], "sensenova_interleave_input_images": len(references), } ) return expanded
def append_interleave_tokens(metadata, token_ids, image_requested): updated = dict(metadata) if token_ids: suffix = updated["text_input_ids"].new_tensor(token_ids).unsqueeze(0) updated["text_input_ids"] = torch.cat( (updated["text_input_ids"], suffix), dim=1 ) updated["sensenova_interleave_pending_image"] = image_requested return updated
def append_interleave_image(metadata, image_tokens, image): if not metadata.get("sensenova_interleave_pending_image"): raise ValueError("SenseNova interleave received an image without an image request.") updated = append_interleave_tokens(metadata, image_tokens, False) updated["reference_latents"] = [*(metadata.get("reference_latents") or []), image] return updated
def conditioning_tokens(metadata): tokens = {key: metadata[key] for key in ( "text_input_ids", "reference_latents", "sensenova_prompt", "sensenova_thinking_start", "sensenova_interleave_expanded", "sensenova_interleave_start", ) if key in metadata} return tokens
def encode_conditioning(clip, conditioning, image_only=False): output = [] for _, metadata in conditioning: tokens = conditioning_tokens(metadata) tokens["image_only"] = image_only for tensor, encoded in clip.encode_from_tokens_scheduled(tokens): output.append([tensor, {**metadata, **encoded}]) return output
def generate_tokens(clip, metadata, max_tokens, stop_token): tokens = conditioning_tokens(metadata) tokens["stop_token_ids"] = (stop_token,) token_ids = clip.generate(tokens, do_sample=False, max_length=max_tokens) stop = token_ids[-1] if token_ids and token_ids[-1] in (stop_token, IM_END_ID) else None if stop == IM_END_ID: token_ids.pop() return token_ids, stop
def _decode_generated_text(clip, token_ids): text_tokens = [token for token in token_ids if token != IMAGE_START_ID] return clip.decode(text_tokens, skip_special_tokens=True) if text_tokens else ""
def _interleave_thinking_span(clip, token_ids): """Only a leading think block is protocol; later think tags are answer text."""
start = next((index for index, token in enumerate(token_ids) if token == THINK_START_ID), len(token_ids)) if start == len(token_ids) or clip.decode(token_ids[:start], skip_special_tokens=False).strip(): return len(token_ids), len(token_ids) end = next((index for index in range(start + 1, len(token_ids)) if token_ids[index] == THINK_END_ID), len(token_ids)) return start, end
def _decode_interleave_text(clip, token_ids): start, end = _interleave_thinking_span(clip, token_ids) has_thinking = start < len(token_ids) thinking_ids = [] if has_thinking: thinking_ids = token_ids[start + 1:end] token_ids = token_ids[end + 1:]
outputs = [] for ids, is_thinking in ((token_ids, False), (thinking_ids, True)): parts = [] text_tokens = [] for token_id in ids: if token_id == IMAGE_START_ID: parts.append(clip.decode(text_tokens, skip_special_tokens=True)) text_tokens = [] if not is_thinking: parts.append("<image>") elif token_id not in (IMAGE_CONTEXT_ID, IMAGE_END_ID): text_tokens.append(token_id) parts.append(clip.decode(text_tokens, skip_special_tokens=True)) outputs.append("\n\n".join(part.strip() for part in parts if part.strip()) if is_thinking else "".join(parts)) return outputs[0], outputs[1]
class SenseNovaInterleaveDecode(io.ComfyNode): @classmethod def define_schema(cls) -> io.Schema: return io.Schema( node_id="SenseNovaInterleaveDecode", display_name="SenseNova Interleave Decode", category="model/sampling/sensenova", description=( "Extract generated text, images and thinking from the interleave " "history produced by SenseNova Conditioning, including U1.6 " "self-correction. With loops, use End Loop with " "accumulate disabled. Input reference images are excluded. " "Image consumers are skipped when no images were generated." ), inputs=[ io.Clip.Input("clip"), io.Conditioning.Input("conditioning"), io.Latent.Input( "samples", optional=True, tooltip="Last KSampler pixel latent, if the loop ended on an image request.", ), ], outputs=[ io.String.Output(display_name="text"), io.Image.Output(display_name="images", is_output_list=True), io.String.Output(display_name="thinking"), ], )
@classmethod def execute( cls, clip, conditioning, samples=None, ) -> io.NodeOutput: if len(conditioning) != 1 or "sensenova_interleave_start" not in conditioning[0][1]: raise ValueError( "SenseNova Interleave Decode requires interleave conditioning from SenseNova Conditioning." ) metadata = conditioning[0][1] if metadata["sensenova_interleave_pending_image"]: if samples is None: raise ValueError( "SenseNova Interleave Decode is waiting for samples from the last KSampler. " "Connect its LATENT output to samples." ) metadata = append_interleave_image(metadata, *prepare_interleave_image(samples["samples"])) token_ids = metadata["text_input_ids"][0, metadata["sensenova_interleave_start"]:].tolist() text, thinking = _decode_interleave_text(clip, token_ids) images = [ reference.clamp(0.0, 1.0) for reference in metadata["reference_latents"][metadata["sensenova_interleave_input_images"]:] ] return io.NodeOutput(text, images or [ExecutionBlocker(None)], thinking)
class SenseNovaExtension(ComfyExtension): @override async def get_node_list(self) -> list[type[io.ComfyNode]]: return [ SenseNovaConditioning, SenseNovaSamplingOptions, SenseNovaInterleaveDecode, ]
async def comfy_entrypoint() -> SenseNovaExtension: return SenseNovaExtension()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198{ "1": { "class_type": "CheckpointLoaderSimple", "inputs": { "ckpt_name": "SenseNova-U1.5-8B-MoT-MT-Forcing-BF16-v0.1-ComfyUI.safetensors" } }, "2": { "class_type": "SenseNovaSamplingOptions", "inputs": { "model": ["1", 0], "shift": 3.0 } }, "3": { "class_type": "LoadImage", "inputs": { "image": "mt_forcing_test_input.jpg" } }, "4": { "class_type": "ImageScaleToTotalPixels", "inputs": { "image": ["3", 0], "upscale_method": "bicubic", "megapixels": 1.98, "resolution_steps": 32 } }, "5": { "class_type": "GetImageSize", "inputs": { "image": ["4", 0] } }, "6": { "class_type": "EmptyHiDreamO1LatentImage", "inputs": { "width": ["5", 0], "height": ["5", 1], "batch_size": 1 } }, "7": { "class_type": "CLIPTextEncode", "inputs": { "clip": ["1", 1], "text": "" } }, "10": { "class_type": "CLIPTextEncode", "inputs": { "clip": ["1", 1], "text": "Change the woman's yellow ribbed short-sleeve button-up top to a soft sage green." } }, "11": { "class_type": "HiDreamO1ReferenceImages", "inputs": { "positive": ["10", 0], "negative": ["7", 0], "images.image_1": ["4", 0] } }, "12": { "class_type": "SenseNovaConditioning", "inputs": { "clip": ["1", 1], "conditioning": ["11", 0], "task": "multi-turn edit", "max_tokens": 1024 } }, "13": { "class_type": "KSampler", "inputs": { "model": ["2", 0], "positive": ["12", 0], "negative": ["12", 2], "latent_image": ["6", 0], "seed": 42, "steps": 8, "cfg": 1.0, "sampler_name": "euler", "scheduler": "simple", "denoise": 1.0 } }, "14": { "class_type": "VAEDecode", "inputs": { "samples": ["13", 0], "vae": ["1", 2] } }, "15": { "class_type": "SaveImage", "inputs": { "images": ["14", 0], "filename_prefix": "mt_forcing_native_verify/round_000" } }, "20": { "class_type": "CLIPTextEncode", "inputs": { "clip": ["1", 1], "text": "Replace the shiny copper mug she is holding with a matte deep navy blue ceramic mug." } }, "22": { "class_type": "SenseNovaConditioning", "inputs": { "clip": ["1", 1], "conditioning": ["20", 0], "task": "multi-turn edit", "task.previous": ["12", 0], "task.samples": ["13", 0], "max_tokens": 1024 } }, "23": { "class_type": "KSampler", "inputs": { "model": ["2", 0], "positive": ["22", 0], "negative": ["22", 2], "latent_image": ["6", 0], "seed": 43, "steps": 8, "cfg": 1.0, "sampler_name": "euler", "scheduler": "simple", "denoise": 1.0 } }, "24": { "class_type": "VAEDecode", "inputs": { "samples": ["23", 0], "vae": ["1", 2] } }, "25": { "class_type": "SaveImage", "inputs": { "images": ["24", 0], "filename_prefix": "mt_forcing_native_verify/round_001" } }, "30": { "class_type": "CLIPTextEncode", "inputs": { "clip": ["1", 1], "text": "Add a wide ivory fabric headband across the top of her curly red hair, partly tucked into the curls and sitting naturally." } }, "32": { "class_type": "SenseNovaConditioning", "inputs": { "clip": ["1", 1], "conditioning": ["30", 0], "task": "multi-turn edit", "task.previous": ["22", 0], "task.samples": ["23", 0], "max_tokens": 1024 } }, "33": { "class_type": "KSampler", "inputs": { "model": ["2", 0], "positive": ["32", 0], "negative": ["32", 2], "latent_image": ["6", 0], "seed": 44, "steps": 8, "cfg": 1.0, "sampler_name": "euler", "scheduler": "simple", "denoise": 1.0 } }, "34": { "class_type": "VAEDecode", "inputs": { "samples": ["33", 0], "vae": ["1", 2] } }, "35": { "class_type": "SaveImage", "inputs": { "images": ["34", 0], "filename_prefix": "mt_forcing_native_verify/round_002" } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172#!/usr/bin/env python3"""Submit a ComfyUI API workflow JSON and wait for completion."""
from __future__ import annotations
import argparseimport jsonimport sysimport timeimport urllib.errorimport urllib.requestfrom pathlib import Path
def http_json(url: str, payload: dict | None = None, timeout: int = 30) -> dict: data = None headers = {} if payload is not None: data = json.dumps(payload).encode("utf-8") headers["Content-Type"] = "application/json" req = urllib.request.Request(url, data=data, headers=headers) try: with urllib.request.urlopen(req, timeout=timeout) as resp: return json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError as exc: body = exc.read().decode("utf-8", errors="replace") raise RuntimeError(f"HTTP {exc.code} for {url}: {body}") from exc
def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--server", default="http://127.0.0.1:8188") parser.add_argument("--workflow", required=True) parser.add_argument("--timeout", type=int, default=600) args = parser.parse_args()
base = args.server.rstrip("/")
info = http_json(f"{base}/object_info/SenseNovaConditioning", timeout=10) options = info["SenseNovaConditioning"]["input"]["required"]["task"][1]["options"] keys = [opt["key"] for opt in options] assert "multi-turn edit" in keys, f"multi-turn edit not found in options: {keys}" print(f"ComfyUI server ready; SenseNovaConditioning tasks={keys}", flush=True)
workflow = json.loads(Path(args.workflow).read_text(encoding="utf-8")) resp = http_json(f"{base}/prompt", {"prompt": workflow}) prompt_id = resp["prompt_id"] print(f"Queued prompt_id={prompt_id}", flush=True)
t0 = time.monotonic() while True: history = http_json(f"{base}/history/{prompt_id}") if prompt_id in history: entry = history[prompt_id] status = entry.get("status", {}) print( f"Finished in {time.monotonic() - t0:.1f}s; status={status.get('status_str')}", flush=True, ) if status.get("status_str") != "success": print(json.dumps(status, indent=2, ensure_ascii=False), file=sys.stderr) sys.exit(1) outputs = entry.get("outputs", {}) print(json.dumps(outputs, indent=2, ensure_ascii=False), flush=True) return if time.monotonic() - t0 > args.timeout: raise TimeoutError(f"Timed out waiting for prompt_id={prompt_id}") time.sleep(2)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510#!/usr/bin/env python3"""Convert an MT-Forcing / SenseUmm checkpoint into ComfyUI's native SenseNova-U1.5 format.
ComfyUI v0.46+ natively loads SenseNova-U1.5-8B-MoT checkpoints via`comfy/checkpoint_convert.py`, which expects the Hugging Face SenseNova-U1.5 keylayout (`fm_modules.*`, `vision_model.embeddings.*`, `language_model.model.*`,`language_model.lm_head.*`).
This script remaps all 1,116 MT-Forcing tensors 1-to-1 into that layout usingstreaming I/O (one tensor in RAM at a time) and optionally validates the mappedkeys and shapes against a local ComfyUI checkout on the `meta` device."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport mathimport osimport structimport sysimport timefrom pathlib import Pathfrom typing import Any
import torchfrom safetensors import safe_open
SAFETENSORS_DTYPE_TO_TORCH: dict[str, torch.dtype] = { "BOOL": torch.bool, "U8": torch.uint8, "I8": torch.int8, "I16": torch.int16, "I32": torch.int32, "I64": torch.int64, "F16": torch.float16, "BF16": torch.bfloat16, "F32": torch.float32, "F64": torch.float64,}
TORCH_DTYPE_TO_SAFETENSORS: dict[torch.dtype, tuple[str, int]] = { torch.bool: ("BOOL", 1), torch.uint8: ("U8", 1), torch.int8: ("I8", 1), torch.int16: ("I16", 2), torch.int32: ("I32", 4), torch.int64: ("I64", 8), torch.float16: ("F16", 2), torch.bfloat16: ("BF16", 2), torch.float32: ("F32", 4), torch.float64: ("F64", 8),}
CLI_DTYPE_MAP: dict[str, torch.dtype | None] = { "bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32, "keep": None,}
def resolve_input_shards(input_path: Path) -> list[Path]: path = input_path.resolve() if path.is_file(): if path.suffix != ".safetensors": raise ValueError(f"Expected a .safetensors file, got: {path}") return [path] if not path.is_dir(): raise FileNotFoundError(f"Checkpoint path does not exist: {path}")
for role in ("generator", "model"): role_dir = path / role if role_dir.is_dir(): return resolve_input_shards(role_dir)
index_path = path / "model.safetensors.index.json" if index_path.is_file(): index = json.loads(index_path.read_text(encoding="utf-8")) weight_map = index.get("weight_map") if not isinstance(weight_map, dict) or not weight_map: raise ValueError(f"Invalid safetensors index: {index_path}") shard_names = sorted(set(weight_map.values())) shards = [path / name for name in shard_names] for shard in shards: if not shard.is_file(): raise FileNotFoundError(f"Missing indexed shard: {shard}") return shards
single = path / "model.safetensors" if single.is_file(): return [single]
shards = sorted(path.glob("*.safetensors")) if not shards: raise FileNotFoundError(f"No .safetensors files found under: {path}") return shards
def map_mt_forcing_key(key: str) -> str: """Map an MT-Forcing / SenseUmm key to ComfyUI's SenseNova-U1.5 input layout.""" if key.startswith(("fm_modules.", "language_model.model.", "vision_model.embeddings.")): raise ValueError( f"Input key {key!r} already appears to be in ComfyUI/HF SenseNova-U1.5 format" ) if key.startswith("fm_head."): return "fm_modules." + key if key.startswith("noise_scale_embedder."): return "fm_modules." + key if key.startswith("time_embedder."): return "fm_modules.timestep_embedder." + key.removeprefix("time_embedder.") if key.startswith("vision_model_mot_gen."): return ( "fm_modules.vision_model_mot_gen.embeddings." + key.removeprefix("vision_model_mot_gen.") ) if key.startswith("vision_model."): return "vision_model.embeddings." + key.removeprefix("vision_model.") if key.startswith("lm_head."): return "language_model." + key if key.startswith("language_model."): return "language_model.model." + key.removeprefix("language_model.") raise KeyError(f"Unrecognized MT-Forcing tensor key: {key!r}")
def read_safetensors_header(path: Path) -> dict[str, Any]: with path.open("rb") as handle: header_len_bytes = handle.read(8) if len(header_len_bytes) != 8: raise ValueError(f"Truncated safetensors file: {path}") (header_len,) = struct.unpack("<Q", header_len_bytes) header_bytes = handle.read(header_len) if len(header_bytes) != header_len: raise ValueError(f"Truncated safetensors header: {path}") return json.loads(header_bytes.decode("utf-8"))
def collect_tensor_plan( shards: list[Path], target_dtype: torch.dtype | None,) -> tuple[list[dict[str, Any]], int, int]: plan: list[dict[str, Any]] = [] seen_targets: dict[str, str] = {} total_params = 0 total_bytes = 0
for shard in shards: header = read_safetensors_header(shard) for src_key, meta in header.items(): if src_key == "__metadata__": continue dst_key = map_mt_forcing_key(src_key) if dst_key in seen_targets: raise ValueError( f"Duplicate destination key {dst_key!r} from " f"{seen_targets[dst_key]!r} and {src_key!r}" ) seen_targets[dst_key] = src_key
src_st_dtype = meta["dtype"] if src_st_dtype not in SAFETENSORS_DTYPE_TO_TORCH: raise ValueError( f"Unsupported safetensors dtype {src_st_dtype!r} for key {src_key!r}" ) src_torch_dtype = SAFETENSORS_DTYPE_TO_TORCH[src_st_dtype] if target_dtype is not None and src_torch_dtype.is_floating_point: dst_torch_dtype = target_dtype else: dst_torch_dtype = src_torch_dtype dst_st_dtype, itemsize = TORCH_DTYPE_TO_SAFETENSORS[dst_torch_dtype] shape = [int(dim) for dim in meta["shape"]] numel = math.prod(shape) if shape else 1 nbytes = numel * itemsize
plan.append( { "shard": shard, "src_key": src_key, "dst_key": dst_key, "shape": shape, "src_dtype": src_torch_dtype, "dst_dtype": dst_torch_dtype, "dst_st_dtype": dst_st_dtype, "numel": numel, "nbytes": nbytes, } ) total_params += numel total_bytes += nbytes
plan.sort(key=lambda item: item["dst_key"]) return plan, total_params, total_bytes
def read_config_sha256(source_dir: Path) -> str | None: manifest_path = source_dir / "external_dependencies.json" if not manifest_path.is_file(): return None try: manifest = json.loads(manifest_path.read_text(encoding="utf-8")) for dep in manifest.get("dependencies", []): if dep.get("role") == "model_architecture": cfg = dep.get("files", {}).get("config.json", {}) if isinstance(cfg, dict) and cfg.get("sha256"): return str(cfg["sha256"]) except Exception: return None return None
def validate_with_comfyui( comfyui_dir: Path, plan: list[dict[str, Any]],) -> dict[str, Any]: repo = comfyui_dir.resolve() if not (repo / "comfy" / "checkpoint_convert.py").is_file(): raise FileNotFoundError( f"ComfyUI checkout missing comfy/checkpoint_convert.py: {repo}" ) if str(repo) not in sys.path: sys.path.insert(0, str(repo))
import comfy.checkpoint_convert import comfy.model_detection import comfy.ops from comfy.ldm.sensenova.model import SenseNovaTextModel, SenseNovaU15
meta_sd = { item["dst_key"]: torch.empty( item["shape"], dtype=item["dst_dtype"], device="meta" ) for item in plan } converted = comfy.checkpoint_convert.convert_checkpoint(meta_sd) if converted is meta_sd: raise RuntimeError( "comfy.checkpoint_convert.convert_checkpoint did not recognize the mapped keys" )
unet_prefix = "model.diffusion_model." te_prefix = "text_encoders." unet_sd = { k.removeprefix(unet_prefix): v for k, v in converted.items() if k.startswith(unet_prefix) } te_sd = { k.removeprefix(te_prefix): v for k, v in converted.items() if k.startswith(te_prefix) } extra_keys = sorted( k for k in converted if not k.startswith(unet_prefix) and not k.startswith(te_prefix) and k != "vae.pixel_space_vae" ) if extra_keys: raise RuntimeError(f"Unexpected converted keys outside UNet/TE: {extra_keys[:10]}")
unet_config = comfy.model_detection.detect_unet_config(unet_sd, "") if not unet_config or unet_config.get("image_model") != "sensenova_u15": raise RuntimeError(f"ComfyUI model_detection failed: {unet_config!r}")
has_lm_head = "language_model.lm_head.weight" in te_sd unet_model = SenseNovaU15( device="meta", dtype=torch.bfloat16, operations=comfy.ops.disable_weight_init, ) unet_result = unet_model.load_state_dict(unet_sd, strict=True, assign=True)
te_model = SenseNovaTextModel( has_lm_head=has_lm_head, device="meta", dtype=torch.bfloat16, operations=comfy.ops.disable_weight_init, ) te_result = te_model.load_state_dict(te_sd, strict=True, assign=True)
return { "comfyui_repo": str(repo), "unet_config": unet_config, "has_lm_head": has_lm_head, "unet_tensors": len(unet_sd), "text_encoder_tensors": len(te_sd), "total_tensors": len(unet_sd) + len(te_sd), "unet_load": str(unet_result), "text_encoder_load": str(te_result), "validation_device": "meta", }
def write_streaming_safetensors( plan: list[dict[str, Any]], output_path: Path, metadata: dict[str, str], *, compute_sha256: bool = False,) -> tuple[int, str | None]: header: dict[str, Any] = {"__metadata__": metadata} offset = 0 for item in plan: end = offset + item["nbytes"] header[item["dst_key"]] = { "dtype": item["dst_st_dtype"], "shape": item["shape"], "data_offsets": [offset, end], } offset = end
header_bytes = json.dumps( header, separators=(",", ":"), ensure_ascii=False ).encode("utf-8") pad_len = (-len(header_bytes)) % 8 if pad_len: header_bytes += b" " * pad_len
output_path.parent.mkdir(parents=True, exist_ok=True) tmp_path = output_path.with_suffix(output_path.suffix + ".tmp")
# Group reads per shard to keep file descriptors open cleanly, # while still writing strictly in the offset order defined by `plan`. open_handles: dict[Path, Any] = {} hasher = hashlib.sha256() if compute_sha256 else None t0 = time.monotonic()
try: for shard in sorted({item["shard"] for item in plan}): open_handles[shard] = safe_open(str(shard), framework="pt", device="cpu")
with tmp_path.open("wb") as out: prefix = struct.pack("<Q", len(header_bytes)) out.write(prefix) out.write(header_bytes) if hasher is not None: hasher.update(prefix) hasher.update(header_bytes)
written_bytes = 0 total_bytes = offset for idx, item in enumerate(plan, 1): tensor = open_handles[item["shard"]].get_tensor(item["src_key"]) if tensor.dtype != item["dst_dtype"]: tensor = tensor.to(dtype=item["dst_dtype"]) tensor = tensor.contiguous() raw = tensor.view(torch.uint8).numpy().tobytes() if len(raw) != item["nbytes"]: raise RuntimeError( f"Byte size mismatch for {item['dst_key']}: " f"expected {item['nbytes']}, got {len(raw)}" ) out.write(raw) if hasher is not None: hasher.update(raw) written_bytes += len(raw) del tensor, raw
if idx % 100 == 0 or idx == len(plan): elapsed = max(time.monotonic() - t0, 1e-6) gib = written_bytes / (1024**3) total_gib = total_bytes / (1024**3) print( f"[{idx:4d}/{len(plan)}] {gib:6.2f}/{total_gib:.2f} GiB " f"({gib / elapsed:.2f} GiB/s)", flush=True, )
file_bytes = tmp_path.stat().st_size os.replace(tmp_path, output_path) return file_bytes, (hasher.hexdigest() if hasher is not None else None) except Exception: if tmp_path.exists(): tmp_path.unlink() raise finally: for handle in open_handles.values(): handle.__exit__(None, None, None)
def main() -> None: parser = argparse.ArgumentParser( description=( "Convert an MT-Forcing / SenseUmm checkpoint into a ComfyUI-native " "SenseNova-U1.5 safetensors checkpoint." ) ) parser.add_argument( "--input", required=True, help="Path to MT-Forcing model.safetensors or checkpoint directory.", ) parser.add_argument( "--output", help="Output .safetensors path (required unless --dry-run is set).", ) parser.add_argument( "--dtype", choices=tuple(CLI_DTYPE_MAP), default="bf16", help="Target floating-point dtype (default: bf16).", ) parser.add_argument( "--validate-comfyui", help="Optional ComfyUI repo path to validate mapped keys/shapes on meta device.", ) parser.add_argument( "--dry-run", action="store_true", help="Inspect and validate mapping without writing the output checkpoint.", ) parser.add_argument( "--overwrite", action="store_true", help="Overwrite output file if it already exists.", ) parser.add_argument( "--sha256", action="store_true", help="Compute SHA-256 of the written output file.", ) parser.add_argument( "--no-manifest", action="store_true", help="Skip writing <output>.conversion.json next to the output checkpoint.", ) args = parser.parse_args()
if not args.dry_run and not args.output: parser.error("--output is required unless --dry-run is specified")
input_path = Path(args.input).resolve() shards = resolve_input_shards(input_path) source_dir = shards[0].parent target_dtype = CLI_DTYPE_MAP[args.dtype]
plan, total_params, total_bytes = collect_tensor_plan(shards, target_dtype) print( f"Planned {len(plan)} tensors ({total_params:,} params, " f"{total_bytes / (1024**3):.2f} GiB payload, dtype={args.dtype}) " f"from {len(shards)} shard(s).", flush=True, )
comfyui_validation = None if args.validate_comfyui: comfyui_validation = validate_with_comfyui(Path(args.validate_comfyui), plan) print( "ComfyUI meta validation passed:\n" + json.dumps(comfyui_validation, indent=2), flush=True, )
if args.dry_run: return
output_path = Path(args.output).resolve() if output_path.exists() and not args.overwrite: raise FileExistsError( f"Output already exists: {output_path} (pass --overwrite to replace)" )
metadata: dict[str, str] = { "format": "sensenova-u1.5-mot", "conversion": "mt-forcing-to-comfyui-v1", "dtype": args.dtype.upper(), "source_checkpoint": str(input_path), } config_sha256 = read_config_sha256(source_dir) if config_sha256: metadata["config_sha256"] = config_sha256
file_bytes, file_sha256 = write_streaming_safetensors( plan, output_path, metadata, compute_sha256=args.sha256, ) print( f"Wrote {output_path} ({file_bytes / (1024**3):.2f} GiB).", flush=True, )
if not args.no_manifest: manifest_path = output_path.with_suffix(".conversion.json") manifest: dict[str, Any] = { "source": str(input_path), "output": str(output_path), "shards": len(shards), "tensors": len(plan), "parameter_count": total_params, "tensor_bytes": total_bytes, "file_bytes": file_bytes, "dtype": args.dtype.upper(), } if file_sha256: manifest["sha256"] = file_sha256 if comfyui_validation is not None: manifest["comfyui_validation"] = comfyui_validation manifest_path.write_text( json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8", ) print(f"Wrote manifest: {manifest_path}", flush=True)
if __name__ == "__main__": main()README.md+12-83
assets/method.pngDeleted

Large File Pointer Details
- SHA256: 94fdaf5a7c55103174be5bae49d3dba5630fbe28c52256596d042c831f16d271
- Pointer size: 131 Bytes
- Size of remote file: 643 kB
assets/puppy-ours-01.webpDeleted

Large File Pointer Details
- SHA256: 244031eb7cca7c98fb895e4d772bd4e337558b32b7788c71d50e1fdea297019f
- Pointer size: 131 Bytes
- Size of remote file: 200 kB
assets/puppy-ours-03.webpDeleted

Large File Pointer Details
- SHA256: 6f5cf0314b5f1d168012ca421abe016c5f89b7c6a57f6897eded502833188c09
- Pointer size: 131 Bytes
- Size of remote file: 206 kB
assets/puppy-ours-08.webpDeleted

Large File Pointer Details
- SHA256: e43bcc315494806b298e2921b31273c412238b4b7b59523a403f4674a3b62194
- Pointer size: 131 Bytes
- Size of remote file: 204 kB
assets/puppy-source.webpDeleted

Large File Pointer Details
- SHA256: bc58261b12064d42483445cd7d406db15137a38b8f4c43df58120bb909e1ab58
- Pointer size: 131 Bytes
- Size of remote file: 210 kB
comfyui/LICENSEDeleted-674
comfyui/comfy/checkpoint_convert.pyDeleted-31
comfyui/comfy/ldm/sensenova/__init__.pyDeleted-1
comfyui/comfy/ldm/sensenova/conditioning.pyDeleted-272
comfyui/comfy/ldm/sensenova/model.pyDeleted-801
comfyui/comfy/ldm/sensenova/sampling.pyDeleted-69
comfyui/comfy/text_encoders/sensenova.pyDeleted-315
comfyui/comfy_extras/nodes_sensenova.pyDeleted-530
examples/comfyui_mt_forcing_3turn_api.jsonDeleted-198
examples/mt_forcing_test_input.jpgDeleted

Large File Pointer Details
- SHA256: 132c097acd123958995df9e922308a9f271f0067eb31f3c4e1fc8af0aca4c4c2
- Pointer size: 131 Bytes
- Size of remote file: 290 kB
examples/run_comfyui_workflow.pyDeleted-72
scripts/convert_to_comfyui.pyDeleted-510