Spaces:
Running on Zero
Running on Zero
Upload folder using huggingface_hub
Browse files- LICENSE +202 -0
- README.md +25 -6
- app.py +147 -0
- integral/__init__.py +17 -0
- integral/configuration_integral.py +394 -0
- integral/modeling_integral.py +0 -0
- integral/processing_integral.py +212 -0
- integral/sampling.py +114 -0
- requirements.txt +7 -0
LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
README.md
CHANGED
|
@@ -1,13 +1,32 @@
|
|
| 1 |
---
|
| 2 |
-
title: Integral
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.32.0
|
| 8 |
-
python_version: '3.12'
|
| 9 |
app_file: app.py
|
| 10 |
-
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Integral-9B
|
| 3 |
+
emoji: 🧩
|
| 4 |
+
colorFrom: red
|
| 5 |
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.32.0
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
+
short_description: Text-to-image from a unified vision-language model
|
| 10 |
+
python_version: "3.12"
|
| 11 |
+
startup_duration_timeout: 1h
|
| 12 |
---
|
| 13 |
|
| 14 |
+
# Integral-9B — Let Vision-Language Models Generate Images
|
| 15 |
+
|
| 16 |
+
**Integral** converts a pretrained vision-language model into a unified model that generates
|
| 17 |
+
images through its own visual representations: [**"Let Vision-Language Models Generate Images
|
| 18 |
+
through Their Representations"**](https://arxiv.org/abs/2611.31237) (Kim et al., 2026).
|
| 19 |
+
|
| 20 |
+
While a VLM normally only *understands* images, Integral adds image generation on top of the
|
| 21 |
+
same representations — **Abstraction Fusion** builds a shared visual representation space for
|
| 22 |
+
understanding and generation, and **Block-wise MoT** generates images efficiently from the
|
| 23 |
+
language model's key/value states. One 9B model does both.
|
| 24 |
+
|
| 25 |
+
## Text-to-image
|
| 26 |
+
|
| 27 |
+
Type a prompt and generate. The advanced settings expose the paper's sampler defaults:
|
| 28 |
+
DPM-Solver++ (2M), 50 steps, guidance scale 4.0, time-shift 4.0.
|
| 29 |
+
|
| 30 |
+
Model: [`the-jb/Integral-9B`](https://huggingface.co/the-jb/Integral-9B) ·
|
| 31 |
+
Code: [`the-jb/integral`](https://github.com/the-jb/integral) (Apache-2.0) ·
|
| 32 |
+
Project page: [thejb.ai/integral](https://thejb.ai/integral/)
|
app.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
|
| 3 |
+
|
| 4 |
+
import spaces # before torch / transformers
|
| 5 |
+
|
| 6 |
+
import random
|
| 7 |
+
import time
|
| 8 |
+
|
| 9 |
+
import gradio as gr
|
| 10 |
+
import torch
|
| 11 |
+
from integral import IntegralForConditionalGeneration, IntegralProcessor
|
| 12 |
+
|
| 13 |
+
MODEL_ID = "the-jb/Integral-9B"
|
| 14 |
+
DEFAULT_STEPS = 50
|
| 15 |
+
DEFAULT_GUIDANCE = 4.0
|
| 16 |
+
DEFAULT_TIME_SHIFT = 4.0
|
| 17 |
+
DEFAULT_SIZE = 512
|
| 18 |
+
|
| 19 |
+
# SDPA everywhere: torch-native, supported by both the text model (ALL_ATTENTION_FUNCTIONS
|
| 20 |
+
# interface) and the visual generation blocks (VISUAL_GENERATION_ATTENTION_FUNCTIONS).
|
| 21 |
+
# The optional causal_conv1d / flash-linear-attention kernels fall back to pure-torch
|
| 22 |
+
# implementations when absent; the model runs and generates correctly without them.
|
| 23 |
+
model = IntegralForConditionalGeneration.from_pretrained(
|
| 24 |
+
MODEL_ID,
|
| 25 |
+
dtype=torch.bfloat16,
|
| 26 |
+
attn_implementation="sdpa",
|
| 27 |
+
).to("cuda").eval()
|
| 28 |
+
processor = IntegralProcessor.from_pretrained(MODEL_ID)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@spaces.GPU(duration=180)
|
| 32 |
+
def generate(
|
| 33 |
+
prompt: str,
|
| 34 |
+
seed: int = 42,
|
| 35 |
+
randomize_seed: bool = True,
|
| 36 |
+
steps: int = DEFAULT_STEPS,
|
| 37 |
+
guidance_scale: float = DEFAULT_GUIDANCE,
|
| 38 |
+
time_shift: float = DEFAULT_TIME_SHIFT,
|
| 39 |
+
height: int = DEFAULT_SIZE,
|
| 40 |
+
width: int = DEFAULT_SIZE,
|
| 41 |
+
):
|
| 42 |
+
"""Generate an image from a text prompt with Integral-9B.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
prompt: What to draw.
|
| 46 |
+
seed: RNG seed for reproducibility.
|
| 47 |
+
randomize_seed: Pick a fresh seed each run instead of the given one.
|
| 48 |
+
steps: Number of sampler steps (DPM-Solver++ 2M).
|
| 49 |
+
guidance_scale: Classifier-free guidance scale.
|
| 50 |
+
time_shift: Timestep schedule shift.
|
| 51 |
+
height: Image height in pixels, multiple of 32.
|
| 52 |
+
width: Image width in pixels, multiple of 32.
|
| 53 |
+
"""
|
| 54 |
+
prompt = (prompt or "").strip()
|
| 55 |
+
if not prompt:
|
| 56 |
+
raise gr.Error("Please enter a text prompt.")
|
| 57 |
+
if randomize_seed:
|
| 58 |
+
seed = random.randint(0, 2**31 - 1)
|
| 59 |
+
seed = int(seed)
|
| 60 |
+
height, width = int(height), int(width)
|
| 61 |
+
steps = int(steps)
|
| 62 |
+
if steps < 2:
|
| 63 |
+
steps = 2
|
| 64 |
+
height -= height % 32
|
| 65 |
+
width -= width % 32
|
| 66 |
+
|
| 67 |
+
start = time.perf_counter()
|
| 68 |
+
inputs = processor.prepare_image_generation([prompt], height=height, width=width)
|
| 69 |
+
out = model.generate_image(
|
| 70 |
+
**inputs,
|
| 71 |
+
solver="dpm_solver++",
|
| 72 |
+
num_inference_steps=steps,
|
| 73 |
+
guidance_scale=float(guidance_scale),
|
| 74 |
+
time_shift=float(time_shift),
|
| 75 |
+
generator=torch.Generator().manual_seed(seed),
|
| 76 |
+
)
|
| 77 |
+
image = out.images[0]
|
| 78 |
+
elapsed = time.perf_counter() - start
|
| 79 |
+
print(f"[integral] {steps} steps, {width}x{height}, prompt={prompt!r}: {elapsed:.1f}s")
|
| 80 |
+
return image, seed
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
CSS = """
|
| 84 |
+
#col-container { max-width: 1100px; margin: 0 auto; }
|
| 85 |
+
.dark .gradio-container { color: var(--body-text-color); }
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
with gr.Blocks(theme=gr.themes.Citrus(), css=CSS) as demo:
|
| 89 |
+
with gr.Column(elem_id="col-container"):
|
| 90 |
+
gr.Markdown(
|
| 91 |
+
"""
|
| 92 |
+
# 🧩 Integral-9B
|
| 93 |
+
**Let Vision-Language Models Generate Images through Their Representations**
|
| 94 |
+
([arXiv:2611.31237](https://arxiv.org/abs/2611.31237)) — one 9B model that both
|
| 95 |
+
*understands* and *generates* images, generation flowing through the same visual
|
| 96 |
+
representations used for understanding.
|
| 97 |
+
"""
|
| 98 |
+
)
|
| 99 |
+
with gr.Row():
|
| 100 |
+
prompt = gr.Textbox(
|
| 101 |
+
label="Prompt",
|
| 102 |
+
show_label=False,
|
| 103 |
+
placeholder="Describe the image to generate…",
|
| 104 |
+
lines=2,
|
| 105 |
+
scale=4,
|
| 106 |
+
autofocus=True,
|
| 107 |
+
)
|
| 108 |
+
run = gr.Button("Generate", variant="primary", scale=1)
|
| 109 |
+
image_out = gr.Image(label="Generated image", height=512, type="pil", show_download_button=True)
|
| 110 |
+
with gr.Accordion("Advanced settings", open=False):
|
| 111 |
+
with gr.Row():
|
| 112 |
+
seed = gr.Number(label="Seed", value=42, precision=0, minimum=-1)
|
| 113 |
+
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
| 114 |
+
with gr.Row():
|
| 115 |
+
steps = gr.Slider(label="Steps", minimum=2, maximum=100, value=DEFAULT_STEPS, step=1)
|
| 116 |
+
guidance_scale = gr.Slider(label="Guidance scale", minimum=1.0, maximum=10.0, value=DEFAULT_GUIDANCE, step=0.1)
|
| 117 |
+
with gr.Row():
|
| 118 |
+
time_shift = gr.Slider(label="Time shift", minimum=1.0, maximum=8.0, value=DEFAULT_TIME_SHIFT, step=0.1)
|
| 119 |
+
with gr.Row():
|
| 120 |
+
height = gr.Slider(label="Height", minimum=256, maximum=1024, value=DEFAULT_SIZE, step=32)
|
| 121 |
+
width = gr.Slider(label="Width", minimum=256, maximum=1024, value=DEFAULT_SIZE, step=32)
|
| 122 |
+
|
| 123 |
+
gr.Examples(
|
| 124 |
+
examples=[
|
| 125 |
+
# The authors' showcased prompts (project page, https://thejb.ai/integral/).
|
| 126 |
+
["A photograph of a cat wearing a white T-shirt with the word 'Integral' printed across the chest in bold black capital letters."],
|
| 127 |
+
["The mountain most closely associated with the country where Tokyo is located"],
|
| 128 |
+
["A cold soda can left outside on a humid day, highlighting the state of the can"],
|
| 129 |
+
["Potassium permanganate crystal dissolving in water"],
|
| 130 |
+
["The orchard watch hut when the first bats begin leaving the trees."],
|
| 131 |
+
["The state of a leaf after a cold night"],
|
| 132 |
+
["Show a large animal that lives in the arctic and subarctic, known for its thick white fur"],
|
| 133 |
+
["The stepped field landscape associated with the island where Ubud is located"],
|
| 134 |
+
],
|
| 135 |
+
inputs=[prompt],
|
| 136 |
+
outputs=[image_out],
|
| 137 |
+
fn=generate,
|
| 138 |
+
cache_examples=True,
|
| 139 |
+
cache_mode="lazy",
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
prompt.submit(generate, inputs=[prompt, seed, randomize_seed, steps, guidance_scale, time_shift, height, width],
|
| 143 |
+
outputs=[image_out, seed], api_name="generate")
|
| 144 |
+
run.click(generate, inputs=[prompt, seed, randomize_seed, steps, guidance_scale, time_shift, height, width],
|
| 145 |
+
outputs=[image_out, seed], api_name="generate")
|
| 146 |
+
|
| 147 |
+
demo.launch(mcp_server=True)
|
integral/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Integral. Importing the package registers its classes with transformers' Auto classes, so a directory whose
|
| 2 |
+
config has `model_type` `integral` loads through `AutoConfig`, `AutoModelForImageTextToText` and `AutoProcessor`
|
| 3 |
+
with this package's code and no `trust_remote_code` prompt.
|
| 4 |
+
|
| 5 |
+
`register` only adds to the Auto mappings: saving writes no `auto_map` and copies no code files (that is
|
| 6 |
+
`register_for_auto_class`, which nothing here calls).
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from transformers import AutoConfig, AutoModelForImageTextToText, AutoProcessor
|
| 10 |
+
|
| 11 |
+
from .configuration_integral import IntegralConfig
|
| 12 |
+
from .modeling_integral import IntegralForConditionalGeneration
|
| 13 |
+
from .processing_integral import IntegralProcessor
|
| 14 |
+
|
| 15 |
+
AutoConfig.register("integral", IntegralConfig)
|
| 16 |
+
AutoModelForImageTextToText.register(IntegralConfig, IntegralForConditionalGeneration)
|
| 17 |
+
AutoProcessor.register(IntegralConfig, IntegralProcessor)
|
integral/configuration_integral.py
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The Qwen Team and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from huggingface_hub.dataclasses import strict
|
| 15 |
+
|
| 16 |
+
from transformers.configuration_utils import PreTrainedConfig, remap_legacy_layer_types
|
| 17 |
+
from transformers.modeling_rope_utils import RopeParameters
|
| 18 |
+
from transformers.utils import auto_docstring
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@auto_docstring(checkpoint="Qwen/Qwen3.5-27B")
|
| 22 |
+
@strict
|
| 23 |
+
class IntegralTextConfig(PreTrainedConfig):
|
| 24 |
+
r"""
|
| 25 |
+
linear_conv_kernel_dim (`int`, *optional*, defaults to 4):
|
| 26 |
+
Kernel size of the convolution used in linear attention layers.
|
| 27 |
+
linear_key_head_dim (`int`, *optional*, defaults to 128):
|
| 28 |
+
Dimension of each key head in linear attention.
|
| 29 |
+
linear_value_head_dim (`int`, *optional*, defaults to 128):
|
| 30 |
+
Dimension of each value head in linear attention.
|
| 31 |
+
linear_num_key_heads (`int`, *optional*, defaults to 16):
|
| 32 |
+
Number of key heads used in linear attention layers.
|
| 33 |
+
linear_num_value_heads (`int`, *optional*, defaults to 32):
|
| 34 |
+
Number of value heads used in linear attention layers.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
model_type = "integral_text"
|
| 38 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 39 |
+
|
| 40 |
+
base_model_tp_plan = {
|
| 41 |
+
"layers.*.self_attn.q_proj": "colwise",
|
| 42 |
+
"layers.*.self_attn.k_proj": "colwise",
|
| 43 |
+
"layers.*.self_attn.v_proj": "colwise",
|
| 44 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
| 45 |
+
"layers.*.self_attn.q_norm": "replicated_with_grad_allreduce",
|
| 46 |
+
"layers.*.self_attn.k_norm": "replicated_with_grad_allreduce",
|
| 47 |
+
"layers.*.mlp.gate_proj": "colwise",
|
| 48 |
+
"layers.*.mlp.up_proj": "colwise",
|
| 49 |
+
"layers.*.mlp.down_proj": "rowwise",
|
| 50 |
+
"layers.*.linear_attn.in_proj_qkv": "colwise_gather_output",
|
| 51 |
+
"layers.*.linear_attn.in_proj_z": "colwise_gather_output",
|
| 52 |
+
"layers.*.linear_attn.in_proj_b": "colwise_gather_output",
|
| 53 |
+
"layers.*.linear_attn.in_proj_a": "colwise_gather_output",
|
| 54 |
+
"layers.*.linear_attn.out_proj": "colwise_gather_output",
|
| 55 |
+
}
|
| 56 |
+
base_model_pp_plan = {
|
| 57 |
+
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
| 58 |
+
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
| 59 |
+
"norm": (["hidden_states"], ["hidden_states"]),
|
| 60 |
+
}
|
| 61 |
+
base_model_ep_plan = None # no Moe
|
| 62 |
+
|
| 63 |
+
vocab_size: int = 248320
|
| 64 |
+
hidden_size: int = 4096
|
| 65 |
+
intermediate_size: int = 12288
|
| 66 |
+
num_hidden_layers: int = 32
|
| 67 |
+
num_attention_heads: int = 16
|
| 68 |
+
num_key_value_heads: int = 4
|
| 69 |
+
hidden_act: str = "silu"
|
| 70 |
+
max_position_embeddings: int = 32768
|
| 71 |
+
initializer_range: float = 0.02
|
| 72 |
+
rms_norm_eps: float = 1e-6
|
| 73 |
+
use_cache: bool = True
|
| 74 |
+
tie_word_embeddings: bool = False
|
| 75 |
+
rope_parameters: RopeParameters | dict | None = None
|
| 76 |
+
attention_bias: bool = False
|
| 77 |
+
attention_dropout: float | int = 0.0
|
| 78 |
+
head_dim: int = 256
|
| 79 |
+
linear_conv_kernel_dim: int = 4
|
| 80 |
+
linear_key_head_dim: int = 128
|
| 81 |
+
linear_value_head_dim: int = 128
|
| 82 |
+
linear_num_key_heads: int = 16
|
| 83 |
+
linear_num_value_heads: int = 32
|
| 84 |
+
layer_types: list[str] | None = None
|
| 85 |
+
pad_token_id: int | None = None
|
| 86 |
+
bos_token_id: int | None = None
|
| 87 |
+
eos_token_id: int | list[int] | None = None
|
| 88 |
+
base_config_key = "text_config"
|
| 89 |
+
ignore_keys_at_rope_validation = {"mrope_section", "mrope_interleaved"}
|
| 90 |
+
|
| 91 |
+
def __post_init__(self, **kwargs):
|
| 92 |
+
kwargs.setdefault("partial_rotary_factor", 0.25) # assign default for BC
|
| 93 |
+
if self.layer_types is None:
|
| 94 |
+
interval_pattern = kwargs.pop("full_attention_interval", 4)
|
| 95 |
+
self.layer_types = [
|
| 96 |
+
"linear_attention" if bool((i + 1) % interval_pattern) else "full_attention"
|
| 97 |
+
for i in range(self.num_hidden_layers)
|
| 98 |
+
]
|
| 99 |
+
else:
|
| 100 |
+
self.layer_types = remap_legacy_layer_types(self.layer_types)
|
| 101 |
+
|
| 102 |
+
super().__post_init__(**kwargs)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class IntegralVisionTokenizerConfig(PreTrainedConfig):
|
| 106 |
+
r"""
|
| 107 |
+
Configuration for [`IntegralVisionTokenizer`].
|
| 108 |
+
|
| 109 |
+
Args:
|
| 110 |
+
vision_num_hidden_layers (`int`, *optional*, defaults to 27):
|
| 111 |
+
Number of blocks in the vision tower.
|
| 112 |
+
vision_hidden_size (`int`, *optional*, defaults to 1152):
|
| 113 |
+
Hidden size of the vision tower.
|
| 114 |
+
vision_intermediate_size (`int`, *optional*, defaults to 4304):
|
| 115 |
+
MLP size of the vision tower.
|
| 116 |
+
vision_num_attention_heads (`int`, *optional*, defaults to 16):
|
| 117 |
+
Attention heads of the vision tower.
|
| 118 |
+
vision_num_position_embeddings (`int`, *optional*, defaults to 2304):
|
| 119 |
+
Size of the vision tower's position table, a square grid interpolated to each image.
|
| 120 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 121 |
+
Pixels per patch side.
|
| 122 |
+
temporal_patch_size (`int`, *optional*, defaults to 2):
|
| 123 |
+
Frames per patch. A still image is repeated to fill them.
|
| 124 |
+
spatial_merge_size (`int`, *optional*, defaults to 2):
|
| 125 |
+
Patches merged per side into one language model token.
|
| 126 |
+
image_mean (`list[float]`, *optional*, defaults to `[0.5, 0.5, 0.5]`):
|
| 127 |
+
Per-channel mean for normalizing RGB in [0, 1].
|
| 128 |
+
image_std (`list[float]`, *optional*, defaults to `[0.5, 0.5, 0.5]`):
|
| 129 |
+
Per-channel standard deviation for normalizing RGB in [0, 1].
|
| 130 |
+
abstraction_fusion_group_size (`int`, *optional*, defaults to 4):
|
| 131 |
+
Consecutive vision tower hidden states per abstraction group.
|
| 132 |
+
abstraction_fusion_hidden_size (`int`, *optional*, defaults to 1152):
|
| 133 |
+
Hidden size of abstraction fusion.
|
| 134 |
+
abstraction_fusion_num_hidden_layers (`int`, *optional*, defaults to 1):
|
| 135 |
+
Self-attention layers across the abstraction groups.
|
| 136 |
+
abstraction_fusion_num_attention_heads (`int`, *optional*, defaults to 16):
|
| 137 |
+
Attention heads of those layers.
|
| 138 |
+
abstraction_fusion_intermediate_size (`int`, *optional*, defaults to 4608):
|
| 139 |
+
MLP size of those layers.
|
| 140 |
+
bottleneck_pre_intermediate_size (`int`, *optional*, defaults to 4096):
|
| 141 |
+
Hidden size of the bottleneck's first SwiGLU.
|
| 142 |
+
bottleneck_hidden_size (`int`, *optional*, defaults to 1152):
|
| 143 |
+
Output size of the bottleneck's first SwiGLU.
|
| 144 |
+
bottleneck_post_intermediate_size (`int`, *optional*, defaults to 4608):
|
| 145 |
+
Hidden size of the bottleneck's second SwiGLU.
|
| 146 |
+
vae_hidden_size (`int`, *optional*, defaults to 2304):
|
| 147 |
+
Input and output size of the VAE.
|
| 148 |
+
latent_size (`int`, *optional*, defaults to 256):
|
| 149 |
+
Size of the latent.
|
| 150 |
+
merger_intermediate_size (`int`, *optional*, defaults to 4608):
|
| 151 |
+
Hidden size of the merger's input SwiGLU.
|
| 152 |
+
merger_hidden_size (`int`, *optional*, defaults to 1152):
|
| 153 |
+
Output size of the merger's input SwiGLU.
|
| 154 |
+
merger_out_hidden_size (`int`, *optional*, defaults to 4096):
|
| 155 |
+
Output size of the merger, the language model's hidden size.
|
| 156 |
+
merger_layer_norm_eps (`float`, *optional*, defaults to 1e-6):
|
| 157 |
+
Epsilon of the merger's LayerNorm.
|
| 158 |
+
visual_generation_adapter_num_layers (`int`, *optional*, defaults to 8):
|
| 159 |
+
Number of key/value deltas the visual generation adapter produces, one per visual generation
|
| 160 |
+
block.
|
| 161 |
+
visual_generation_adapter_intermediate_size (`int`, *optional*, defaults to 2304):
|
| 162 |
+
Hidden size of the visual generation adapter.
|
| 163 |
+
visual_generation_adapter_num_key_value_heads (`int`, *optional*, defaults to 4):
|
| 164 |
+
Key/value heads of each delta.
|
| 165 |
+
visual_generation_adapter_head_dim (`int`, *optional*, defaults to 256):
|
| 166 |
+
Head size of each delta.
|
| 167 |
+
pixel_decoder_in_intermediate_size (`int`, *optional*, defaults to 4608):
|
| 168 |
+
Hidden size of the pixel decoder's input SwiGLU.
|
| 169 |
+
pixel_decoder_in_hidden_size (`int`, *optional*, defaults to 1152):
|
| 170 |
+
Output size of the pixel decoder's input SwiGLU.
|
| 171 |
+
pixel_decoder_hidden_size (`int`, *optional*, defaults to 1152):
|
| 172 |
+
Hidden size of the pixel decoder.
|
| 173 |
+
pixel_decoder_num_hidden_layers (`int`, *optional*, defaults to 28):
|
| 174 |
+
Number of blocks in the pixel decoder.
|
| 175 |
+
pixel_decoder_num_attention_heads (`int`, *optional*, defaults to 16):
|
| 176 |
+
Attention heads of the pixel decoder.
|
| 177 |
+
pixel_decoder_intermediate_size (`int`, *optional*, defaults to 3072):
|
| 178 |
+
SwiGLU size of the pixel decoder's blocks.
|
| 179 |
+
pixel_decoder_rope_theta (`float`, *optional*, defaults to 100.0):
|
| 180 |
+
Base of the pixel decoder's 2D RoPE.
|
| 181 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-5):
|
| 182 |
+
Epsilon of the LayerNorms in abstraction fusion, the bottleneck and the pixel decoder.
|
| 183 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 184 |
+
Standard deviation of the normal initializer for linear, convolution and embedding
|
| 185 |
+
weights.
|
| 186 |
+
"""
|
| 187 |
+
|
| 188 |
+
model_type = "integral_vision_tokenizer"
|
| 189 |
+
base_config_key = "vision_tokenizer_config"
|
| 190 |
+
|
| 191 |
+
vision_num_hidden_layers: int = 27
|
| 192 |
+
vision_hidden_size: int = 1152
|
| 193 |
+
vision_intermediate_size: int = 4304
|
| 194 |
+
vision_num_attention_heads: int = 16
|
| 195 |
+
vision_num_position_embeddings: int = 2304
|
| 196 |
+
|
| 197 |
+
patch_size: int = 16
|
| 198 |
+
temporal_patch_size: int = 2
|
| 199 |
+
spatial_merge_size: int = 2
|
| 200 |
+
image_mean: list[float] | None = None
|
| 201 |
+
image_std: list[float] | None = None
|
| 202 |
+
|
| 203 |
+
abstraction_fusion_group_size: int = 4
|
| 204 |
+
abstraction_fusion_hidden_size: int = 1152
|
| 205 |
+
abstraction_fusion_num_hidden_layers: int = 1
|
| 206 |
+
abstraction_fusion_num_attention_heads: int = 16
|
| 207 |
+
abstraction_fusion_intermediate_size: int = 4608
|
| 208 |
+
|
| 209 |
+
bottleneck_pre_intermediate_size: int = 4096
|
| 210 |
+
bottleneck_hidden_size: int = 1152
|
| 211 |
+
bottleneck_post_intermediate_size: int = 4608
|
| 212 |
+
vae_hidden_size: int = 2304
|
| 213 |
+
latent_size: int = 256
|
| 214 |
+
|
| 215 |
+
merger_intermediate_size: int = 4608
|
| 216 |
+
merger_hidden_size: int = 1152
|
| 217 |
+
merger_out_hidden_size: int = 4096
|
| 218 |
+
merger_layer_norm_eps: float = 1e-6
|
| 219 |
+
|
| 220 |
+
visual_generation_adapter_num_layers: int = 8
|
| 221 |
+
visual_generation_adapter_intermediate_size: int = 2304
|
| 222 |
+
visual_generation_adapter_num_key_value_heads: int = 4
|
| 223 |
+
visual_generation_adapter_head_dim: int = 256
|
| 224 |
+
|
| 225 |
+
pixel_decoder_in_intermediate_size: int = 4608
|
| 226 |
+
pixel_decoder_in_hidden_size: int = 1152
|
| 227 |
+
pixel_decoder_hidden_size: int = 1152
|
| 228 |
+
pixel_decoder_num_hidden_layers: int = 28
|
| 229 |
+
pixel_decoder_num_attention_heads: int = 16
|
| 230 |
+
pixel_decoder_intermediate_size: int = 3072
|
| 231 |
+
pixel_decoder_rope_theta: float = 100.0
|
| 232 |
+
|
| 233 |
+
layer_norm_eps: float = 1e-5
|
| 234 |
+
initializer_range: float = 0.02
|
| 235 |
+
|
| 236 |
+
def __post_init__(self, **kwargs):
|
| 237 |
+
if self.image_mean is None:
|
| 238 |
+
self.image_mean = [0.5, 0.5, 0.5]
|
| 239 |
+
if self.image_std is None:
|
| 240 |
+
self.image_std = [0.5, 0.5, 0.5]
|
| 241 |
+
super().__post_init__(**kwargs)
|
| 242 |
+
|
| 243 |
+
@property
|
| 244 |
+
def num_vision_hidden_states(self) -> int:
|
| 245 |
+
"""Hidden states the vision tower emits: the patch embeddings and one per block."""
|
| 246 |
+
return self.vision_num_hidden_layers + 1
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
class IntegralVisualGenerationConfig(PreTrainedConfig):
|
| 250 |
+
r"""
|
| 251 |
+
Configuration for [`IntegralVisualGenerationModel`]: the visual generation blocks, which read the key/value
|
| 252 |
+
states of language model layers, and the flow head.
|
| 253 |
+
|
| 254 |
+
Args:
|
| 255 |
+
key_value_layer_indices (`list[int]`, *optional*, defaults to `[3, 7, 11, 15, 19, 23, 27, 31]`):
|
| 256 |
+
Full-attention language model layers whose key/value states the visual generation blocks read, one
|
| 257 |
+
block per layer, in increasing order.
|
| 258 |
+
latent_size (`int`, *optional*, defaults to 256):
|
| 259 |
+
Size of the image latent the model denoises.
|
| 260 |
+
hidden_size (`int`, *optional*, defaults to 2048):
|
| 261 |
+
Hidden size of the visual generation blocks.
|
| 262 |
+
num_attention_heads (`int`, *optional*, defaults to 16):
|
| 263 |
+
Query heads of the visual generation blocks.
|
| 264 |
+
num_key_value_heads (`int`, *optional*, defaults to 8):
|
| 265 |
+
Key/value heads the blocks compute from their own hidden states.
|
| 266 |
+
head_dim (`int`, *optional*, defaults to 256):
|
| 267 |
+
Head size of the blocks, equal to the language model's.
|
| 268 |
+
intermediate_size (`int`, *optional*, defaults to 8192):
|
| 269 |
+
MLP size of the blocks.
|
| 270 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-6):
|
| 271 |
+
Epsilon of the LayerNorms of the blocks and the flow head.
|
| 272 |
+
timestep_embedding_size (`int`, *optional*, defaults to 512):
|
| 273 |
+
Size of the sinusoidal timestep embedding of the blocks.
|
| 274 |
+
timestep_scale (`float`, *optional*, defaults to 1000.0):
|
| 275 |
+
Factor applied to the timestep in [0, 1] before the blocks' sinusoidal embedding.
|
| 276 |
+
partial_rotary_factor (`float`, *optional*, defaults to 0.5):
|
| 277 |
+
Fraction of each head the blocks' 2D rotary embedding rotates.
|
| 278 |
+
rope_theta (`float`, *optional*, defaults to 100.0):
|
| 279 |
+
Base of the blocks' 2D rotary embedding.
|
| 280 |
+
flow_head_hidden_size (`int`, *optional*, defaults to 3072):
|
| 281 |
+
Hidden size of the flow head.
|
| 282 |
+
flow_head_num_hidden_layers (`int`, *optional*, defaults to 2):
|
| 283 |
+
Blocks in the flow head.
|
| 284 |
+
flow_head_num_attention_heads (`int`, *optional*, defaults to 32):
|
| 285 |
+
Attention heads of the flow head.
|
| 286 |
+
flow_head_intermediate_size (`int`, *optional*, defaults to 12288):
|
| 287 |
+
MLP size of the flow head.
|
| 288 |
+
flow_head_rope_theta (`float`, *optional*, defaults to 100.0):
|
| 289 |
+
Base of the flow head's 2D rotary embedding.
|
| 290 |
+
time_shift (`float`, *optional*, defaults to 4.0):
|
| 291 |
+
Shift `s` of the timestep schedule, `t -> s * t / (1 + (s - 1) * t)`, the model was trained with; the
|
| 292 |
+
default of `generate_image`.
|
| 293 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 294 |
+
Standard deviation of the normal initializer for linear weights.
|
| 295 |
+
"""
|
| 296 |
+
|
| 297 |
+
model_type = "integral_visual_generation"
|
| 298 |
+
base_config_key = "visual_generation_config"
|
| 299 |
+
|
| 300 |
+
key_value_layer_indices: list[int] | None = None
|
| 301 |
+
latent_size: int = 256
|
| 302 |
+
hidden_size: int = 2048
|
| 303 |
+
num_attention_heads: int = 16
|
| 304 |
+
num_key_value_heads: int = 8
|
| 305 |
+
head_dim: int = 256
|
| 306 |
+
intermediate_size: int = 8192
|
| 307 |
+
layer_norm_eps: float = 1e-6
|
| 308 |
+
timestep_embedding_size: int = 512
|
| 309 |
+
timestep_scale: float = 1000.0
|
| 310 |
+
partial_rotary_factor: float = 0.5
|
| 311 |
+
rope_theta: float = 100.0
|
| 312 |
+
flow_head_hidden_size: int = 3072
|
| 313 |
+
flow_head_num_hidden_layers: int = 2
|
| 314 |
+
flow_head_num_attention_heads: int = 32
|
| 315 |
+
flow_head_intermediate_size: int = 12288
|
| 316 |
+
flow_head_rope_theta: float = 100.0
|
| 317 |
+
time_shift: float = 4.0
|
| 318 |
+
initializer_range: float = 0.02
|
| 319 |
+
|
| 320 |
+
def __post_init__(self, **kwargs):
|
| 321 |
+
if self.key_value_layer_indices is None:
|
| 322 |
+
self.key_value_layer_indices = [3, 7, 11, 15, 19, 23, 27, 31]
|
| 323 |
+
super().__post_init__(**kwargs)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
@auto_docstring(checkpoint="Qwen/Qwen3.5-27B")
|
| 327 |
+
@strict
|
| 328 |
+
class IntegralConfig(PreTrainedConfig):
|
| 329 |
+
r"""
|
| 330 |
+
vision_tokenizer_config (`IntegralVisionTokenizerConfig` or `dict`, *optional*):
|
| 331 |
+
Configuration of the vision tokenizer.
|
| 332 |
+
visual_generation_config (`IntegralVisualGenerationConfig` or `dict`, *optional*):
|
| 333 |
+
Configuration of the visual generation model.
|
| 334 |
+
"""
|
| 335 |
+
|
| 336 |
+
model_type = "integral"
|
| 337 |
+
sub_configs = {
|
| 338 |
+
"vision_tokenizer_config": IntegralVisionTokenizerConfig,
|
| 339 |
+
"text_config": IntegralTextConfig,
|
| 340 |
+
"visual_generation_config": IntegralVisualGenerationConfig,
|
| 341 |
+
}
|
| 342 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 343 |
+
|
| 344 |
+
text_config: dict | PreTrainedConfig | None = None
|
| 345 |
+
vision_tokenizer_config: dict | PreTrainedConfig | None = None
|
| 346 |
+
visual_generation_config: dict | PreTrainedConfig | None = None
|
| 347 |
+
|
| 348 |
+
image_token_id: int = 248056
|
| 349 |
+
video_token_id: int = 248057
|
| 350 |
+
vision_start_token_id: int = 248053
|
| 351 |
+
vision_end_token_id: int = 248054
|
| 352 |
+
tie_word_embeddings: bool = False
|
| 353 |
+
|
| 354 |
+
def __post_init__(self, **kwargs):
|
| 355 |
+
if isinstance(self.vision_tokenizer_config, dict):
|
| 356 |
+
self.vision_tokenizer_config = self.sub_configs["vision_tokenizer_config"](**self.vision_tokenizer_config)
|
| 357 |
+
elif self.vision_tokenizer_config is None:
|
| 358 |
+
self.vision_tokenizer_config = self.sub_configs["vision_tokenizer_config"]()
|
| 359 |
+
|
| 360 |
+
if isinstance(self.text_config, dict):
|
| 361 |
+
self.text_config = self.sub_configs["text_config"](**self.text_config)
|
| 362 |
+
elif self.text_config is None:
|
| 363 |
+
self.text_config = self.sub_configs["text_config"]()
|
| 364 |
+
|
| 365 |
+
if isinstance(self.visual_generation_config, dict):
|
| 366 |
+
self.visual_generation_config = self.sub_configs["visual_generation_config"](**self.visual_generation_config)
|
| 367 |
+
elif self.visual_generation_config is None:
|
| 368 |
+
self.visual_generation_config = self.sub_configs["visual_generation_config"]()
|
| 369 |
+
|
| 370 |
+
tokenizer, text, generation = self.vision_tokenizer_config, self.text_config, self.visual_generation_config
|
| 371 |
+
layers = list(generation.key_value_layer_indices)
|
| 372 |
+
mismatched = {
|
| 373 |
+
"merger_out_hidden_size vs hidden_size": (tokenizer.merger_out_hidden_size, text.hidden_size),
|
| 374 |
+
"visual_generation_adapter_num_key_value_heads vs num_key_value_heads":
|
| 375 |
+
(tokenizer.visual_generation_adapter_num_key_value_heads, text.num_key_value_heads),
|
| 376 |
+
"visual_generation_adapter_head_dim vs head_dim": (tokenizer.visual_generation_adapter_head_dim, text.head_dim),
|
| 377 |
+
"visual_generation_adapter_num_layers vs len(key_value_layer_indices)":
|
| 378 |
+
(tokenizer.visual_generation_adapter_num_layers, len(layers)),
|
| 379 |
+
"visual_generation_config.head_dim vs head_dim": (generation.head_dim, text.head_dim),
|
| 380 |
+
"visual_generation_config.latent_size vs vision_tokenizer_config.latent_size":
|
| 381 |
+
(generation.latent_size, tokenizer.latent_size),
|
| 382 |
+
"key_value_layer_indices are increasing full-attention layers":
|
| 383 |
+
(layers == sorted(set(layers)) and all(0 <= i < text.num_hidden_layers for i in layers)
|
| 384 |
+
and all(text.layer_types[i] == "full_attention" for i in layers if 0 <= i < text.num_hidden_layers),
|
| 385 |
+
True),
|
| 386 |
+
}
|
| 387 |
+
mismatched = {k: v for k, v in mismatched.items() if v[0] != v[1]}
|
| 388 |
+
if mismatched:
|
| 389 |
+
raise ValueError(f"the sub-configs disagree: {mismatched}")
|
| 390 |
+
|
| 391 |
+
super().__post_init__(**kwargs)
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
__all__ = ["IntegralConfig", "IntegralTextConfig", "IntegralVisionTokenizerConfig", "IntegralVisualGenerationConfig"]
|
integral/modeling_integral.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
integral/processing_integral.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Processor of the Integral model: the image processor and the tokenizer for understanding inputs, and the prompts
|
| 2 |
+
of image generation."""
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from transformers.feature_extraction_utils import BatchFeature
|
| 7 |
+
from transformers.processing_utils import ProcessingKwargs, ProcessorMixin
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class IntegralProcessorKwargs(ProcessingKwargs, total=False):
|
| 11 |
+
_defaults = {
|
| 12 |
+
"text_kwargs": {
|
| 13 |
+
"padding": False,
|
| 14 |
+
"return_token_type_ids": False,
|
| 15 |
+
"return_mm_token_type_ids": True,
|
| 16 |
+
},
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class IntegralProcessor(ProcessorMixin):
|
| 21 |
+
r"""
|
| 22 |
+
Constructs an Integral processor from an image processor and a tokenizer.
|
| 23 |
+
|
| 24 |
+
Args:
|
| 25 |
+
image_processor ([`BaseImageProcessor`], *optional*):
|
| 26 |
+
Produces `pixel_values` and `image_grid_thw` in the vision tokenizer's input format.
|
| 27 |
+
tokenizer ([`PreTrainedTokenizerBase`], *optional*):
|
| 28 |
+
The language model's tokenizer.
|
| 29 |
+
chat_template (`str`, *optional*):
|
| 30 |
+
The chat template.
|
| 31 |
+
image_generation_system_prompt (`str`, *optional*):
|
| 32 |
+
The system turn of image generation prompts.
|
| 33 |
+
image_generation_user_template (`str`, *optional*):
|
| 34 |
+
The user turn of image generation prompts, with `{h}`, `{w}` (the image size in pixels) and `{caption}`.
|
| 35 |
+
image_generation_marker (`str`, *optional*):
|
| 36 |
+
The text after the assistant turn opens and before the generated image, with `{h}` and `{w}`.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
valid_processor_kwargs = IntegralProcessorKwargs
|
| 40 |
+
|
| 41 |
+
def __init__(self, image_processor=None, tokenizer=None, chat_template=None,
|
| 42 |
+
image_generation_system_prompt=None, image_generation_user_template=None,
|
| 43 |
+
image_generation_marker=None, **kwargs):
|
| 44 |
+
self.image_token = getattr(tokenizer, "image_token", None) or "<|image_pad|>"
|
| 45 |
+
self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
|
| 46 |
+
super().__init__(image_processor, tokenizer, chat_template=chat_template)
|
| 47 |
+
self.image_generation_system_prompt = image_generation_system_prompt
|
| 48 |
+
self.image_generation_user_template = image_generation_user_template
|
| 49 |
+
self.image_generation_marker = image_generation_marker
|
| 50 |
+
|
| 51 |
+
def replace_image_token(self, image_inputs: dict, image_idx: int, **kwargs) -> str:
|
| 52 |
+
# transformers >= 5.16 passes the processing kwargs too; they change nothing here
|
| 53 |
+
merge_length = self.image_processor.merge_size**2
|
| 54 |
+
return self.image_token * int(image_inputs["image_grid_thw"][image_idx].prod() // merge_length)
|
| 55 |
+
|
| 56 |
+
@property
|
| 57 |
+
def model_input_names(self):
|
| 58 |
+
return super().model_input_names + ["mm_token_type_ids"]
|
| 59 |
+
|
| 60 |
+
def image_generation_prompt_ids(self, caption: str, height: int, width: int,
|
| 61 |
+
image_tokens: int | list[int] = 0) -> list[int]:
|
| 62 |
+
"""
|
| 63 |
+
The token ids of the prompt asking for one `height x width` image of `caption`: the system turn, the user
|
| 64 |
+
turn (the input images, in order, then `image_generation_user_template` around the caption), the opened
|
| 65 |
+
assistant turn, then `image_generation_marker`.
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
caption (`str`):
|
| 69 |
+
The image description or, with input images, the instruction; `""` gives the unconditional prompt
|
| 70 |
+
of classifier-free guidance.
|
| 71 |
+
height (`int`), width (`int`):
|
| 72 |
+
The size of the generated image in pixels.
|
| 73 |
+
image_tokens (`int` or `list[int]`, *optional*, defaults to 0):
|
| 74 |
+
The image tokens of each input image, in order (an `int` for one image); 0 or `[]` for none.
|
| 75 |
+
|
| 76 |
+
Returns:
|
| 77 |
+
`list[int]`.
|
| 78 |
+
"""
|
| 79 |
+
if None in (self.image_generation_system_prompt, self.image_generation_user_template,
|
| 80 |
+
self.image_generation_marker):
|
| 81 |
+
raise ValueError("this processor has no image generation prompt (image_generation_system_prompt, "
|
| 82 |
+
"image_generation_user_template, image_generation_marker)")
|
| 83 |
+
image_tokens = ([image_tokens] if image_tokens else []) if isinstance(image_tokens, int) else list(image_tokens)
|
| 84 |
+
request = self.image_generation_user_template.format(h=height, w=width, caption=caption)
|
| 85 |
+
content = ([{"type": "image"}] * len(image_tokens) + [{"type": "text", "text": request}] if image_tokens
|
| 86 |
+
else request)
|
| 87 |
+
messages = [
|
| 88 |
+
{"role": "system", "content": self.image_generation_system_prompt},
|
| 89 |
+
{"role": "user", "content": content},
|
| 90 |
+
]
|
| 91 |
+
text = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True,
|
| 92 |
+
enable_thinking=False)
|
| 93 |
+
ids = self.tokenizer(text, add_special_tokens=False)["input_ids"]
|
| 94 |
+
if image_tokens:
|
| 95 |
+
pads = [k for k, t in enumerate(ids) if t == self.image_token_id]
|
| 96 |
+
if len(pads) != len(image_tokens):
|
| 97 |
+
raise ValueError(f"the chat template emitted {len(pads)} image tokens for {len(image_tokens)} images")
|
| 98 |
+
# widened from the back so the earlier positions stay valid
|
| 99 |
+
for k, n in zip(reversed(pads), reversed(image_tokens)):
|
| 100 |
+
ids = ids[:k] + [self.image_token_id] * n + ids[k + 1:]
|
| 101 |
+
marker = self.tokenizer(self.image_generation_marker.format(h=height, w=width),
|
| 102 |
+
add_special_tokens=False)["input_ids"]
|
| 103 |
+
return ids + marker
|
| 104 |
+
|
| 105 |
+
def image_generation_pixel_values(self, images: list) -> BatchFeature:
|
| 106 |
+
"""
|
| 107 |
+
The input images of image generation as the vision tokenizer reads them, at their own size: pixels
|
| 108 |
+
`uint8 / 255`, normalized with the image processor's `image_mean` and `image_std`, then cut into patches.
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
images (`list`):
|
| 112 |
+
`PIL.Image.Image`s or `torch.Tensor`s of shape `(3, height, width)` in `uint8`; height and width
|
| 113 |
+
multiples of `patch_size * merge_size`.
|
| 114 |
+
|
| 115 |
+
Returns:
|
| 116 |
+
[`BatchFeature`] with `pixel_values` and `image_grid_thw` (`(num_images, 3)`).
|
| 117 |
+
"""
|
| 118 |
+
unit = self.image_processor.patch_size * self.image_processor.merge_size
|
| 119 |
+
mean = torch.tensor(self.image_processor.image_mean).view(3, 1, 1)
|
| 120 |
+
std = torch.tensor(self.image_processor.image_std).view(3, 1, 1)
|
| 121 |
+
normalized = []
|
| 122 |
+
for image in images:
|
| 123 |
+
if not isinstance(image, torch.Tensor):
|
| 124 |
+
image = torch.from_numpy(np.asarray(image.convert("RGB")).copy()).permute(2, 0, 1)
|
| 125 |
+
if image.dtype != torch.uint8 or image.dim() != 3 or image.shape[0] != 3:
|
| 126 |
+
raise ValueError(f"an input image must be a PIL image or a (3, H, W) uint8 tensor, got "
|
| 127 |
+
f"{tuple(image.shape)} {image.dtype}")
|
| 128 |
+
if image.shape[1] % unit or image.shape[2] % unit:
|
| 129 |
+
raise ValueError(f"input image sides must be multiples of {unit}, got {tuple(image.shape[1:])}")
|
| 130 |
+
normalized.append((image.float().div(255) - mean) / std)
|
| 131 |
+
return self.image_processor(images=normalized, do_resize=False, do_rescale=False, do_normalize=False,
|
| 132 |
+
return_tensors="pt")
|
| 133 |
+
|
| 134 |
+
def prepare_image_generation(self, prompts: str | list[str], height: int = 512, width: int = 512,
|
| 135 |
+
images: list | None = None, guidance: bool = True,
|
| 136 |
+
image_guidance: bool | None = None) -> BatchFeature:
|
| 137 |
+
"""
|
| 138 |
+
Builds the inputs of `IntegralForConditionalGeneration.prepare_image_generation_cache` / `generate_image`.
|
| 139 |
+
|
| 140 |
+
Args:
|
| 141 |
+
prompts (`str` or `list[str]`):
|
| 142 |
+
The image descriptions, or with `images` the instructions.
|
| 143 |
+
height (`int`, *optional*, defaults to 512), width (`int`, *optional*, defaults to 512):
|
| 144 |
+
The size of the generated images in pixels, a multiple of `patch_size * merge_size`.
|
| 145 |
+
images (`list`, *optional*):
|
| 146 |
+
The input images of each prompt (`image_generation_pixel_values`): one image, or a list of one or
|
| 147 |
+
more read in order in the same user turn, before the instruction. The unconditional rows keep them and
|
| 148 |
+
drop the instruction.
|
| 149 |
+
guidance (`bool`, *optional*, defaults to `True`):
|
| 150 |
+
Whether to add the unconditional rows classifier-free guidance needs.
|
| 151 |
+
image_guidance (`bool`, *optional*):
|
| 152 |
+
Whether to add the image-free rows of image guidance (`generate_image(image_guidance_scale=...)`):
|
| 153 |
+
each prompt's instruction with no input image, the prompt of text-to-image. Needs `images` and
|
| 154 |
+
`guidance`. Defaults to `True` with `images` and `guidance` (editing samples with image guidance by
|
| 155 |
+
default), `False` otherwise.
|
| 156 |
+
|
| 157 |
+
Returns:
|
| 158 |
+
[`BatchFeature`] with, for `B` prompts:
|
| 159 |
+
- `input_ids`, `attention_mask`, `mm_token_type_ids` (1 at image tokens) of shape `(B, sequence_length)`,
|
| 160 |
+
`(2B, sequence_length)` with guidance, `(3B, sequence_length)` with image guidance: the prompts, then
|
| 161 |
+
their unconditional rows, then their image-free rows, each in prompt order. Padded on the right.
|
| 162 |
+
- `visual_grid_thw` of shape `(B, 3)`: the patch grid `(1, height // patch_size, width // patch_size)`.
|
| 163 |
+
- with `images`: `pixel_values` and `image_grid_thw` of the input images, in row order (the prompts' images,
|
| 164 |
+
then the unconditional rows' copies; the image-free rows have none).
|
| 165 |
+
"""
|
| 166 |
+
prompts = [prompts] if isinstance(prompts, str) else list(prompts)
|
| 167 |
+
patch_size, merge_size = self.image_processor.patch_size, self.image_processor.merge_size
|
| 168 |
+
unit = patch_size * merge_size
|
| 169 |
+
if height % unit or width % unit:
|
| 170 |
+
raise ValueError(f"height and width must be multiples of {unit}, got {height}x{width}")
|
| 171 |
+
if image_guidance is None:
|
| 172 |
+
image_guidance = images is not None and guidance
|
| 173 |
+
if image_guidance and (images is None or not guidance):
|
| 174 |
+
raise ValueError("image guidance needs input images and the unconditional rows (`guidance=True`)")
|
| 175 |
+
captions = prompts + ([""] * len(prompts) if guidance else []) + (prompts if image_guidance else [])
|
| 176 |
+
image_inputs, image_tokens = None, [[] for _ in captions]
|
| 177 |
+
if images is not None:
|
| 178 |
+
if len(images) != len(prompts):
|
| 179 |
+
raise ValueError(f"input images for {len(images)} prompts, {len(prompts)} prompts")
|
| 180 |
+
per_prompt = [list(i) if isinstance(i, (list, tuple)) else [i] for i in images]
|
| 181 |
+
if not all(per_prompt):
|
| 182 |
+
raise ValueError("a prompt given `images` needs at least one image")
|
| 183 |
+
image_inputs = self.image_generation_pixel_values([i for row in per_prompt for i in row])
|
| 184 |
+
counts = (image_inputs["image_grid_thw"].prod(dim=-1) // merge_size**2).tolist()
|
| 185 |
+
tokens, k = [], 0
|
| 186 |
+
for row in per_prompt:
|
| 187 |
+
tokens.append(counts[k:k + len(row)])
|
| 188 |
+
k += len(row)
|
| 189 |
+
image_tokens = tokens + (tokens if guidance else []) + ([[]] * len(prompts) if image_guidance else [])
|
| 190 |
+
rows = [self.image_generation_prompt_ids(caption, height, width, n)
|
| 191 |
+
for caption, n in zip(captions, image_tokens)]
|
| 192 |
+
length = max(len(ids) for ids in rows)
|
| 193 |
+
input_ids = torch.full((len(rows), length), self.tokenizer.pad_token_id, dtype=torch.long)
|
| 194 |
+
attention_mask = torch.zeros(len(rows), length, dtype=torch.long)
|
| 195 |
+
for i, ids in enumerate(rows):
|
| 196 |
+
input_ids[i, :len(ids)] = torch.tensor(ids)
|
| 197 |
+
attention_mask[i, :len(ids)] = 1
|
| 198 |
+
visual_grid_thw = torch.tensor([[1, height // patch_size, width // patch_size]] * len(prompts))
|
| 199 |
+
outputs = {
|
| 200 |
+
"input_ids": input_ids,
|
| 201 |
+
"attention_mask": attention_mask,
|
| 202 |
+
"mm_token_type_ids": ((input_ids == self.image_token_id) & (attention_mask == 1)).int(),
|
| 203 |
+
"visual_grid_thw": visual_grid_thw,
|
| 204 |
+
}
|
| 205 |
+
if image_inputs is not None:
|
| 206 |
+
repeat = 2 if guidance else 1
|
| 207 |
+
outputs["pixel_values"] = torch.cat([image_inputs["pixel_values"]] * repeat)
|
| 208 |
+
outputs["image_grid_thw"] = torch.cat([image_inputs["image_grid_thw"]] * repeat)
|
| 209 |
+
return BatchFeature(outputs)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
__all__ = ["IntegralProcessor"]
|
integral/sampling.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sampling of the flow-matching image generation: the timestep schedules, classifier-free guidance and the solvers
|
| 2 |
+
(Euler, second-order multistep DPM-Solver++). `t = 1` is noise and `t = 0` the clean latent; the model predicts the
|
| 3 |
+
velocity `noise - latent`."""
|
| 4 |
+
|
| 5 |
+
from collections.abc import Callable
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch import Tensor
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def flow_timesteps(num_inference_steps: int, time_shift: float, device=None, dtype=torch.float32) -> Tensor:
|
| 12 |
+
"""
|
| 13 |
+
The timesteps of a sampling run, from 1 to 0.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
num_inference_steps (`int`):
|
| 17 |
+
Number of solver steps.
|
| 18 |
+
time_shift (`float`):
|
| 19 |
+
The schedule shift `s`: `t = s * u / (1 + (s - 1) * u)` over `u` uniform in [1, 0]. 1.0 leaves `u` as is.
|
| 20 |
+
|
| 21 |
+
Returns:
|
| 22 |
+
`torch.FloatTensor` of shape `(num_inference_steps + 1,)`, descending.
|
| 23 |
+
"""
|
| 24 |
+
u = torch.linspace(1.0, 0.0, num_inference_steps + 1, device=device, dtype=dtype)
|
| 25 |
+
return u if time_shift == 1.0 else time_shift * u / (1 + (time_shift - 1) * u)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def classifier_free_guidance(velocity: Tensor, unconditional_velocity: Tensor, guidance_scale: float) -> Tensor:
|
| 29 |
+
"""`unconditional + guidance_scale * (conditional - unconditional)`, in fp32."""
|
| 30 |
+
unconditional_velocity = unconditional_velocity.float()
|
| 31 |
+
return unconditional_velocity + guidance_scale * (velocity.float() - unconditional_velocity)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def euler_step(latents: Tensor, velocity: Tensor, t: Tensor, t_next: Tensor) -> Tensor:
|
| 35 |
+
"""One Euler step of the flow ODE from `t` to `t_next`: `latents + (t_next - t) * velocity`."""
|
| 36 |
+
return latents + (t_next - t) * velocity
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def dpm_solver_timesteps(num_inference_steps: int, time_shift: float, device=None) -> Tensor:
|
| 40 |
+
"""
|
| 41 |
+
The timesteps of a DPM-Solver++ run, from `1 - 0.001` shifted down to 0.
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
num_inference_steps (`int`):
|
| 45 |
+
Number of solver steps.
|
| 46 |
+
time_shift (`float`):
|
| 47 |
+
The schedule shift `s`: `t = s * u / (1 + (s - 1) * u)` over `u` uniform in [0.999, 0].
|
| 48 |
+
|
| 49 |
+
Returns:
|
| 50 |
+
`torch.FloatTensor` of shape `(num_inference_steps + 1,)`, descending.
|
| 51 |
+
"""
|
| 52 |
+
u = 1.0 - torch.linspace(1.0, 0.001, num_inference_steps + 1).to(device)
|
| 53 |
+
return (time_shift * u / (1 + (time_shift - 1) * u)).flip(dims=[0])
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _half_log_snr(t: Tensor) -> Tensor:
|
| 57 |
+
"""`log(alpha_t) - log(sigma_t)` with `alpha_t = 1 - t`, `sigma_t = t`."""
|
| 58 |
+
return torch.log(1 - t) - torch.log(t)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _dpm_solver_first_order_update(latents: Tensor, data: Tensor, s: Tensor, t: Tensor) -> Tensor:
|
| 62 |
+
"""First-order DPM-Solver++ update from `s` to `t` with the data prediction at `s`."""
|
| 63 |
+
h = _half_log_snr(t) - _half_log_snr(s)
|
| 64 |
+
alpha_t = torch.exp(torch.log(1 - t))
|
| 65 |
+
phi_1 = torch.expm1(-h)
|
| 66 |
+
return t / s * latents - alpha_t * phi_1 * data
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _dpm_solver_second_order_update(
|
| 70 |
+
latents: Tensor, data_prev: Tensor, data: Tensor, s_prev: Tensor, s: Tensor, t: Tensor
|
| 71 |
+
) -> Tensor:
|
| 72 |
+
"""Second-order multistep DPM-Solver++ update from `s` to `t` with the data predictions at `s_prev` and `s`."""
|
| 73 |
+
lambda_prev, lambda_s, lambda_t = _half_log_snr(s_prev), _half_log_snr(s), _half_log_snr(t)
|
| 74 |
+
alpha_t = torch.exp(torch.log(1 - t))
|
| 75 |
+
h_prev = lambda_s - lambda_prev
|
| 76 |
+
h = lambda_t - lambda_s
|
| 77 |
+
r = h_prev / h
|
| 78 |
+
d = (1.0 / r) * (data - data_prev)
|
| 79 |
+
phi_1 = torch.expm1(-h)
|
| 80 |
+
return (t / s) * latents - (alpha_t * phi_1) * data - 0.5 * (alpha_t * phi_1) * d
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def dpm_solver_sample(velocity_fn: Callable[[Tensor, Tensor], Tensor], latents: Tensor, timesteps: Tensor) -> Tensor:
|
| 84 |
+
"""
|
| 85 |
+
Integrates the flow ODE with the second-order multistep DPM-Solver++ (data prediction), one model call per step.
|
| 86 |
+
The first and the last step are first order.
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
velocity_fn (`Callable`):
|
| 90 |
+
`velocity_fn(latents, t)` -> the velocity at `t` (a 0-dim tensor). It is called at `t * 1000 / 1000`, the
|
| 91 |
+
timestep taken to the solver's 1000-step time scale and back.
|
| 92 |
+
latents (`torch.FloatTensor`):
|
| 93 |
+
The noise at `timesteps[0]`.
|
| 94 |
+
timesteps (`torch.FloatTensor` of shape `(num_inference_steps + 1,)`):
|
| 95 |
+
`dpm_solver_timesteps`; at least two steps.
|
| 96 |
+
|
| 97 |
+
Returns:
|
| 98 |
+
`torch.FloatTensor`: the latents at `timesteps[-1]`.
|
| 99 |
+
"""
|
| 100 |
+
num_steps = timesteps.shape[0] - 1
|
| 101 |
+
if num_steps < 2:
|
| 102 |
+
raise ValueError(f"DPM-Solver++ needs at least 2 steps, got {num_steps}")
|
| 103 |
+
data_prev = None
|
| 104 |
+
for i in range(num_steps):
|
| 105 |
+
s, t = timesteps[i], timesteps[i + 1]
|
| 106 |
+
velocity = velocity_fn(latents, s * 1000 / 1000).float()
|
| 107 |
+
noise = (1 - s) * velocity + latents
|
| 108 |
+
data = (latents - s * noise) / (1 - s)
|
| 109 |
+
if i == 0 or i == num_steps - 1:
|
| 110 |
+
latents = _dpm_solver_first_order_update(latents, data, s, t)
|
| 111 |
+
else:
|
| 112 |
+
latents = _dpm_solver_second_order_update(latents, data_prev, data, timesteps[i - 1], s, t)
|
| 113 |
+
data_prev = data
|
| 114 |
+
return latents
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
transformers==5.14.1
|
| 2 |
+
accelerate==1.14.0
|
| 3 |
+
sentencepiece
|
| 4 |
+
protobuf
|
| 5 |
+
einops
|
| 6 |
+
pillow
|
| 7 |
+
numpy
|