├── .gitignore ├── LICENSE ├── README.md ├── chat_interface.py ├── gradio_app.py ├── lib_omost ├── canvas.py ├── memory_management.py └── pipeline.py └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | hf_download/ 2 | 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | share/python-wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | MANIFEST 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .nox/ 45 | .coverage 46 | .coverage.* 47 | .cache 48 | nosetests.xml 49 | coverage.xml 50 | *.cover 51 | *.py,cover 52 | .hypothesis/ 53 | .pytest_cache/ 54 | cover/ 55 | 56 | # Translations 57 | *.mo 58 | *.pot 59 | 60 | # Django stuff: 61 | *.log 62 | local_settings.py 63 | db.sqlite3 64 | db.sqlite3-journal 65 | 66 | # Flask stuff: 67 | instance/ 68 | .webassets-cache 69 | 70 | # Scrapy stuff: 71 | .scrapy 72 | 73 | # Sphinx documentation 74 | docs/_build/ 75 | 76 | # PyBuilder 77 | .pybuilder/ 78 | target/ 79 | 80 | # Jupyter Notebook 81 | .ipynb_checkpoints 82 | 83 | # IPython 84 | profile_default/ 85 | ipython_config.py 86 | 87 | # pyenv 88 | # For a library or package, you might want to ignore these files since the code is 89 | # intended to run in multiple environments; otherwise, check them in: 90 | # .python-version 91 | 92 | # pipenv 93 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 94 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 95 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 96 | # install all needed dependencies. 97 | #Pipfile.lock 98 | 99 | # poetry 100 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 101 | # This is especially recommended for binary packages to ensure reproducibility, and is more 102 | # commonly ignored for libraries. 103 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 104 | #poetry.lock 105 | 106 | # pdm 107 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 108 | #pdm.lock 109 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 110 | # in version control. 111 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 112 | .pdm.toml 113 | .pdm-python 114 | .pdm-build/ 115 | 116 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 117 | __pypackages__/ 118 | 119 | # Celery stuff 120 | celerybeat-schedule 121 | celerybeat.pid 122 | 123 | # SageMath parsed files 124 | *.sage.py 125 | 126 | # Environments 127 | .env 128 | .venv 129 | env/ 130 | venv/ 131 | ENV/ 132 | env.bak/ 133 | venv.bak/ 134 | 135 | # Spyder project settings 136 | .spyderproject 137 | .spyproject 138 | 139 | # Rope project settings 140 | .ropeproject 141 | 142 | # mkdocs documentation 143 | /site 144 | 145 | # mypy 146 | .mypy_cache/ 147 | .dmypy.json 148 | dmypy.json 149 | 150 | # Pyre type checker 151 | .pyre/ 152 | 153 | # pytype static type analyzer 154 | .pytype/ 155 | 156 | # Cython debug symbols 157 | cython_debug/ 158 | 159 | # PyCharm 160 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 161 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 162 | # and can be added to the global gitignore or merged into this file. For a more nuclear 163 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 164 | .idea/ 165 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Omost 2 | 3 | Omost is a project to convert LLM's coding capability to image generation (or more accurately, image composing) capability. 4 | 5 | The name `Omost` (pronunciation: almost) has two meanings: 1) everytime after you use Omost, your image is almost there; 2) the `O` mean "omni" (multi-modal) and `most` means we want to get the most out of it. 6 | 7 | Omost provides LLMs models that will write codes to compose image visual contents with Omost's virtual `Canvas` agent. This `Canvas` can be rendered by specific implementations of image generators to actually generate images. 8 | 9 | Currently, we provide 3 pretrained LLM models based on variations of Llama3 and Phi3 (see also the model notes at the end of this page). 10 | 11 | All models are trained with mixed data of (1) ground-truth annotations of several datasets including Open-Images, (2) extracted data by automatically annotating images, (3) reinforcement from DPO (Direct Preference Optimization, "whether the codes can be compiled by python 3.10 or not" as a direct preference), and (4) a small amount of tuning data from OpenAI GPT4o's multi-modal capability. 12 | 13 | # Get Started 14 | 15 | You can just use the [official HuggingFace space](https://huggingface.co/spaces/lllyasviel/Omost). 16 | 17 | Or, you can use the below deployment (requires 8GB Nvidia VRAM): 18 | 19 | git clone https://github.com/lllyasviel/Omost.git 20 | cd Omost 21 | conda create -n omost python=3.10 22 | conda activate omost 23 | pip install torch torchvision --index-url https://download.pytorch.org/whl/cu121 24 | pip install -r requirements.txt 25 | python gradio_app.py 26 | 27 | (Note that quant LLM requires `bitsandbytes` - some 9XX or 10XX or 20XX GPUs may have trouble in running it. If that happens, just use our official huggingface space.) 28 | 29 | # Screenshots 30 | 31 | (All with random seed 12345) 32 | 33 | a ragged man wearing a tattered jacket in the nineteenth century: 34 | 35 |  36 | 37 |  38 | 39 | the greatest escape after the apocalypse, the hope of all humanity: 40 | 41 |  42 | 43 |  44 | 45 | jurassic dinosaur battle: 46 | 47 |  48 | 49 |  50 | 51 | the supreme ruler with endless magic on a gothic throne, with undead armies kneeling: 52 | 53 |  54 | 55 |  56 | 57 | a funny cartoon batman fights joker: 58 | 59 |  60 | 61 |  62 | 63 | # Example Transcripts (with Conversational Editing) 64 | 65 | *(Below is a raw transcript from default model, with random seed 123456)* 66 | 67 | *(If the GitHub's code block rendering is causing troubles to reading long lines, click [here](https://raw.githubusercontent.com/lllyasviel/Omost/main/README.md) to read raw texts.)* 68 | 69 | ### User 70 | 71 | generate an image of the fierce battle of warriors and the dragon 72 | 73 | ### Assistant 74 | 75 | ```python 76 | # Initialize the canvas 77 | canvas = Canvas() 78 | 79 | # Set a global description for the canvas 80 | canvas.set_global_description( 81 | description='A fierce battle between warriors and a dragon.', 82 | detailed_descriptions=[ 83 | 'In this intense scene, a group of fierce warriors is engaged in an epic battle with a mighty dragon.', 84 | 'The warriors, clad in armor and wielding swords and shields, are positioned on the left side of the image.', 85 | 'Their expressions are determined and focused, reflecting their resolve to defeat the dragon.', 86 | 'The dragon, with its massive wings spread wide and its fiery breath illuminating the scene, dominates the center of the image.', 87 | 'Its scales glisten with a metallic sheen, and its eyes burn with a fierce intensity.', 88 | 'The background is a dark, stormy sky with flashes of lightning, adding to the drama and tension of the battle.', 89 | 'The ground is littered with debris and the remnants of previous battles, enhancing the sense of a long and brutal conflict.', 90 | 'The overall atmosphere is one of chaos and intensity, with the warriors and the dragon locked in a fierce struggle for survival.', 91 | ], 92 | tags='battle, warriors, dragon, fierce, armor, swords, shields, determined, focused, epic, intense, metallic, glistening, fiery breath, stormy sky, lightning, debris, conflict, struggle, survival, chaos, tension, drama, wings, scales, eyes, burning, illuminated', 93 | HTML_web_color_name='darkslategray', 94 | ) 95 | 96 | # Add a group of fierce warriors. 97 | canvas.add_local_description( 98 | location='on the left', 99 | offset='no offset', 100 | area='a large horizontal area', 101 | distance_to_viewer=5.0, 102 | description='A group of fierce warriors.', 103 | detailed_descriptions=[ 104 | 'The warriors, clad in gleaming armor, are positioned on the left side of the image.', 105 | 'They are armed with swords, shields, and spears, ready for battle.', 106 | 'Their faces are set with determination and focus, reflecting their resolve to defeat the dragon.', 107 | 'Some warriors are in mid-action, swinging their swords or shields, while others stand ready to strike.', 108 | 'The armor they wear is intricately designed, with symbols and patterns that signify their rank and bravery.', 109 | 'The ground beneath them is uneven and littered with debris, adding to the sense of a chaotic and intense battle.', 110 | ], 111 | tags='warriors, armor, swords, shields, spears, determined, focused, mid-action, intricate design, symbols, patterns, rank, bravery, uneven ground, debris, chaotic, intense, battle', 112 | atmosphere='Determined and focused, ready for the fierce battle.', 113 | style='Highly detailed and dynamic, capturing the intensity of the warriors.', 114 | quality_meta='High resolution with intricate details and dynamic poses.', 115 | HTML_web_color_name='darkgoldenrod', 116 | ) 117 | 118 | # Add a mighty dragon. 119 | canvas.add_local_description( 120 | location='in the center', 121 | offset='no offset', 122 | area='a large square area', 123 | distance_to_viewer=7.0, 124 | description='A mighty dragon.', 125 | detailed_descriptions=[ 126 | 'The dragon is a massive creature, dominating the center of the image with its wide-spread wings and fiery breath.', 127 | 'Its scales glisten with a metallic sheen, reflecting the light from its fiery breath.', 128 | "The dragon's eyes burn with a fierce intensity, and its teeth are sharp and menacing.", 129 | 'The wings of the dragon are powerful and spread wide, casting shadows over the battlefield.', 130 | 'The dragon’s body is muscular and covered in protective scales, with a long, sinewy tail that adds to its formidable appearance.', 131 | 'The fiery breath of the dragon illuminates the scene, casting a reddish glow over the warriors and the battlefield.', 132 | ], 133 | tags='dragon, massive, wings, fiery breath, glistening scales, metallic sheen, fierce eyes, sharp teeth, powerful wings, shadows, battlefield, muscular body, protective scales, sinewy tail, formidable, reddish glow, illumination', 134 | atmosphere='Intense and menacing, with a powerful presence.', 135 | style='Epic and dramatic, emphasizing the grandeur and danger of the dragon.', 136 | quality_meta='High resolution with dramatic lighting and detailed textures.', 137 | HTML_web_color_name='firebrick', 138 | ) 139 | 140 | # Add a stormy sky with flashes of lightning. 141 | canvas.add_local_description( 142 | location='on the top', 143 | offset='no offset', 144 | area='a large horizontal area', 145 | distance_to_viewer=10.0, 146 | description='A stormy sky with flashes of lightning.', 147 | detailed_descriptions=[ 148 | 'The background of the image is a dark, stormy sky filled with swirling clouds and flashes of lightning.', 149 | 'The sky is turbulent, with clouds dark and foreboding, adding to the dramatic tension of the battle.', 150 | 'The lightning flashes illuminate the scene, casting sharp, brief lights over the warriors and the dragon.', 151 | 'The stormy sky creates a sense of chaos and unpredictability, heightening the intensity of the battle below.', 152 | 'The overall atmosphere is one of impending doom and relentless conflict, with the storm mirroring the fierce struggle between the warriors and the dragon.', 153 | ], 154 | tags='stormy sky, dark clouds, lightning, turbulent, foreboding, dramatic tension, illumination, chaos, unpredictability, intensity, impending doom, relentless conflict, battle, warriors, dragon, swirling clouds, sharp lights, brief lights', 155 | atmosphere='Chaotic and intense, mirroring the fierce battle below.', 156 | style='Dramatic and turbulent, emphasizing the conflict and tension.', 157 | quality_meta='High resolution with dynamic lighting and detailed cloud textures.', 158 | HTML_web_color_name='midnightblue', 159 | ) 160 | 161 | # Add a debris-covered battlefield. 162 | canvas.add_local_description( 163 | location='on the bottom', 164 | offset='no offset', 165 | area='a large horizontal area', 166 | distance_to_viewer=5.0, 167 | description='A debris-covered battlefield.', 168 | detailed_descriptions=[ 169 | 'The ground of the battlefield is littered with debris, remnants of previous battles.', 170 | 'Broken weapons, shattered shields, and scattered armor pieces are strewn across the battlefield.', 171 | 'The terrain is uneven, with patches of mud and dirt, adding to the sense of a long and brutal conflict.', 172 | 'The debris-covered battlefield enhances the chaotic and intense atmosphere of the scene, reflecting the ferocity and duration of the battle.', 173 | 'The overall appearance is one of destruction and turmoil, with the remnants of previous battles serving as a grim reminder of the ongoing struggle.', 174 | ], 175 | tags='battlefield, debris, broken weapons, shattered shields, scattered armor, uneven terrain, mud, dirt, brutal conflict, chaos, intensity, destruction, turmoil, previous battles, ongoing struggle, remnants, ferocity, duration', 176 | atmosphere='Chaotic and intense, reflecting the ferocity of the battle.', 177 | style='Detailed and realistic, emphasizing the destruction and chaos.', 178 | quality_meta='High resolution with detailed textures and realistic debris.', 179 | HTML_web_color_name='darkolivegreen', 180 | ) 181 | ``` 182 | 183 | ### User 184 | 185 | change the dragon to a dinosaur 186 | 187 | ### Assistant 188 | 189 | ```python 190 | # Initialize the canvas 191 | canvas = Canvas() 192 | 193 | # Set a global description for the canvas 194 | canvas.set_global_description( 195 | description='A fierce battle between warriors and a dinosaur.', 196 | detailed_descriptions=[ 197 | 'In this intense scene, a group of fierce warriors is engaged in an epic battle with a mighty dinosaur.', 198 | 'The warriors, clad in armor and wielding swords and shields, are positioned on the left side of the image.', 199 | 'Their expressions are determined and focused, reflecting their resolve to defeat the dinosaur.', 200 | 'The dinosaur, with its massive body and powerful legs, dominates the center of the image.', 201 | 'Its scales glisten with a metallic sheen, and its eyes burn with a fierce intensity.', 202 | 'The background is a dark, stormy sky with flashes of lightning, adding to the drama and tension of the battle.', 203 | 'The ground is littered with debris and the remnants of previous battles, enhancing the sense of a long and brutal conflict.', 204 | 'The overall atmosphere is one of chaos and intensity, with the warriors and the dinosaur locked in a fierce struggle for survival.', 205 | ], 206 | tags='battle, warriors, dinosaur, fierce, armor, swords, shields, determined, focused, epic, intense, metallic, glistening, stormy sky, lightning, debris, conflict, struggle, survival, chaos, tension, drama, powerful legs, scales, eyes, burning, illuminated', 207 | HTML_web_color_name='darkslategray', 208 | ) 209 | 210 | # Add a group of fierce warriors. 211 | canvas.add_local_description( 212 | location='on the left', 213 | offset='no offset', 214 | area='a large horizontal area', 215 | distance_to_viewer=5.0, 216 | description='A group of fierce warriors.', 217 | detailed_descriptions=[ 218 | 'The warriors, clad in gleaming armor, are positioned on the left side of the image.', 219 | 'They are armed with swords, shields, and spears, ready for battle.', 220 | 'Their faces are set with determination and focus, reflecting their resolve to defeat the dinosaur.', 221 | 'Some warriors are in mid-action, swinging their swords or shields, while others stand ready to strike.', 222 | 'The armor they wear is intricately designed, with symbols and patterns that signify their rank and bravery.', 223 | 'The ground beneath them is uneven and littered with debris, adding to the sense of a chaotic and intense battle.', 224 | ], 225 | tags='warriors, armor, swords, shields, spears, determined, focused, mid-action, intricate design, symbols, patterns, rank, bravery, uneven ground, debris, chaotic, intense, battle', 226 | atmosphere='Determined and focused, ready for the fierce battle.', 227 | style='Highly detailed and dynamic, capturing the intensity of the warriors.', 228 | quality_meta='High resolution with intricate details and dynamic poses.', 229 | HTML_web_color_name='darkgoldenrod', 230 | ) 231 | 232 | # Add a mighty dinosaur. 233 | canvas.add_local_description( 234 | location='in the center', 235 | offset='no offset', 236 | area='a large square area', 237 | distance_to_viewer=7.0, 238 | description='A mighty dinosaur.', 239 | detailed_descriptions=[ 240 | 'The dinosaur is a massive creature, dominating the center of the image with its powerful legs and fierce roar.', 241 | 'Its scales glisten with a metallic sheen, reflecting the light from the stormy sky.', 242 | "The dinosaur's eyes burn with a fierce intensity, and its teeth are sharp and menacing.", 243 | 'The powerful legs of the dinosaur are muscular and add to its formidable appearance.', 244 | 'The ground shakes beneath its feet, enhancing the sense of a long and brutal conflict.', 245 | 'The overall appearance is one of destruction and turmoil, with the dinosaur adding to the chaotic atmosphere.', 246 | ], 247 | tags='dinosaur, massive, powerful legs, fierce roar, glistening scales, metallic sheen, fierce eyes, sharp teeth, muscular legs, formidable, ground shaking, destruction, turmoil, chaos, battle', 248 | atmosphere='Intense and menacing, with a powerful presence.', 249 | style='Epic and dramatic, emphasizing the grandeur and danger of the dinosaur.', 250 | quality_meta='High resolution with dramatic lighting and detailed textures.', 251 | HTML_web_color_name='firebrick', 252 | ) 253 | 254 | # Add a stormy sky with flashes of lightning. 255 | canvas.add_local_description( 256 | location='on the top', 257 | offset='no offset', 258 | area='a large horizontal area', 259 | distance_to_viewer=10.0, 260 | description='A stormy sky with flashes of lightning.', 261 | detailed_descriptions=[ 262 | 'The background of the image is a dark, stormy sky filled with swirling clouds and flashes of lightning.', 263 | 'The sky is turbulent, with clouds dark and foreboding, adding to the dramatic tension of the battle.', 264 | 'The lightning flashes illuminate the scene, casting sharp, brief lights over the warriors and the dinosaur.', 265 | 'The stormy sky creates a sense of chaos and unpredictability, heightening the intensity of the battle below.', 266 | 'The overall atmosphere is one of impending doom and relentless conflict, with the storm mirroring the fierce struggle between the warriors and the dinosaur.', 267 | ], 268 | tags='stormy sky, dark clouds, lightning, turbulent, foreboding, dramatic tension, illumination, chaos, unpredictability, intensity, impending doom, relentless conflict, battle, warriors, dinosaur, swirling clouds, sharp lights, brief lights', 269 | atmosphere='Chaotic and intense, mirroring the fierce battle below.', 270 | style='Dramatic and turbulent, emphasizing the conflict and tension.', 271 | quality_meta='High resolution with dynamic lighting and detailed cloud textures.', 272 | HTML_web_color_name='midnightblue', 273 | ) 274 | 275 | # Add a debris-covered battlefield. 276 | canvas.add_local_description( 277 | location='on the bottom', 278 | offset='no offset', 279 | area='a large horizontal area', 280 | distance_to_viewer=5.0, 281 | description='A debris-covered battlefield.', 282 | detailed_descriptions=[ 283 | 'The ground of the battlefield is littered with debris, remnants of previous battles.', 284 | 'Broken weapons, shattered shields, and scattered armor pieces are strewn across the battlefield.', 285 | 'The terrain is uneven, with patches of mud and dirt, adding to the sense of a long and brutal conflict.', 286 | 'The debris-covered battlefield enhances the chaotic and intense atmosphere of the scene, reflecting the ferocity and duration of the battle.', 287 | 'The overall appearance is one of destruction and turmoil, with the remnants of previous battles serving as a grim reminder of the ongoing struggle.', 288 | ], 289 | tags='battlefield, debris, broken weapons, shattered shields, scattered armor, uneven terrain, mud, dirt, brutal conflict, chaos, intensity, destruction, turmoil, previous battles, ongoing struggle, remnants, ferocity, duration', 290 | atmosphere='Chaotic and intense, reflecting the ferocity of the battle.', 291 | style='Detailed and realistic, emphasizing the destruction and chaos.', 292 | quality_meta='High resolution with detailed textures and realistic debris.', 293 | HTML_web_color_name='darkolivegreen', 294 | ) 295 | ``` 296 | 297 | (User can click the render button to actually render the image from any of those `Canvas` instances.) 298 | 299 |  300 | 301 |  302 | 303 |  304 | 305 | # Symbols 306 | 307 | All Omost LLMs are trained to obey the following symbols 308 | 309 | ```python 310 | class Canvas: 311 | def set_global_description( 312 | self, 313 | description: str, 314 | detailed_descriptions: list[str], 315 | tags: str, 316 | HTML_web_color_name: str 317 | ): 318 | pass 319 | 320 | def add_local_description( 321 | self, 322 | location: str, 323 | offset: str, 324 | area: str, 325 | distance_to_viewer: float, 326 | description: str, 327 | detailed_descriptions: list[str], 328 | tags: str, 329 | atmosphere: str, 330 | style: str, 331 | quality_meta: str, 332 | HTML_web_color_name: str 333 | ): 334 | assert location in [ 335 | "in the center", 336 | "on the left", 337 | "on the right", 338 | "on the top", 339 | "on the bottom", 340 | "on the top-left", 341 | "on the top-right", 342 | "on the bottom-left", 343 | "on the bottom-right" 344 | ] 345 | assert offset in [ 346 | "no offset", 347 | "slightly to the left", 348 | "slightly to the right", 349 | "slightly to the upper", 350 | "slightly to the lower", 351 | "slightly to the upper-left", 352 | "slightly to the upper-right", 353 | "slightly to the lower-left", 354 | "slightly to the lower-right" 355 | ] 356 | assert area in [ 357 | "a small square area", 358 | "a small vertical area", 359 | "a small horizontal area", 360 | "a medium-sized square area", 361 | "a medium-sized vertical area", 362 | "a medium-sized horizontal area", 363 | "a large square area", 364 | "a large vertical area", 365 | "a large horizontal area" 366 | ] 367 | assert distance_to_viewer > 0 368 | pass 369 | ``` 370 | 371 | During training, the above symbols are associated with specific concepts and use cases related to image generation. 372 | 373 | The design is to make those codes easy to learn for LLMs, but also easy to handle for diffusion models. 374 | 375 | Lets breakdown each part: 376 | 377 | ## Function: Canvas.set_global_description and Canvas.add_local_description 378 | 379 | They set descriptions to images. The meanings of the parameters are same for them, with `add_local_description` having more fields than `set_global_description`. 380 | 381 | The `set_global_description` annotate entire image, while `add_local_description` annotates a part of image. 382 | 383 | ## Parameter: description and detailed_descriptions 384 | 385 | Let us introduce a concept called "sub-prompt". If a prompt is less than 75 tokens, and is self-supported to describe a thing without relying on other prompts, we call it a "sub-prompt". 386 | 387 | The `description` is a sub-prompt, and the `detailed_descriptions` is a list of sub-prompts. 388 | 389 | Note that each sub-prompt is strictly less than 75 tokens (and typically less than 40 tokens), you can safely encode them with any clip without worrying the truncation position affecting the semantics. 390 | 391 | The design of sub-prompt also allows more satisfying text encoding based on greedy merge. For example, if you have 392 | 393 | sub-prompt A: 25 tokens 394 | sub-prompt B: 35 tokens 395 | sub-prompt C: 5 tokens 396 | sub-prompt D: 60 tokens 397 | sub-prompt E: 15 tokens 398 | sub-prompt F: 25 tokens 399 | 400 | and since every sub-prompt is promised to be self-supported to describe a thing independently, we can use greedy method to merge them to bags like 401 | 402 | bag 1 {A, B, C} : 65 tokens 403 | bag 2 {D} : 60 tokens 404 | bag 1 {E, F} : 40 tokens 405 | 406 | where each bag is less than 75 tokens and can be encoded by any clip in one pass (and then concat them). 407 | 408 | Encoding texts in this way will make sure that text-encoder will never make semantic truncation mistakes. 409 | 410 | One may ask - if all sub-prompts are less than 75 tokens with independent semantics, why not just encode them without merge and then concat? This is mainly because we want the text embedding to be more coherent. For example, lets say sub-prompt A is "a man" while sub-prompt B is "handsome, professional", then merging them before encoding will give you a more mixed text embedding concept with coherent features of a handsome professional man. 411 | 412 | All Omost LLMs are trained to give strictly well-defined sub-prompts. You can make use of these definitions to design lossless text encoding methods. 413 | 414 | ### Parameter: location, offset, area 415 | 416 | The three parameters defines a bounding box. Note that they must obey 417 | 418 | ```python 419 | assert location in [ 420 | "in the center", 421 | "on the left", 422 | "on the right", 423 | "on the top", 424 | "on the bottom", 425 | "on the top-left", 426 | "on the top-right", 427 | "on the bottom-left", 428 | "on the bottom-right" 429 | ] 430 | assert offset in [ 431 | "no offset", 432 | "slightly to the left", 433 | "slightly to the right", 434 | "slightly to the upper", 435 | "slightly to the lower", 436 | "slightly to the upper-left", 437 | "slightly to the upper-right", 438 | "slightly to the lower-left", 439 | "slightly to the lower-right" 440 | ] 441 | assert area in [ 442 | "a small square area", 443 | "a small vertical area", 444 | "a small horizontal area", 445 | "a medium-sized square area", 446 | "a medium-sized vertical area", 447 | "a medium-sized horizontal area", 448 | "a large square area", 449 | "a large vertical area", 450 | "a large horizontal area" 451 | ] 452 | ``` 453 | 454 | First we divide a canvas into 3*3=9 locations: 455 | 456 |  457 | 458 | Then we further divide each location to 3\*3 offsets, resulting in 9\*9=81 positions: 459 | 460 |  461 | 462 | Using these positions as centers, we further define 9 types of bounding boxes: 463 | 464 |  465 | 466 | We can see that this method allows 9\*9\*9=729 different bounding boxes, covering almost all common possible locations of an object in the image. 467 | 468 | One may argue that why this is necessary - why not just let the LLMs to learn pixel index or x, y coordinates - and should that be much more accurate? Below is several of my notes: 469 | 470 | 1. I have tried several representations, including pixel index like {x=32, y=16, w=58, h=99}, or margin pixels like {left=32, right=15, top=27, bottom=33}, or percentage pixel index like {x=0.124, y=0.65, w=0.335, h=0.251}, or percentage margin like {left=0.251, right=0.154, top=0.254, bottom=0.441}. The result is that opensource LLMs are really not very good at learning these representations even for Llama3 (perhaps GPT4o can learn it). Sometimes it works sometimes it gives completely random numbers. Note that our problem is very different from MLLM. The vision-LLM usually have image embedding as inputs and in that case estimating numeric position is like a look-up table problem and can somewhat be learned, but our case is where the LLM need to generate every composition from scratch without help of any image embedding to look-up. 471 | 2. But the natural language like "on the right", "slightly to the top-right", "a small vertical area" etc, works very well. The model converges very fast and the learning is stable. It aligns to the pretrained knowledge of LLMs very well. 472 | 3. I have also tried adding some special tokens to represent spatial locations and also train the embedding layers. But that model is very difficult to train and debug. Also, the token-embedding-based method needs many hyperparameter tuning everytime we change the LLM - for example when changing from Llama3 to Phi, if we use the token-embedding method, we need to design training parameters again. 473 | 4. The number 9\*9\*9=729 is not really a small number from the perspective of bounding box proposals. This can also be called ROI (region of interest) and some old semantic segmentation tech uses (RPN) Region Proposal Network to produce a similar number (<1000) of regions. 474 | 5. Most region-guided diffusion methods are coarse-level methods (like multi-diffusion and attention couple and gligen), and they do not need pixel-perfect regions. 475 | 6. These are very personal results from me - if you are working on some similar multi-modal LLM research, using pixel indices is completely okay, worth trying, and probably other training methods can also achieve a robust system. 476 | 477 | ### Parameter: distance_to_viewer and HTML_web_color_name 478 | 479 | The `distance_to_viewer` can be viewed as relative depth. Note that this value's absolute number is not reliable at all (because opensource LLMs are not very good at producing image-space numbers) and it should only be used in sorting elements into background-to-foreground layers. 480 | 481 | You can always use `distance_to_viewer` to sort all local elements before rendering them using a diffusion model. The global description can be always viewed as the most far away background layer. 482 | 483 | The `HTML_web_color_name` is one of these: 484 | 485 | ```python 486 | possible_HTML_web_color_names = { # r, g, b 487 | 'aliceblue': (240, 248, 255), 'antiquewhite': (250, 235, 215), 'aqua': (0, 255, 255), 488 | 'aquamarine': (127, 255, 212), 'azure': (240, 255, 255), 'beige': (245, 245, 220), 489 | 'bisque': (255, 228, 196), 'black': (0, 0, 0), 'blanchedalmond': (255, 235, 205), 'blue': (0, 0, 255), 490 | 'blueviolet': (138, 43, 226), 'brown': (165, 42, 42), 'burlywood': (222, 184, 135), 491 | 'cadetblue': (95, 158, 160), 'chartreuse': (127, 255, 0), 'chocolate': (210, 105, 30), 492 | 'coral': (255, 127, 80), 'cornflowerblue': (100, 149, 237), 'cornsilk': (255, 248, 220), 493 | 'crimson': (220, 20, 60), 'cyan': (0, 255, 255), 'darkblue': (0, 0, 139), 'darkcyan': (0, 139, 139), 494 | 'darkgoldenrod': (184, 134, 11), 'darkgray': (169, 169, 169), 'darkgrey': (169, 169, 169), 495 | 'darkgreen': (0, 100, 0), 'darkkhaki': (189, 183, 107), 'darkmagenta': (139, 0, 139), 496 | 'darkolivegreen': (85, 107, 47), 'darkorange': (255, 140, 0), 'darkorchid': (153, 50, 204), 497 | 'darkred': (139, 0, 0), 'darksalmon': (233, 150, 122), 'darkseagreen': (143, 188, 143), 498 | 'darkslateblue': (72, 61, 139), 'darkslategray': (47, 79, 79), 'darkslategrey': (47, 79, 79), 499 | 'darkturquoise': (0, 206, 209), 'darkviolet': (148, 0, 211), 'deeppink': (255, 20, 147), 500 | 'deepskyblue': (0, 191, 255), 'dimgray': (105, 105, 105), 'dimgrey': (105, 105, 105), 501 | 'dodgerblue': (30, 144, 255), 'firebrick': (178, 34, 34), 'floralwhite': (255, 250, 240), 502 | 'forestgreen': (34, 139, 34), 'fuchsia': (255, 0, 255), 'gainsboro': (220, 220, 220), 503 | 'ghostwhite': (248, 248, 255), 'gold': (255, 215, 0), 'goldenrod': (218, 165, 32), 504 | 'gray': (128, 128, 128), 'grey': (128, 128, 128), 'green': (0, 128, 0), 'greenyellow': (173, 255, 47), 505 | 'honeydew': (240, 255, 240), 'hotpink': (255, 105, 180), 'indianred': (205, 92, 92), 506 | 'indigo': (75, 0, 130), 'ivory': (255, 255, 240), 'khaki': (240, 230, 140), 'lavender': (230, 230, 250), 507 | 'lavenderblush': (255, 240, 245), 'lawngreen': (124, 252, 0), 'lemonchiffon': (255, 250, 205), 508 | 'lightblue': (173, 216, 230), 'lightcoral': (240, 128, 128), 'lightcyan': (224, 255, 255), 509 | 'lightgoldenrodyellow': (250, 250, 210), 'lightgray': (211, 211, 211), 'lightgrey': (211, 211, 211), 510 | 'lightgreen': (144, 238, 144), 'lightpink': (255, 182, 193), 'lightsalmon': (255, 160, 122), 511 | 'lightseagreen': (32, 178, 170), 'lightskyblue': (135, 206, 250), 'lightslategray': (119, 136, 153), 512 | 'lightslategrey': (119, 136, 153), 'lightsteelblue': (176, 196, 222), 'lightyellow': (255, 255, 224), 513 | 'lime': (0, 255, 0), 'limegreen': (50, 205, 50), 'linen': (250, 240, 230), 'magenta': (255, 0, 255), 514 | 'maroon': (128, 0, 0), 'mediumaquamarine': (102, 205, 170), 'mediumblue': (0, 0, 205), 515 | 'mediumorchid': (186, 85, 211), 'mediumpurple': (147, 112, 219), 'mediumseagreen': (60, 179, 113), 516 | 'mediumslateblue': (123, 104, 238), 'mediumspringgreen': (0, 250, 154), 517 | 'mediumturquoise': (72, 209, 204), 'mediumvioletred': (199, 21, 133), 'midnightblue': (25, 25, 112), 518 | 'mintcream': (245, 255, 250), 'mistyrose': (255, 228, 225), 'moccasin': (255, 228, 181), 519 | 'navajowhite': (255, 222, 173), 'navy': (0, 0, 128), 'navyblue': (0, 0, 128), 520 | 'oldlace': (253, 245, 230), 'olive': (128, 128, 0), 'olivedrab': (107, 142, 35), 521 | 'orange': (255, 165, 0), 'orangered': (255, 69, 0), 'orchid': (218, 112, 214), 522 | 'palegoldenrod': (238, 232, 170), 'palegreen': (152, 251, 152), 'paleturquoise': (175, 238, 238), 523 | 'palevioletred': (219, 112, 147), 'papayawhip': (255, 239, 213), 'peachpuff': (255, 218, 185), 524 | 'peru': (205, 133, 63), 'pink': (255, 192, 203), 'plum': (221, 160, 221), 'powderblue': (176, 224, 230), 525 | 'purple': (128, 0, 128), 'rebeccapurple': (102, 51, 153), 'red': (255, 0, 0), 526 | 'rosybrown': (188, 143, 143), 'royalblue': (65, 105, 225), 'saddlebrown': (139, 69, 19), 527 | 'salmon': (250, 128, 114), 'sandybrown': (244, 164, 96), 'seagreen': (46, 139, 87), 528 | 'seashell': (255, 245, 238), 'sienna': (160, 82, 45), 'silver': (192, 192, 192), 529 | 'skyblue': (135, 206, 235), 'slateblue': (106, 90, 205), 'slategray': (112, 128, 144), 530 | 'slategrey': (112, 128, 144), 'snow': (255, 250, 250), 'springgreen': (0, 255, 127), 531 | 'steelblue': (70, 130, 180), 'tan': (210, 180, 140), 'teal': (0, 128, 128), 'thistle': (216, 191, 216), 532 | 'tomato': (255, 99, 71), 'turquoise': (64, 224, 208), 'violet': (238, 130, 238), 533 | 'wheat': (245, 222, 179), 'white': (255, 255, 255), 'whitesmoke': (245, 245, 245), 534 | 'yellow': (255, 255, 0), 'yellowgreen': (154, 205, 50) 535 | } 536 | ``` 537 | 538 | By combining `distance_to_viewer` and `HTML_web_color_name`, you can draw a very coarse image of the composition. For example, if the LLM works well, "a green bottle in front of a red bottle on a wood table in a dark room" should make it possible for you to compute an image like: 539 | 540 |  541 | 542 | You can use this image as an initial latent and use denoise strength like 0.95 to 0.99 to generate the image. 543 | 544 | Or if you do not like this and still prefer to let diffusion models to generate from zero-mean (even when you know that most diffusion models have tsnr problems), you can ignore this image and or just use this image as a debugger. 545 | 546 | Besides, the layer sorting can also be useful in some very special attention formulation - we will discuss this later. 547 | 548 | # Parameter: tags and atmosphere and style and quality_meta 549 | 550 | The `tags` is designed as a possible replacement for the `description` since many diffusion models prefer tags. If used with anime models, one may hard code some logics to replace all "girl" to "1girl". If used with Pony then probably always hard code adding "score_9, score_8 ..." to this. 551 | 552 | The `atmosphere` and `style` and `quality_meta` are some experimental parameters without very specific use cases. Current we can just treat them as sub-prompts and involve them in the greedy merge of sub-prompt bags. This in my experiments will improve the atmosphere and quality a bit. 553 | 554 | # A Baseline Renderer 555 | 556 | In this repo, we provide a baseline render for Omost LLMs based on attention manipulation. 557 | 558 | ### Regional Prompter 559 | 560 | As of 2024, if we want to achieve a region guided diffusion system, some possible options are: 561 | 562 | 1. multi-diffusion / mixture-of-diffusers: these method run UNet on different locations, and then merge the estimated epsilon or x0 using weights or masks for different regions. 563 | 2. attention decomposition: lets say attention is like `y=softmax(q@k)@v`, then one can achieve attention decomposition like `y=mask_A * softmax(q@k_A)@v_A + mask_B * softmax(q@k_B)@v_B` where mask_A, k_A, v_A are masks, k, v for region A; mask_B, k_B, v_B are masks, k, v for region B. This method usually yields image quality a bit better than (1) and some people call it Attention Couple or Region Prompter Attention Mode. But this method has a consideration: the mask only makes regional attention numerically possible, but it does not force the UNet to really attend its activations in those regions. That is to say, the attention is indeed masked, but there is no promise that the attention softmax will really be activated in the masked area, and there is also no promise that the attention softmax will never be activated outside the masked area. 564 | 3. attention score manipulation: this is a more advanced method compared to (2). It directly manipulates the attention scores to make sure that the activations in mask each area are encouraged and those outside the masks are discouraged. The formulation is like `y=softmax(modify(q@k))@v` where `modify()` is a complicated non-linear function with many normalizations and tricks to change the score's distributions. This method goes beyond a simple masked attention to really make sure that those layers get wanted activations. A typical example is [Dense Diffusion](https://github.com/naver-ai/DenseDiffusion). 565 | 4. gradient optimization: since the attention can tell us where each part is corresponding to what prompts, we can split prompts into segments and then get attention activations to each prompt segment. Then we compare those activations with external masks to compute a loss function, and back propagate the gradients. Those methods are usually very high quality but VRAM hungry and very slow. Typical methods are [BoxDiff](https://github.com/showlab/BoxDiff) and [Attend-and-Excite](https://github.com/yuval-alaluf/Attend-and-Excite). 566 | 5. Use external control models like gligen and [InstanceDiffusion](https://github.com/frank-xwang/InstanceDiffusion). Those methods give the highest benchmark performance on region following but will also introduce some style offset to the base model since they are trained parameters. Also, those methods need to convert prompts to vectors and usually do not support prompts of arbitary length (but one can use them together with other attention methods to achieve arbitrary length). 567 | 6. Some more possible layer options like layerdiffuse and [mulan](https://mulan-dataset.github.io/). 568 | 569 | In this repo I wrote a baseline formulation based on (3). I consider this parameter-free formulation as a very standard baseline implementation that will almost introduce zero style offsets or quality degradation. In the future we may consider training some parametrized methods for Omost. 570 | 571 | Lets consider an extremely simplified image with only 2\*2=4 pixels: 572 | 573 |  574 | 575 | Then we have three prompts "two cats", "a black cat", "a white cat", and we have their masks: 576 | 577 |  578 | 579 | Then we can draw this attention score table: 580 | 581 |  582 | 583 | where the upper arrow mean that we want to encourage the activation, while the lower arrow means we want to get rid of those activation. 584 | 585 | This manipulation directly modify attention scores and compute all prompts conditions in one single SDP attention pass. (See also the codes for more details.) 586 | 587 | ### Prompt Prefix Tree 588 | 589 | In this repo, I also included another trick that I find out to improve prompt understanding a lot. Lets call it a Prompt Prefix Tree. The motivation is that, since now that all our prompts are sub-prompts that can be merged arbitrarily (recall that all sub-prompts are strictly less than 75 tokens and typically less than 40 tokens, describe independent concepts, and can be arbitrarily merged as common prompts for clip to encode), finding a better method to merge those sub-prompts may improve the results and prompt interpretation. 590 | 591 | For example below is a tree structure of global/local overall/detailed descriptions. 592 | 593 |  594 | 595 | The idea is that, since all sub-prompts can be merged arbitrarily, we can use the paths in this tree graph as prompts. 596 | 597 | For example the below path will give a prompt "A cat and a dog. The cat on sofa." 598 | 599 |  600 | 601 | Note that we can use this together with greedy subprompt bag merging when a path exceed 75 tokens. And, if a path has remaining place to contain more subprompts, the greedy subprompt bag merging will also take care of it. And again, since all sub prompts describe independent concepts, the greedy subprompt bag merging never makes semantic truncation mistakes. So satisfying! 602 | 603 | # Model Notes 604 | 605 | Currently, we provide 3 models (you can get them by adding the prefix `https://huggingface.co/lllyasviel/` to the below names): 606 | 607 | omost-llama-3-8b 608 | omost-dolphin-2.9-llama3-8b 609 | omost-phi-3-mini-128k 610 | 611 | And their quant versions: 612 | 613 | omost-llama-3-8b-4bits 614 | omost-dolphin-2.9-llama3-8b-4bits 615 | omost-phi-3-mini-128k-8bits 616 | 617 | Some notes: 618 | 619 | 1. The recommended quant for `omost-llama-3-8b` is 4bits, and for `omost-phi-3-mini-128k` (3.8B) is 8 bits. They all fit in 8GB VRAM without offloads. The performance degradation caused by quant is very minimal and I personally never observed any evidences of degradation. However, quant `omost-phi-3-mini-128k` into 4 bits is not recommended since I noticed some obvious performance degradation. The 4bit inference of `omost-phi-3-mini-128k` should be viewed as a last method in extreme cases when you really do not have more capable GPUs. 620 | 2. My user study shows that `omost-llama-3-8b-4bits` > `omost-dolphin-2.9-llama3-8b-4bits` > `omost-phi-3-mini-128k-8bits`. So in most cases one should just use `omost-llama-3-8b-4bits`. 621 | 3. The `omost-llama-3-8b` and `omost-phi-3-mini-128k` are trained with filtered safe data without NSFW or inappropriate contents. See (4) if you need a different option. 622 | 4. The `omost-dolphin-2.9-llama3-8b` is trained with all data WITHOUT any filtering. You must apply your own safety alignment methods if you expose any service of `omost-dolphin-2.9-llama3-8b` to public. 623 | 5. Note that the filtering in (3) is not because of any policy - the reason is that I noticed slight instability in training gradients in those models since they are pretrained with instruct following regulated by safety alignment, causing the performance to degrade a bit. But the instruct following of `omost-dolphin-2.9-llama3-8b` is pretrained with community efforts and do not have this problem. 624 | 6. The 128k context length of `omost-phi-3-mini-128k` cannot be trusted. The performance of it will degrade a lot after the tokens reach about 8k. One should just view it as a model with about 8k content length. 625 | 7. A model of 8k context length can do about 5 to 6 rounds of conversational editing. If you are about to run out of token lengths, use the UI to modify your message and respond again (this can be done with infinite times). 626 | 8. All models are fully trained with our H100 clusters at precision fp16 without any tricks like quant or Q-LoRA etc. The optimizer is Adam without any tricks. 627 | 9. You must also follow the licenses of Llama-3 and Phi-3. 628 | 10. You can request us to train on other LLMs if reasonable and necessary. 629 | 630 | # Cite 631 | 632 | @Misc{omost, 633 | author = {Omost Team}, 634 | title = {Omost GitHub Page}, 635 | year = {2024}, 636 | } 637 | 638 | # Related Work 639 | 640 | Also read ... 641 | 642 | [DOCCI: Descriptions of Connected and Contrasting Images](https://google.github.io/docci/) 643 | 644 | [(RPG-DiffusionMaster) Mastering Text-to-Image Diffusion: Recaptioning, Planning, and Generating with Multimodal LLMs](https://github.com/YangLing0818/RPG-DiffusionMaster) 645 | 646 | [Ranni: Taming Text-to-Image Diffusion for Accurate Instruction Following](https://arxiv.org/abs/2311.17002) 647 | 648 | [LLM-grounded Diffusion: Enhancing Prompt Understanding of Text-to-Image Diffusion Models with Large Language Models](https://arxiv.org/abs/2305.13655) and [Self-correcting LLM-controlled Diffusion Models](https://arxiv.org/abs/2311.16090) 649 | 650 | [MultiDiffusion: Fusing Diffusion Paths for Controlled Image Generation](https://multidiffusion.github.io/) 651 | 652 | [sd-webui-regional-prompter](https://github.com/hako-mikan/sd-webui-regional-prompter) 653 | 654 | (please open issue or email me if you want to add more links here) 655 | 656 | 657 | -------------------------------------------------------------------------------- /chat_interface.py: -------------------------------------------------------------------------------- 1 | """ 2 | This file defines a useful high-level abstraction to build Gradio chatbots: ChatInterface. 3 | """ 4 | 5 | from __future__ import annotations 6 | 7 | import inspect 8 | from typing import AsyncGenerator, Callable, Literal, Union, cast 9 | 10 | import anyio 11 | from gradio_client.documentation import document 12 | 13 | from gradio.blocks import Blocks 14 | from gradio.components import ( 15 | Button, 16 | Chatbot, 17 | Component, 18 | Markdown, 19 | MultimodalTextbox, 20 | State, 21 | Textbox, 22 | get_component_instance, 23 | Dataset, 24 | ) 25 | from gradio.events import Dependency, on 26 | from gradio.helpers import special_args 27 | from gradio.layouts import Accordion, Group, Row 28 | from gradio.routes import Request 29 | from gradio.themes import ThemeClass as Theme 30 | from gradio.utils import SyncToAsyncIterator, async_iteration, async_lambda 31 | 32 | 33 | @document() 34 | class ChatInterface(Blocks): 35 | """ 36 | ChatInterface is Gradio's high-level abstraction for creating chatbot UIs, and allows you to create 37 | a web-based demo around a chatbot model in a few lines of code. Only one parameter is required: fn, which 38 | takes a function that governs the response of the chatbot based on the user input and chat history. Additional 39 | parameters can be used to control the appearance and behavior of the demo. 40 | 41 | Example: 42 | import gradio as gr 43 | 44 | def echo(message, history): 45 | return message 46 | 47 | demo = gr.ChatInterface(fn=echo, examples=["hello", "hola", "merhaba"], title="Echo Bot") 48 | demo.launch() 49 | Demos: chatinterface_multimodal, chatinterface_random_response, chatinterface_streaming_echo 50 | Guides: creating-a-chatbot-fast, sharing-your-app 51 | """ 52 | 53 | def __init__( 54 | self, 55 | fn: Callable, 56 | post_fn: Callable, 57 | pre_fn: Callable, 58 | chatbot: Chatbot, 59 | *, 60 | post_fn_kwargs: dict = None, 61 | pre_fn_kwargs: dict = None, 62 | multimodal: bool = False, 63 | textbox: Textbox | MultimodalTextbox | None = None, 64 | additional_inputs: str | Component | list[str | Component] | None = None, 65 | additional_inputs_accordion_name: str | None = None, 66 | additional_inputs_accordion: str | Accordion | None = None, 67 | examples: Dataset = None, 68 | title: str | None = None, 69 | description: str | None = None, 70 | theme: Theme | str | None = None, 71 | css: str | None = None, 72 | js: str | None = None, 73 | head: str | None = None, 74 | analytics_enabled: bool | None = None, 75 | submit_btn: str | None | Button = "Submit", 76 | stop_btn: str | None | Button = "Stop", 77 | retry_btn: str | None | Button = "🔄 Retry", 78 | undo_btn: str | None | Button = "↩️ Undo", 79 | clear_btn: str | None | Button = "🗑️ Clear", 80 | autofocus: bool = True, 81 | concurrency_limit: int | None | Literal["default"] = "default", 82 | fill_height: bool = True, 83 | delete_cache: tuple[int, int] | None = None, 84 | ): 85 | super().__init__( 86 | analytics_enabled=analytics_enabled, 87 | mode="chat_interface", 88 | css=css, 89 | title=title or "Gradio", 90 | theme=theme, 91 | js=js, 92 | head=head, 93 | fill_height=fill_height, 94 | delete_cache=delete_cache, 95 | ) 96 | 97 | if post_fn_kwargs is None: 98 | post_fn_kwargs = [] 99 | 100 | self.post_fn = post_fn 101 | self.post_fn_kwargs = post_fn_kwargs 102 | 103 | self.pre_fn = pre_fn 104 | self.pre_fn_kwargs = pre_fn_kwargs 105 | 106 | self.interrupter = State(None) 107 | 108 | self.multimodal = multimodal 109 | self.concurrency_limit = concurrency_limit 110 | self.fn = fn 111 | self.is_async = inspect.iscoroutinefunction( 112 | self.fn 113 | ) or inspect.isasyncgenfunction(self.fn) 114 | self.is_generator = inspect.isgeneratorfunction( 115 | self.fn 116 | ) or inspect.isasyncgenfunction(self.fn) 117 | 118 | if additional_inputs: 119 | if not isinstance(additional_inputs, list): 120 | additional_inputs = [additional_inputs] 121 | self.additional_inputs = [ 122 | get_component_instance(i) 123 | for i in additional_inputs # type: ignore 124 | ] 125 | else: 126 | self.additional_inputs = [] 127 | if additional_inputs_accordion_name is not None: 128 | print( 129 | "The `additional_inputs_accordion_name` parameter is deprecated and will be removed in a future version of Gradio. Use the `additional_inputs_accordion` parameter instead." 130 | ) 131 | self.additional_inputs_accordion_params = { 132 | "label": additional_inputs_accordion_name 133 | } 134 | if additional_inputs_accordion is None: 135 | self.additional_inputs_accordion_params = { 136 | "label": "Additional Inputs", 137 | "open": False, 138 | } 139 | elif isinstance(additional_inputs_accordion, str): 140 | self.additional_inputs_accordion_params = { 141 | "label": additional_inputs_accordion 142 | } 143 | elif isinstance(additional_inputs_accordion, Accordion): 144 | self.additional_inputs_accordion_params = ( 145 | additional_inputs_accordion.recover_kwargs( 146 | additional_inputs_accordion.get_config() 147 | ) 148 | ) 149 | else: 150 | raise ValueError( 151 | f"The `additional_inputs_accordion` parameter must be a string or gr.Accordion, not {type(additional_inputs_accordion)}" 152 | ) 153 | 154 | with self: 155 | if title: 156 | Markdown( 157 | f"