Text-to-Image
Diffusers
English
jeveration
image-to-image
depth-estimation
image-segmentation
modular-diffusers
Run this model with HF Jobs
Run OzzyGT/jeveration_custom_blocks on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/OzzyGT/jeveration_custom_blocks. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/OzzyGT/jeveration_custom_blocks on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use OzzyGT/jeveration_custom_blocks with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use OzzyGT/jeveration_custom_blocks with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("OzzyGT/jeveration_custom_blocks", dtype=torch.bfloat16, device_map="cuda") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- Draw Things
- DiffusionBee
add blocks
Browse filesFiles changed (17)
- .gitignoreAdded+2
- LICENSEAdded+202
- NOTICEAdded+8
- README.mdAdded+101
- __init__.pyAdded
- components.pyAdded+63
- convert_jeveration_to_diffusers.pyAdded+258
- decide.pyAdded+64
- decoders.pyAdded+182
- dense.pyAdded+71
- encoders.pyAdded+247
- image_decoder_jeveration.pyAdded+205
- modular_blocks_jeveration.pyAdded+91
- modular_config.jsonAdded+12
- modular_model_index.jsonAdded+4
- prompts_jeveration.pyAdded+245
- transformer_jeveration.pyAdded+412
12__pycache__/.ruff_cache/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.12345678Jeveration Modular Diffusers blocksCopyright 2026 The HuggingFace Team
This product includes software adapted from Jeveration (https://github.com/Carol-lyh/Jeveration),Copyright 2026 The Jeveration Authors, licensed under the Apache License, Version 2.0.
This product includes software adapted from TA-TiTok (https://github.com/bytedance/1d-tokenizer),Copyright (2024) Bytedance Ltd. and/or its affiliates, licensed under the Apache License, Version 2.0.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101---language:- enlicense: apache-2.0base_model:- linlinlinlinsdada/Jeverationpipeline_tag: text-to-imagetags:- jeveration- text-to-image- image-to-image- depth-estimation- image-segmentation- modular-diffuserslibrary_name: diffusers---# Jeveration Modular Diffusers

*Generated with the text-to-image code below, seed `0`.*
Modular Diffusers blocks for [Jeveration](https://huggingface.co/linlinlinlinsdada/Jeveration)([paper](https://arxiv.org/abs/2611.24738), [code](https://github.com/Carol-lyh/Jeveration)), a Qwen3.5-4B that makes awhole 512 x 512 image in one step. One model does text-to-image, image-to-image (edge map or depth map to image,colorization, three styles) and indoor depth, surface normals and segmentation. The blocks ship the model code and loadthe weights from [OzzyGT/jeveration_diffusers](https://huggingface.co/OzzyGT/jeveration_diffusers).
Requires PyTorch, `diffusers>=0.41.0`, `transformers>=5.14.0` and `ftfy`. Installing[`flash-linear-attention`](https://github.com/fla-org/flash-linear-attention) makes the model faster on NVIDIA GPUs;transformers uses it on its own when it is installed.
## Usage
```pythonimport torchfrom diffusers import ModularPipelineBlocks
blocks = ModularPipelineBlocks.from_pretrained("OzzyGT/jeveration_custom_blocks", trust_remote_code=True)pipe = blocks.init_pipeline()pipe.load_components(dtype={"default": torch.bfloat16, "text_encoder": torch.float32})pipe.to("cuda")```
This needs about 12 GiB of VRAM. Prompts are in English and images are 512 x 512.
### Text-to-image
```pythonprompt = ( "A cozy wooden cabin in a snowy pine forest at dusk, warm light glowing from its windows, smoke rising from the " "chimney, snow-covered mountains and a starry purple sky behind it.")image = pipe(prompt=prompt, generator=torch.Generator("cuda").manual_seed(0)).get("images")[0]image.save("cabin.png")```
### Image-to-image
Pass an `image` and a `task`. Pictures of other sizes are resized and centre cropped to 512 x 512.
| Task | Image | `prompt` || --- | --- | --- || `hed` | a soft edge map | a caption of the wanted image || `depth` | a depth map, bright is near | a caption of the wanted image || `colorize` | any photo, made grey first | not used || `anime`, `ghibli`, `watercolor` | a photo | not used |
```pythonimage = pipe(image="cabin.png", task="watercolor", generator=torch.Generator("cuda").manual_seed(0)).get("images")[0]image.save("cabin_watercolor.png")
image = pipe(image="cabin.png", task="colorize", generator=torch.Generator("cuda").manual_seed(0)).get("images")[0]image.save("cabin_colorized.png")```
### Depth, normals and segmentation
For pictures of rooms.
```pythonstate = pipe(image="room.jpg", dense_tasks=["seg", "depth", "normal"])predictions, pictures = state.get("predictions"), state.get("prediction_images")# predictions["seg"]: class index of every pixel, (1, H, W)# predictions["depth"]: meters, (1, H, W)# predictions["normal"]: unit vectors, (1, H, W, 3)# pictures: the same as PIL images, to look atpictures["depth"][0].save("room_depth.png")```
The segmentation classes are bed, books, ceiling, chair, floor, furniture, objects, picture, sofa, table, tv, wall andwindow. The model learned these on indoor scenes; other content works less well.
## Licensing
The blocks are [Apache-2.0](https://huggingface.co/OzzyGT/jeveration_custom_blocks/blob/main/LICENSE), with codeadapted from [Jeveration](https://github.com/Carol-lyh/Jeveration) and[TA-TiTok](https://github.com/bytedance/1d-tokenizer), both Apache-2.0 (see[NOTICE](https://huggingface.co/OzzyGT/jeveration_custom_blocks/blob/main/NOTICE)). For the weights, see the[model repository](https://huggingface.co/OzzyGT/jeveration_diffusers).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263# Copyright 2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0. See the LICENSE file in this repository.
from transformers import AutoTokenizer, CLIPTextModel, CLIPTokenizer
from diffusers.modular_pipelines.modular_pipeline_utils import ComponentSpec
from .image_decoder_jeveration import JeverationImageDecoderfrom .transformer_jeveration import JeverationTransformer
# The converted weights. The model classes come from this repo, so the weights repo holds no code. Load from elsewhere# with `pipe.load_components(pretrained_model_name_or_path=...)`.JEVERATION_WEIGHTS_REPO = "OzzyGT/jeveration_diffusers"
def transformer_spec() -> ComponentSpec: return ComponentSpec( "transformer", JeverationTransformer, pretrained_model_name_or_path=JEVERATION_WEIGHTS_REPO, subfolder="transformer", )
def image_decoder_spec() -> ComponentSpec: return ComponentSpec( "image_decoder", JeverationImageDecoder, pretrained_model_name_or_path=JEVERATION_WEIGHTS_REPO, subfolder="image_decoder", )
def source_image_decoder_spec() -> ComponentSpec: return ComponentSpec( "source_image_decoder", JeverationImageDecoder, pretrained_model_name_or_path=JEVERATION_WEIGHTS_REPO, subfolder="source_image_decoder", )
def text_encoder_spec() -> ComponentSpec: return ComponentSpec( "text_encoder", CLIPTextModel, pretrained_model_name_or_path=JEVERATION_WEIGHTS_REPO, subfolder="text_encoder" )
def tokenizer_spec() -> ComponentSpec: return ComponentSpec( "tokenizer", AutoTokenizer, pretrained_model_name_or_path=JEVERATION_WEIGHTS_REPO, subfolder="tokenizer" )
def clip_tokenizer_spec() -> ComponentSpec: return ComponentSpec( "clip_tokenizer", CLIPTokenizer, pretrained_model_name_or_path=JEVERATION_WEIGHTS_REPO, subfolder="clip_tokenizer", )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258# Copyright 2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0. See the LICENSE file in this repository.
"""Converts Jeveration (https://huggingface.co/linlinlinlinsdada/Jeveration) to the Diffusers layout.
python -m jeveration_custom_blocks.convert_jeveration_to_diffusers --output jeveration_diffusers \ [--original <local copy of the repo>]
Run it from the folder that holds this repository, as a module: it imports the model classes next to it.
Writes transformer/ (Qwen3.5-4B with the rank-256 adapters merged in, the decision and dense heads), image_decoder/ andsource_image_decoder/ (the 512-px TA-TiTok decoders with the codebook), text_encoder/ (CLIP ViT-L/14-336's text toweras a transformers CLIPTextModel), tokenizer/ (Qwen3.5) and clip_tokenizer/. Values are not changed apart from themerged adapters; packed attention projections are split into q, k and v, and the reference's short module names getdescriptive ones (`TRANSFORMER_RENAMES`, `DECODER_RENAMES`)."""
import argparseimport jsonimport refrom pathlib import Path
import torchfrom huggingface_hub import hf_hub_download, snapshot_downloadfrom safetensors import safe_openfrom transformers import AutoTokenizer, CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers.utils import logging
from .image_decoder_jeveration import JeverationImageDecoderfrom .transformer_jeveration import JeverationTransformer
logger = logging.get_logger(__name__)
ORIGINAL_REPO = "linlinlinlinsdada/Jeveration"# The public models the checkpoint builds on, at the revisions the reference code pins.BACKBONE = ("Qwen/Qwen3.5-4B", "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a")TATITOK = ("turkeyju/tokenizer_tatitok_bl128_vq", "7650d466a955c754265d20e57513518a4e049f00")CLIP_TEXT = ("timm/vit_large_patch14_clip_336.openai", "81e38efc4637de5023b10e75a7f9bd1c6fa6b010")
# The reference's module names -> ours, as (pattern, replacement) on state dict keys.TRANSFORMER_RENAMES = [ (r"^z_in\.", "state_proj."), (r"^z_pos$", "decision_pos_embed"), (r"^t_mlp\.", "time_embed."), (r"^h_mlp\.", "interval_embed."), (r"^cond\.", "cond_embed."), (r"^dense_q_vis\.", "dense_vision_proj."), (r"^head\.inp\.", "head.hidden_proj."), (r"^head\.zin\.", "head.state_proj."), (r"^head\.pos$", "head.pos_embed"), (r"^head\.ada_f\.", "head.norm_out_modulation."), (r"^head\.out\.", "head.proj_out."), (r"^(head\.blocks\.\d+)\.ada\.", r"\1.modulation."),]DECODER_RENAMES = [ (r"^ln_pre\.", "norm_in."), (r"^ln_post\.", "norm_out."), (r"^(transformer\.\d+)\.ln_1\.", r"\1.norm1."), (r"^(transformer\.\d+)\.ln_2\.", r"\1.norm2."), (r"^(transformer\.\d+)\.mlp\.c_fc\.", r"\1.mlp.fc1."), (r"^(transformer\.\d+)\.mlp\.c_proj\.", r"\1.mlp.fc2."), (r"^(cond_gates\.\d+)\.gx\.", r"\1.patch_gate."), (r"^(cond_gates\.\d+)\.gc\.", r"\1.source_gate."),]
def load_tensors(path, prefix=""): with safe_open(str(path), "pt") as handle: return {key: handle.get_tensor(key) for key in handle.keys() if key.startswith(prefix)}
def rename_keys(state, renames): """A new dict with every key passed through the (pattern, replacement) pairs.""" renamed = {} for key, value in state.items(): for pattern, replacement in renames: key = re.sub(pattern, replacement, key) renamed[key] = value return renamed
def load_checkpoint(path): return torch.load(path, map_location="cpu", mmap=True, weights_only=True)
def backbone_state(backbone_dir): """The language model and vision tower of Qwen3.5-4B, keyed as in Qwen3_5ForConditionalGeneration.""" index = json.loads((backbone_dir / "model.safetensors.index.json").read_text()) state = {} for shard in sorted(set(index["weight_map"].values())): state.update(load_tensors(backbone_dir / shard, "model.")) return state
def split_attention(state, packed_weight, packed_bias, out, within=""): """Every packed attention in `state` (keys under `within`): the q, k, v projection `<prefix><packed_weight>` and `<prefix><packed_bias>` and the output projection `<prefix><out>` -> `<prefix>attn.to_q`, `to_k`, `to_v` and `to_out.0`. Returns a new dict.""" state = dict(state) for key in [name for name in state if name.startswith(within) and name.endswith(packed_weight)]: prefix = key[: -len(packed_weight)] weights, biases = state.pop(key).chunk(3), state.pop(prefix + packed_bias).chunk(3) for name, weight, bias in zip(("to_q", "to_k", "to_v"), weights, biases): state[f"{prefix}attn.{name}.weight"], state[f"{prefix}attn.{name}.bias"] = weight, bias for kind in ("weight", "bias"): state[f"{prefix}attn.to_out.0.{kind}"] = state.pop(f"{prefix}{out}.{kind}") return state
def transformer_state(model, backbone, jeveration, codebook): """Our transformer's state dict: the backbone weights with the checkpoint's adapters merged in, its heads, and the standardised codebook.""" ema = split_attention(jeveration["ema"], "qkv.weight", "qkv.bias", "proj", within="head.blocks.") ema = rename_keys(ema, TRANSFORMER_RENAMES) state = {} for name in model.state_dict(): if name == "codebook_std": continue if name.startswith(("language_model.", "visual.")): state[name] = backbone.pop("model." + name) else: state[name] = ema[name] # The adapters: W + (alpha / rank) B A with alpha = rank, in float32, stored in the backbone's dtype. adapters = [key for key in ema if key.startswith("lm.") and key.endswith(".lora_A")] for key in adapters: name = "language_model." + key[len("lm.") : -len(".lora_A")] + ".weight" weight = state[name] update = ema[key.replace(".lora_A", ".lora_B")].float() @ ema[key].float() state[name] = (weight.float() + update).to(weight.dtype) if len(adapters) != 200: raise ValueError(f"Expected 200 adapters, found {len(adapters)}.") # As the reference: the codebook in half precision, standardised with the code statistics. codebook = codebook.float().to(torch.float16).float() state["codebook_std"] = (codebook - jeveration["lat_mean"].float().view(1, -1)) / jeveration[ "lat_std" ].float().view(1, -1) leftover = [key for key in backbone if not key.startswith("model.mtp")] if leftover: logger.warning(f"Unused backbone weights: {leftover[:5]} ({len(leftover)})") return state
def clip_text_state(open_clip_state): """open_clip's text tower -> transformers CLIPTextModel keys (q, k and v split out of the packed projection).""" source = open_clip_state out = { "embeddings.token_embedding.weight": source["token_embedding.weight"], "embeddings.position_embedding.weight": source["positional_embedding"], "final_layer_norm.weight": source["ln_final.weight"], "final_layer_norm.bias": source["ln_final.bias"], } layers = 1 + max(int(key.split(".")[2]) for key in source if key.startswith("transformer.resblocks.")) for layer in range(layers): theirs_prefix, ours_prefix = f"transformer.resblocks.{layer}.", f"encoder.layers.{layer}." for proj, weight, bias in zip( ("q_proj", "k_proj", "v_proj"), source[theirs_prefix + "attn.in_proj_weight"].chunk(3), source[theirs_prefix + "attn.in_proj_bias"].chunk(3), ): (out[ours_prefix + f"self_attn.{proj}.weight"], out[ours_prefix + f"self_attn.{proj}.bias"]) = weight, bias pairs = { "attn.out_proj": "self_attn.out_proj", "ln_1": "layer_norm1", "ln_2": "layer_norm2", "mlp.c_fc": "mlp.fc1", "mlp.c_proj": "mlp.fc2", } for theirs, ours in pairs.items(): out[ours_prefix + ours + ".weight"], out[ours_prefix + ours + ".bias"] = ( source[theirs_prefix + theirs + ".weight"], source[theirs_prefix + theirs + ".bias"], ) return out, layers
def build_transformer(backbone_dir, jeveration, codebook): config = json.loads((backbone_dir / "config.json").read_text()) text, vision = dict(config["text_config"]), dict(config["vision_config"]) with torch.device("meta"): model = JeverationTransformer(text_config=text, vision_config=vision, image_token_id=config["image_token_id"]) state = transformer_state(model, backbone_state(backbone_dir), jeveration, codebook) model.load_state_dict(state, strict=True, assign=True) # The rotary frequencies are non-persistent buffers, created on the meta device: rebuild the two modules on the CPU. language_model, visual = model.language_model, model.visual language_model.rotary_emb = type(language_model.rotary_emb)(config=language_model.config) visual.rotary_pos_emb = type(visual.rotary_pos_emb)(visual.rotary_pos_emb.dim, visual.rotary_pos_emb.theta) return model.eval()
def build_decoder(checkpoint, codebook, source_branch): with torch.device("meta"): decoder = JeverationImageDecoder(source_branch=source_branch) state = dict(checkpoint.get("ema_plain", checkpoint)) if not source_branch: state = {key: value for key, value in state.items() if not key.startswith("cond_")} state = split_attention(state, "attn.in_proj_weight", "attn.in_proj_bias", "attn.out_proj", within="transformer.") state = rename_keys(state, DECODER_RENAMES) state["codebook"] = codebook.float() decoder.load_state_dict(state, strict=True, assign=True) return decoder.eval()
def build_text_encoder(clip_path): state, layers = clip_text_state(load_tensors(clip_path)) config = CLIPTextConfig( vocab_size=state["embeddings.token_embedding.weight"].shape[0], hidden_size=768, intermediate_size=3072, num_hidden_layers=layers, num_attention_heads=12, max_position_embeddings=77, hidden_act="quick_gelu", projection_dim=768, bos_token_id=49406, eos_token_id=49407, pad_token_id=0, ) with torch.device("meta"): model = CLIPTextModel(config) model.load_state_dict(state, strict=True, assign=True) return model.eval()
def convert(original_dir, output_dir): original_dir, output_dir = Path(original_dir), Path(output_dir) backbone_dir = Path(snapshot_download(BACKBONE[0], revision=BACKBONE[1])) codebook = load_tensors(hf_hub_download(TATITOK[0], "model.safetensors", revision=TATITOK[1]))[ "quantize.embedding.weight" ] clip_path = hf_hub_download(CLIP_TEXT[0], "open_clip_model.safetensors", revision=CLIP_TEXT[1])
transformer = build_transformer(backbone_dir, load_checkpoint(original_dir / "jeveration.pt"), codebook) transformer.save_pretrained(output_dir / "transformer", max_shard_size="5GB") del transformer for name, file, source_branch in ( ("image_decoder", "decoder512.pt", False), ("source_image_decoder", "source_decoder512.pt", True), ): build_decoder(load_checkpoint(original_dir / file), codebook, source_branch).save_pretrained(output_dir / name) build_text_encoder(clip_path).save_pretrained(output_dir / "text_encoder") AutoTokenizer.from_pretrained(backbone_dir).save_pretrained(output_dir / "tokenizer") CLIPTokenizer.from_pretrained(Path(clip_path).parent).save_pretrained(output_dir / "clip_tokenizer")
def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--output", required=True) parser.add_argument("--original", default=None, help="Local copy of the original repo (default: download it).") args = parser.parse_args() original = args.original or snapshot_download(ORIGINAL_REPO) convert(original, args.output)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# Copyright 2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0. See the LICENSE file in this repository.
import torch
from diffusers.modular_pipelines import ModularPipelineBlocks, PipelineStatefrom diffusers.modular_pipelines.modular_pipeline_utils import ComponentSpec, InputParam, OutputParamfrom diffusers.utils.torch_utils import get_module_execution_device
from .components import transformer_spec
class JeverationDecideStep(ModularPipelineBlocks): model_name = "jeveration"
@property def description(self) -> str: return ( "Step that decides the image in one forward pass: a shared random state is drawn, the backbone reads the " "request and 128 decision tokens built from that state, and every code is sampled at once." )
@property def expected_components(self) -> list[ComponentSpec]: return [transformer_spec()]
@property def inputs(self) -> list[InputParam]: return [ InputParam("input_ids", required=True, type_hint=torch.Tensor, description="Request token ids `[B, L]`."), InputParam( "attention_mask", required=True, type_hint=torch.Tensor, description="Padding mask of the request ids." ), InputParam("position_ids", type_hint=torch.Tensor, description="Rotary positions of an image request."), InputParam("pixel_values", type_hint=torch.Tensor, description="The source images of an image request."), InputParam.template("generator"), ]
@property def intermediate_outputs(self) -> list[OutputParam]: return [OutputParam("codes", type_hint=torch.Tensor, description="Image codes `[B, 128]`, int64.")]
@torch.no_grad() def __call__(self, components, state: PipelineState) -> PipelineState: block_state = self.get_block_state(state) transformer = components.transformer device = get_module_execution_device(transformer) generator = block_state.generator random_state, masked_share = transformer.sample_random_state(block_state.input_ids.shape[0], generator) logits = transformer( input_ids=block_state.input_ids.to(device), attention_mask=block_state.attention_mask.to(device), position_ids=None if block_state.position_ids is None else block_state.position_ids.to(device), pixel_values=None if block_state.pixel_values is None else block_state.pixel_values.to(device), random_state=random_state, masked_share=masked_share, ).logits probs = torch.softmax(logits.float(), -1) draw_device = generator.device if generator is not None else probs.device codes = torch.multinomial(probs.view(-1, probs.shape[-1]).to(draw_device), 1, generator=generator) block_state.codes = codes.view(logits.shape[:2]) self.set_block_state(state, block_state) return components, state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182# Copyright 2026 The HuggingFace Team and The Jeveration Authors. All rights reserved.## Licensed under the Apache License, Version 2.0. See the LICENSE and NOTICE files in this repository.## Adapted from the Jeveration code (https://github.com/Carol-lyh/Jeveration, Apache-2.0): jeveration/pipeline.py and# dense.py.
import numpy as npimport PIL.Imageimport torchimport torch.nn.functional as F
from diffusers.modular_pipelines import ModularPipelineBlocks, PipelineStatefrom diffusers.modular_pipelines.modular_pipeline_utils import ComponentSpec, InputParam, OutputParamfrom diffusers.utils.torch_utils import get_module_execution_device
from .components import clip_tokenizer_spec, image_decoder_spec, source_image_decoder_spec, text_encoder_specfrom .prompts_jeveration import clip_input_ids, depth_view, normal_view, seg_view
def text_guidance(text_encoder, clip_tokenizer, texts): """The CLIP text tower's per-token output [B, 77, 768] for the decoder, in float32.""" ids = clip_input_ids(clip_tokenizer, texts).to(get_module_execution_device(text_encoder)) return text_encoder(ids).last_hidden_state.float()
def to_predictions(task, raw): """A raw map [B, C, H, W] -> seg: class indices [B, H, W]; depth: meters [B, H, W]; normal: unit vectors [B, H, W, 3].""" if task == "seg": return raw.argmax(1) if task == "depth": return raw[:, 0].clamp(-5, 5).exp() return F.normalize(raw.permute(0, 2, 3, 1), dim=-1)
def to_output(images, output_type): """float images [B, 3, H, W] (not clamped) -> PIL images, or float in [0, 1]: numpy [B, H, W, 3] or tensors [B, 3, H, W].""" images = images.clamp(0, 1) if output_type == "pt": return images array = images.permute(0, 2, 3, 1).cpu().numpy() if output_type == "np": return array return [PIL.Image.fromarray(image) for image in (array * 255).round().astype("uint8")]
class JeverationDecodeStep(ModularPipelineBlocks): model_name = "jeveration"
@property def description(self) -> str: return ( "Step that turns the codes into 512 x 512 images with the text-aware decoder, which also reads the prompt." )
@property def expected_components(self) -> list[ComponentSpec]: return [image_decoder_spec(), text_encoder_spec(), clip_tokenizer_spec()]
@property def inputs(self) -> list[InputParam]: return [ InputParam("codes", required=True, type_hint=torch.Tensor, description="Image codes `[B, 128]`."), InputParam("decoder_texts", required=True, type_hint=list, description="The texts the decoder reads."), InputParam.template("output_type"), ]
@property def intermediate_outputs(self) -> list[OutputParam]: return [OutputParam("images", type_hint=list, description="The generated 512 x 512 images.")]
@torch.no_grad() def __call__(self, components, state: PipelineState) -> PipelineState: block_state = self.get_block_state(state) decoder = components.image_decoder device = get_module_execution_device(decoder) guidance = text_guidance(components.text_encoder, components.clip_tokenizer, block_state.decoder_texts) images = decoder(block_state.codes.to(device), guidance.to(device)).float() block_state.images = to_output(images, block_state.output_type) self.set_block_state(state, block_state) return components, state
class JeverationSourceDecodeStep(ModularPipelineBlocks): model_name = "jeveration"
@property def description(self) -> str: return ( "Step that turns the codes into 512 x 512 images with the source decoder, which also reads the source image " "and the task." )
@property def expected_components(self) -> list[ComponentSpec]: return [source_image_decoder_spec(), text_encoder_spec(), clip_tokenizer_spec()]
@property def inputs(self) -> list[InputParam]: return [ InputParam("codes", required=True, type_hint=torch.Tensor, description="Image codes `[B, 128]`."), InputParam("decoder_texts", required=True, type_hint=list, description="The texts the decoder reads."), InputParam("pixel_values", required=True, type_hint=torch.Tensor, description="Sources, uint8."), InputParam("decoder_task_ids", required=True, type_hint=torch.Tensor, description="Decoder task ids."), InputParam.template("output_type"), ]
@property def intermediate_outputs(self) -> list[OutputParam]: return [OutputParam("images", type_hint=list, description="The generated 512 x 512 images.")]
@torch.no_grad() def __call__(self, components, state: PipelineState) -> PipelineState: block_state = self.get_block_state(state) decoder = components.source_image_decoder device = get_module_execution_device(decoder) guidance = text_guidance(components.text_encoder, components.clip_tokenizer, block_state.decoder_texts) source = block_state.pixel_values.permute(0, 3, 1, 2).float().div(255).to(device) images = decoder( block_state.codes.to(device), guidance.to(device), source, block_state.decoder_task_ids.to(device) ).float() block_state.images = to_output(images, block_state.output_type) self.set_block_state(state, block_state) return components, state
class JeverationDensePostprocessStep(ModularPipelineBlocks): model_name = "jeveration"
@property def description(self) -> str: return ( "Step that scales the raw maps to the pictures' size and turns them into predictions: class indices, " "depth in meters and unit normals, with pictures that show them." )
@property def inputs(self) -> list[InputParam]: return [ InputParam("dense_maps", required=True, type_hint=dict, description="Task -> raw maps `[B, C, h, w]`."), InputParam("pictures", required=True, type_hint=np.ndarray, description="The pictures, uint8."), ]
@property def intermediate_outputs(self) -> list[OutputParam]: return [ OutputParam( "predictions", type_hint=dict, description="Task -> numpy array at the picture's size: `seg` class indices [B, H, W] (see " "`NYU13`), `depth` meters [B, H, W], `normal` unit vectors [B, H, W, 3].", ), OutputParam( "prediction_images", type_hint=dict, description="Task -> PIL images that show the predictions." ), ]
@torch.no_grad() def __call__(self, components, state: PipelineState) -> PipelineState: block_state = self.get_block_state(state) pictures = block_state.pictures size = tuple(pictures.shape[1:3]) predictions = { task: to_predictions(task, F.interpolate(raw.float(), size=size, mode="bilinear", align_corners=False)) .cpu() .numpy() for task, raw in block_state.dense_maps.items() } views = { "seg": lambda prediction, index: seg_view(prediction, pictures[index]), "depth": lambda prediction, index: depth_view(prediction), "normal": lambda prediction, index: normal_view(prediction), } block_state.predictions = predictions block_state.prediction_images = { task: [PIL.Image.fromarray(views[task](prediction[index], index)) for index in range(len(pictures))] for task, prediction in predictions.items() } self.set_block_state(state, block_state) return components, state1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071# Copyright 2026 The HuggingFace Team and The Jeveration Authors. All rights reserved.## Licensed under the Apache License, Version 2.0. See the LICENSE and NOTICE files in this repository.## Adapted from the Jeveration code (https://github.com/Carol-lyh/Jeveration, Apache-2.0): jeveration/pipeline.py.
import torch
from diffusers.modular_pipelines import ModularPipelineBlocks, PipelineStatefrom diffusers.modular_pipelines.modular_pipeline_utils import ComponentSpec, InputParam, OutputParamfrom diffusers.utils.torch_utils import get_module_execution_device
from .components import transformer_spec
class JeverationDensePredictStep(ModularPipelineBlocks): model_name = "jeveration"
@property def description(self) -> str: return ( "Step that predicts the raw per-pixel maps of every request row in one forward pass: segmentation logits, " "log-depth or surface normals, at the dense input size." )
@property def expected_components(self) -> list[ComponentSpec]: return [transformer_spec()]
@property def inputs(self) -> list[InputParam]: return [ InputParam( "input_ids", required=True, type_hint=torch.Tensor, description="Request token ids `[rows, L]`." ), InputParam( "attention_mask", required=True, type_hint=torch.Tensor, description="Padding mask of the request ids." ), InputParam( "position_ids", required=True, type_hint=torch.Tensor, description="Rotary positions `[3, rows, L]`." ), InputParam( "pixel_values", required=True, type_hint=torch.Tensor, description="The resized pictures, uint8." ), InputParam("dense_rows", required=True, type_hint=list, description="The task of each request row."), ]
@property def intermediate_outputs(self) -> list[OutputParam]: return [ OutputParam( "dense_maps", type_hint=dict, description="Task -> raw maps `[B, C, h, w]` of that task's rows, in order, at the dense input size.", ) ]
@torch.no_grad() def __call__(self, components, state: PipelineState) -> PipelineState: block_state = self.get_block_state(state) transformer = components.transformer device = get_module_execution_device(transformer) block_state.dense_maps = transformer( input_ids=block_state.input_ids.to(device), attention_mask=block_state.attention_mask.to(device), position_ids=block_state.position_ids.to(device), pixel_values=block_state.pixel_values.to(device), dense_tasks=block_state.dense_rows, ).dense_maps self.set_block_state(state, block_state) return components, state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247# Copyright 2026 The HuggingFace Team and The Jeveration Authors. All rights reserved.## Licensed under the Apache License, Version 2.0. See the LICENSE and NOTICE files in this repository.## Adapted from the Jeveration code (https://github.com/Carol-lyh/Jeveration, Apache-2.0): jeveration/pipeline.py and# dense.py.
import numpy as npimport PIL.Imageimport torchimport torch.nn.functional as F
from diffusers.modular_pipelines import ModularPipelineBlocks, PipelineStatefrom diffusers.modular_pipelines.modular_pipeline_utils import ComponentSpec, InputParam, OutputParamfrom diffusers.utils import load_imagefrom diffusers.utils.torch_utils import get_module_execution_device
from .components import tokenizer_spec, transformer_specfrom .prompts_jeveration import ( DECODER_TASK_ID, DENSE_INSTRUCTIONS, DENSE_TASKS, I2I_TASKS, IMAGE_SIZE, encode_instruction, encode_text_prompts, i2i_texts, image_requests, load_square, to_gray,)
def as_list(value, batch=None): if value is None: return None if isinstance(value, (list, tuple)): return list(value) return [value] * (batch or 1)
class JeverationTextInputStep(ModularPipelineBlocks): model_name = "jeveration"
@property def description(self) -> str: return ( "Step that puts the prompts in the backbone's chat format (`Generate an image: <prompt>`), cut to 128 tokens " "and left padded. The decoder reads the prompts themselves." )
@property def expected_components(self) -> list[ComponentSpec]: return [tokenizer_spec()]
@property def inputs(self) -> list[InputParam]: return [InputParam.template("prompt", note="in English, one image per prompt")]
@property def intermediate_outputs(self) -> list[OutputParam]: return [ OutputParam("input_ids", type_hint=torch.Tensor, description="Request token ids `[B, L]`, left padded."), OutputParam("attention_mask", type_hint=torch.Tensor, description="Padding mask of the request ids."), OutputParam("decoder_texts", type_hint=list, description="The texts the image decoder reads."), ]
@torch.no_grad() def __call__(self, components, state: PipelineState) -> PipelineState: block_state = self.get_block_state(state) prompts = as_list(block_state.prompt) block_state.input_ids, block_state.attention_mask = encode_text_prompts(components.tokenizer, prompts) block_state.decoder_texts = prompts self.set_block_state(state, block_state) return components, state
class JeverationImageInputStep(ModularPipelineBlocks): model_name = "jeveration"
@property def description(self) -> str: return ( "Step that prepares an image-to-image request: the source image (shorter side to 512, centre crop) for the " "backbone's vision tower, followed by the task's trained instruction." )
@property def expected_components(self) -> list[ComponentSpec]: return [transformer_spec(), tokenizer_spec()]
@property def inputs(self) -> list[InputParam]: return [ InputParam( "image", required=True, type_hint=PIL.Image.Image, description="The source image, or a list of them: a PIL image, path or URL. For `hed` and `depth`, the " "edge map or depth map; for `colorize`, any picture (it is made grey first).", ), InputParam( "task", type_hint=str, default="watercolor", description=f"The image-to-image task: one of {', '.join(I2I_TASKS)}.", ), InputParam( "prompt", type_hint=str | list, description="For `hed` and `depth`: a caption of the wanted image. The other tasks ignore it.", ), InputParam( "instruction_wording", type_hint=int, default=0, description="For `hed`, `depth` and `colorize`: which of the three trained wordings to use (0-2).", ), ]
@property def intermediate_outputs(self) -> list[OutputParam]: return [ OutputParam( "input_ids", type_hint=torch.Tensor, description="Request token ids `[B, L]`, left padded, with one image token per visual token.", ), OutputParam("attention_mask", type_hint=torch.Tensor, description="Padding mask of the request ids."), OutputParam("position_ids", type_hint=torch.Tensor, description="Rotary positions `[3, B, L]`."), OutputParam("pixel_values", type_hint=torch.Tensor, description="Sources `[B, 512, 512, 3]`, uint8."), OutputParam("decoder_texts", type_hint=list, description="The texts the image decoder reads."), OutputParam("decoder_task_ids", type_hint=torch.Tensor, description="The source decoder's task ids."), ]
@torch.no_grad() def __call__(self, components, state: PipelineState) -> PipelineState: block_state = self.get_block_state(state) task = block_state.task if task not in I2I_TASKS: raise ValueError(f"Unknown task {task!r}; choose one of {', '.join(I2I_TASKS)}.") images = [load_square(image) for image in as_list(block_state.image)] if task == "colorize": images = [to_gray(image) for image in images] captions = as_list(block_state.prompt, len(images)) or [""] * len(images) if len(captions) != len(images): raise ValueError(f"{len(images)} images but {len(captions)} prompts.") if task in ("hed", "depth") and not any(captions): raise ValueError(f"The `{task}` task needs a `prompt`: a caption of the wanted image.") texts = [i2i_texts(task, caption, block_state.instruction_wording) for caption in captions]
visual = components.transformer.visual.config cell = visual.patch_size * visual.spatial_merge_size instructions = [encode_instruction(components.tokenizer, instruction) for instruction, _ in texts] block_state.input_ids, block_state.attention_mask, block_state.position_ids = image_requests( components.tokenizer, instructions, (IMAGE_SIZE // cell, IMAGE_SIZE // cell), components.transformer.config.image_token_id, ) block_state.pixel_values = torch.from_numpy(np.stack(images)) block_state.decoder_texts = [decoder_text for _, decoder_text in texts] block_state.decoder_task_ids = torch.tensor([DECODER_TASK_ID[task]] * len(images), dtype=torch.long) self.set_block_state(state, block_state) return components, state
class JeverationDenseInputStep(ModularPipelineBlocks): model_name = "jeveration"
@property def description(self) -> str: return ( "Step that prepares the dense prediction requests: every picture resized to the dense input size, once per " "task, followed by the task's trained instruction." )
@property def expected_components(self) -> list[ComponentSpec]: return [transformer_spec(), tokenizer_spec()]
@property def inputs(self) -> list[InputParam]: return [ InputParam( "image", required=True, type_hint=PIL.Image.Image, description="The picture, or a list of pictures of one size: a PIL image, path or URL.", ), InputParam( "dense_tasks", required=True, type_hint=list, description=f"The predictions to make: any of {', '.join(DENSE_TASKS)}.", ), ]
@property def intermediate_outputs(self) -> list[OutputParam]: return [ OutputParam( "input_ids", type_hint=torch.Tensor, description="Request token ids `[rows, L]`, left padded, with one image token per visual token.", ), OutputParam("attention_mask", type_hint=torch.Tensor, description="Padding mask of the request ids."), OutputParam("position_ids", type_hint=torch.Tensor, description="Rotary positions `[3, rows, L]`."), OutputParam( "pixel_values", type_hint=torch.Tensor, description="The resized pictures `[rows, H, W, 3]`, uint8." ), OutputParam( "dense_rows", type_hint=list, description="The task of each request row: the tasks in order, one row per picture each.", ), OutputParam("pictures", type_hint=np.ndarray, description="The pictures `[B, H, W, 3]`, uint8."), ]
@torch.no_grad() def __call__(self, components, state: PipelineState) -> PipelineState: block_state = self.get_block_state(state) tasks = list(dict.fromkeys(as_list(block_state.dense_tasks))) unknown = [task for task in tasks if task not in DENSE_TASKS] if unknown: raise ValueError(f"Unknown dense tasks {unknown}; choose from {', '.join(DENSE_TASKS)}.") pictures = np.stack([np.asarray(load_image(image), dtype=np.uint8) for image in as_list(block_state.image)]) transformer = components.transformer input_size = tuple(transformer.config.dense_input_size) # Resized on the transformer's device, as the reference does. resized = torch.from_numpy(pictures).to(get_module_execution_device(transformer)) resized = F.interpolate(resized.permute(0, 3, 1, 2).float(), size=input_size, mode="bilinear") resized = resized.round().clamp(0, 255).to(torch.uint8).permute(0, 2, 3, 1).contiguous() rows = [task for task in tasks for _ in range(len(pictures))] cell = transformer.visual.config.patch_size * transformer.visual.config.spatial_merge_size instructions = [encode_instruction(components.tokenizer, DENSE_INSTRUCTIONS[task], cut=False) for task in rows] block_state.input_ids, block_state.attention_mask, block_state.position_ids = image_requests( components.tokenizer, instructions, (input_size[0] // cell, input_size[1] // cell), transformer.config.image_token_id, ) block_state.pixel_values = resized.repeat(len(tasks), 1, 1, 1) block_state.dense_rows = rows block_state.pictures = pictures self.set_block_state(state, block_state) return components, state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205# Copyright 2026 The HuggingFace Team, The Jeveration Authors and Bytedance Ltd. and/or its affiliates.# All rights reserved.## Licensed under the Apache License, Version 2.0. See the LICENSE and NOTICE files in this repository.## Adapted from TA-TiTok's text-aware decoder (https://github.com/bytedance/1d-tokenizer, Apache-2.0,# modeling/modules/blocks.py) and Jeveration's source decoder (https://github.com/Carol-lyh/Jeveration, Apache-2.0,# jeveration/tokenizer.py), with the same computations. Each layer's packed attention projections are split into# `attn.to_q`, `to_k`, `to_v` and `to_out.0`, and short module names are spelled out (see `DECODER_RENAMES` in# convert_jeveration_to_diffusers.py).
from collections import OrderedDict
import torchimport torch.nn as nn
from diffusers import ModelMixinfrom diffusers.configuration_utils import ConfigMixin, register_to_configfrom diffusers.models.attention import AttentionMixin, AttentionModuleMixinfrom diffusers.models.attention_dispatch import dispatch_attention_fn
class JeverationDecoderAttnProcessor: """Unmasked self-attention over all positions."""
_attention_backend = None _parallel_config = None
def __call__(self, attn, hidden_states): query = attn.to_q(hidden_states).unflatten(-1, (attn.heads, -1)) key = attn.to_k(hidden_states).unflatten(-1, (attn.heads, -1)) value = attn.to_v(hidden_states).unflatten(-1, (attn.heads, -1)) hidden_states = dispatch_attention_fn( query, key, value, backend=self._attention_backend, parallel_config=self._parallel_config ) return attn.to_out[0](hidden_states.flatten(2, 3).to(query.dtype))
class JeverationDecoderAttention(nn.Module, AttentionModuleMixin): _default_processor_cls = JeverationDecoderAttnProcessor _available_processors = [JeverationDecoderAttnProcessor]
def __init__(self, dim, heads): super().__init__() self.heads = heads self.to_q = nn.Linear(dim, dim) self.to_k = nn.Linear(dim, dim) self.to_v = nn.Linear(dim, dim) self.to_out = nn.ModuleList([nn.Linear(dim, dim), nn.Dropout(0.0)]) self.set_processor(JeverationDecoderAttnProcessor())
def forward(self, hidden_states): return self.processor(self, hidden_states)
class ResidualAttentionBlock(nn.Module): def __init__(self, width, heads, mlp_ratio=4.0): super().__init__() self.norm1 = nn.LayerNorm(width) self.attn = JeverationDecoderAttention(width, heads) self.norm2 = nn.LayerNorm(width) mlp_width = int(width * mlp_ratio) self.mlp = nn.Sequential( OrderedDict( [("fc1", nn.Linear(width, mlp_width)), ("gelu", nn.GELU()), ("fc2", nn.Linear(mlp_width, width))] ) )
def forward(self, hidden_states): hidden_states = hidden_states + self.attn(self.norm1(hidden_states)) return hidden_states + self.mlp(self.norm2(hidden_states))
class SourceGate(nn.Module): """Blends the source picture's features into the image patches after a decoder layer."""
def __init__(self, width): super().__init__() self.patch_gate = nn.Linear(width, 1) self.source_gate = nn.Linear(width, 1) self.proj = nn.Linear(width, width)
def forward(self, previous, patches, source): patch_weight = torch.sigmoid(self.patch_gate(previous)) source_weight = torch.sigmoid(self.source_gate(source)) return patches * (1 - patch_weight) + source_weight * self.proj(source)
class JeverationImageDecoder(ModelMixin, ConfigMixin, AttentionMixin): """TA-TiTok's text-aware decoder at 512 px: 128 codes and the CLIP text tower's per-token output -> RGB.
With `source_branch`, a gated branch also reads the source image (image-to-image): every `gate_every` layers, the patch tokens are partly replaced by features of the source image and its task embedding. The tokenizer's codebook is stored here, so the decoder turns code indices into pixels on its own. """
# The code embeddings are looked up in float32, as in the reference. _keep_in_fp32_modules = ["codebook"]
@register_to_config def __init__( self, image_size: int = 512, patch_size: int = 16, width: int = 1024, num_layers: int = 24, num_heads: int = 16, num_latent_tokens: int = 128, token_size: int = 64, codebook_size: int = 8192, text_context_length: int = 77, text_embed_dim: int = 768, source_branch: bool = False, num_tasks: int = 4, gate_every: int = 4, ): super().__init__() self.grid_size = image_size // patch_size scale = width**-0.5 self.register_buffer("codebook", torch.zeros(codebook_size, token_size)) self.decoder_embed = nn.Linear(token_size, width) self.class_embedding = nn.Parameter(scale * torch.randn(1, width)) self.positional_embedding = nn.Parameter(scale * torch.randn(self.grid_size**2 + 1, width)) self.mask_token = nn.Parameter(scale * torch.randn(1, 1, width)) self.latent_token_positional_embedding = nn.Parameter(scale * torch.randn(num_latent_tokens, width)) self.norm_in = nn.LayerNorm(width) self.transformer = nn.ModuleList([ResidualAttentionBlock(width, num_heads) for _ in range(num_layers)]) self.norm_out = nn.LayerNorm(width) self.ffn = nn.Sequential(nn.Conv2d(width, patch_size * patch_size * 3, 1)) self.conv_out = nn.Conv2d(3, 3, 3, padding=1) self.text_guidance_proj = nn.Linear(text_embed_dim, width) self.text_guidance_positional_embedding = nn.Parameter(scale * torch.randn(text_context_length, width)) if source_branch: self.cond_in = nn.Sequential( nn.Conv2d(3, 64, 3, 2, 1), nn.GELU(), nn.Conv2d(64, 128, 3, 2, 1), nn.GELU(), nn.Conv2d(128, 256, 3, 2, 1), nn.GELU(), nn.Conv2d(256, width, 2, 2), ) self.cond_task = nn.Embedding(num_tasks + 1, width) self.cond_gates = nn.ModuleList( [SourceGate(width) for _ in range(len(range(gate_every - 1, num_layers, gate_every)))] )
def to_pixels(self, patches): """[B, patch * patch * 3, grid, grid] -> [B, 3, grid * patch, grid * patch], the patch layout of the trained decoder.""" batch_size, _, grid_height, grid_width = patches.shape patch = self.config.patch_size patches = patches.view(batch_size, patch, patch, 3, grid_height, grid_width).permute(0, 3, 4, 1, 5, 2) return patches.reshape(batch_size, 3, grid_height * patch, grid_width * patch)
def forward(self, codes, text_guidance, source=None, task=None): """ Args: codes (`torch.Tensor`): The sampled codebook indices `[B, N]` (int64). text_guidance (`torch.Tensor`): The CLIP text features `[B, 77, 768]`. source (`torch.Tensor`, *optional*): The source images `[B, 3, 512, 512]` in [0, 1], for the source branch only. task (`torch.Tensor`, *optional*): The task ids `[B]` (> 0), given together with `source`.
Returns: `torch.Tensor`: the images `[B, 3, 512, 512]`, not clamped. """ if (source is None) != (task is None): raise ValueError("Give both `source` and `task`, or neither.") if source is not None and not self.config.source_branch: raise ValueError("This decoder has no source branch; use the source image decoder for image-to-image.") dtype = self.dtype hidden_states = self.decoder_embed(self.codebook[codes].to(dtype)) batch_size, seq_len = hidden_states.shape[:2] num_patches = self.grid_size**2 mask_tokens = self.mask_token.repeat(batch_size, num_patches, 1).to(hidden_states.dtype) if source is not None: source_features = self.cond_in(source.to(dtype).contiguous()).flatten(2).transpose(1, 2) source_features = source_features + self.cond_task(task).unsqueeze(1) class_token = self.class_embedding.unsqueeze(0).expand(batch_size, -1, -1).to(mask_tokens.dtype) mask_tokens = torch.cat([class_token, mask_tokens], dim=1) + self.positional_embedding.to(mask_tokens.dtype) hidden_states = hidden_states + self.latent_token_positional_embedding[:seq_len] hidden_states = torch.cat([mask_tokens, hidden_states], dim=1) text = self.text_guidance_proj(text_guidance.to(dtype)) + self.text_guidance_positional_embedding hidden_states = self.norm_in(torch.cat([hidden_states, text], dim=1)) # Position 0 is the class token, then come the image patches. patch_positions = slice(1, 1 + num_patches) gate_index = 0 for layer_index, layer in enumerate(self.transformer): previous = hidden_states hidden_states = layer(hidden_states) if source is not None and (layer_index + 1) % self.config.gate_every == 0: patches = self.cond_gates[gate_index]( previous[:, patch_positions], hidden_states[:, patch_positions], source_features ) gate_index += 1 hidden_states = torch.cat( [hidden_states[:, :1], patches.to(hidden_states.dtype), hidden_states[:, 1 + num_patches :]], 1 ) hidden_states = self.norm_out(hidden_states[:, patch_positions]) hidden_states = hidden_states.permute(0, 2, 1).reshape(batch_size, -1, self.grid_size, self.grid_size) return self.conv_out(self.to_pixels(self.ffn(hidden_states)))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091# Copyright 2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0. See the LICENSE file in this repository.
from diffusers.modular_pipelines import AutoPipelineBlocks, SequentialPipelineBlocksfrom diffusers.modular_pipelines.modular_pipeline_utils import InsertableDict, OutputParam
# The remote-code loader only copies modules the entry module imports, so every module of this repository is named# here, including the ones only imported by others.from .components import JEVERATION_WEIGHTS_REPO # noqa: F401from .decide import JeverationDecideStepfrom .decoders import JeverationDecodeStep, JeverationDensePostprocessStep, JeverationSourceDecodeStepfrom .dense import JeverationDensePredictStepfrom .encoders import JeverationDenseInputStep, JeverationImageInputStep, JeverationTextInputStepfrom .image_decoder_jeveration import JeverationImageDecoder # noqa: F401from .prompts_jeveration import NYU13 # noqa: F401from .transformer_jeveration import JeverationTransformer # noqa: F401
class JeverationText2ImageBlocks(SequentialPipelineBlocks): model_name = "jeveration" block_classes = [JeverationTextInputStep(), JeverationDecideStep(), JeverationDecodeStep()] block_names = ["text_input", "decide", "decode"]
@property def description(self) -> str: return "Text-to-image: one forward pass decides the 128 codes of a 512 x 512 image, then the decoder draws it."
@property def outputs(self): return [OutputParam("images", description="The generated images.")]
class JeverationImage2ImageBlocks(SequentialPipelineBlocks): model_name = "jeveration" block_classes = [JeverationImageInputStep(), JeverationDecideStep(), JeverationSourceDecodeStep()] block_names = ["image_input", "decide", "decode"]
@property def description(self) -> str: return ( "Image-to-image with one of the six trained tasks: edge map or depth map to image (`hed`, `depth`), " "`colorize`, or the `anime`, `ghibli` and `watercolor` styles." )
@property def outputs(self): return [OutputParam("images", description="The generated images.")]
class JeverationDenseBlocks(SequentialPipelineBlocks): model_name = "jeveration" block_classes = [JeverationDenseInputStep(), JeverationDensePredictStep(), JeverationDensePostprocessStep()] block_names = ["dense_input", "predict", "postprocess"]
@property def description(self) -> str: return "Dense prediction: indoor segmentation, depth and surface normals of a picture."
@property def outputs(self): return [ OutputParam("predictions", description="Task -> the predicted maps."), OutputParam("prediction_images", description="Task -> pictures of the predictions."), ]
JeverationBlocksDict = InsertableDict( [ ("dense", JeverationDenseBlocks()), ("image2image", JeverationImage2ImageBlocks()), ("text2image", JeverationText2ImageBlocks()), ])
class JeverationBlocks(AutoPipelineBlocks): """Jeveration: text-to-image, image-to-image and dense prediction, each in one forward pass of one model."""
model_name = "jeveration" _requirements = {"diffusers": ">=0.41.0", "transformers": ">=5.14.0", "ftfy": ">=6.0"} block_classes = list(JeverationBlocksDict.values()) block_names = list(JeverationBlocksDict.keys()) block_trigger_inputs = ["dense_tasks", "image", None]
@property def description(self) -> str: return ( "Jeveration, a Qwen3.5-4B fine-tuned to answer in one forward pass. Pass `prompt` for " "text-to-image, `image` (+ `task`) for image-to-image, `image` + `dense_tasks` for dense prediction." )123456789101112{ "_class_name": "JeverationBlocks", "_diffusers_version": "0.44.0.dev0", "auto_map": { "ModularPipelineBlocks": "modular_blocks_jeveration.JeverationBlocks" }, "requirements": { "diffusers": ">=0.41.0", "ftfy": ">=6.0", "transformers": ">=5.14.0" }}1234{ "_class_name": "ModularPipeline", "_blocks_class_name": "JeverationBlocks"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245# Copyright 2026 The HuggingFace Team and The Jeveration Authors. All rights reserved.## Licensed under the Apache License, Version 2.0. See the LICENSE and NOTICE files in this repository.## Adapted from the Jeveration code (https://github.com/Carol-lyh/Jeveration, Apache-2.0): jeveration/config.py,# prompts.py, pipeline.py, images.py and dense.py. The instructions are the trained ones, word for word.
import html
import ftfyimport numpy as npimport PIL.Imageimport torch
from diffusers.utils import load_image
IMAGE_SIZE = 512MAX_PROMPT_TOKENS = 128CLIP_CONTEXT = 77
T2I_TEMPLATE = "Generate an image: {prompt}"# Image-to-image: three trained wordings per task, the first is the default. {cap} is a caption of the wanted image.I2I_INSTRUCTIONS = { "hed": ( "Generate an image that follows this soft edge map. {cap}", "Render a picture with the structure of these soft edges. {cap}", "Create an image whose contours match this HED edge map. {cap}", ), "depth": ( "Generate an image with this depth map. {cap}", "Render a picture whose depth layout matches this depth map. {cap}", "Create an image that follows this depth map (bright is near). {cap}", ), "colorize": ( "Colorize this black-and-white photo.", "Add natural colors to this grayscale image.", "Turn this grayscale picture into a color image.", ),}STYLE_PREFIX = "Edit the image: "STYLE_INSTRUCTIONS = { "anime": "Convert this image into a clean modern anime illustration, keep the same composition.", "ghibli": "Transform this photo into a Studio Ghibli style anime illustration, keep the same composition and " "subjects.", "watercolor": "Repaint this entire image as a loose watercolor painting on paper: soft washes, bleeding edges, " "visible paper texture, light pencil lines. Keep the same composition, people and objects in the same places.",}I2I_TASKS = tuple(I2I_INSTRUCTIONS) + tuple(STYLE_INSTRUCTIONS)DECODER_TASK_ID = {"hed": 1, "depth": 2, "colorize": 3, "anime": 4, "ghibli": 4, "watercolor": 4}
NYU13 = ( "bed", "books", "ceiling", "chair", "floor", "furniture", "objects", "picture", "sofa", "table", "tv", "wall", "window",)DENSE_INSTRUCTIONS = { "seg": "Segment the image: give every pixel one of these classes: " + ", ".join(NYU13) + ".", "depth": "Estimate the depth of every pixel of the image, in meters.", "normal": "Estimate the surface normal of every pixel of the image.",}DENSE_TASKS = tuple(DENSE_INSTRUCTIONS)
IMAGE_PAD = "<|image_pad|>"_MARKER = "\u0000PROMPT\u0000"
def _ids(tokenizer, text): return [int(token) for token in tokenizer(text, add_special_tokens=False)["input_ids"]]
def text_chat_pieces(tokenizer): """Token ids before and after the prompt in the chat format of a text-to-image request.""" text = tokenizer.apply_chat_template( [{"role": "user", "content": T2I_TEMPLATE.format(prompt=_MARKER)}], tokenize=False, add_generation_prompt=True, enable_thinking=False, ) head, tail = text.split(_MARKER) return _ids(tokenizer, head), _ids(tokenizer, tail)
def image_chat_pieces(tokenizer): """Token ids of the chat format around an image and an instruction: (head, mid, tail).""" text = tokenizer.apply_chat_template( [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": _MARKER}]}], tokenize=False, add_generation_prompt=True, enable_thinking=False, ) if text.count(IMAGE_PAD) != 1 or text.count(_MARKER) != 1: raise ValueError(f"Unexpected chat template: {text!r}") head, rest = text.split(IMAGE_PAD) mid, tail = rest.split(_MARKER) return _ids(tokenizer, head), _ids(tokenizer, mid), _ids(tokenizer, tail)
def encode_text_prompts(tokenizer, prompts): """Text-to-image prompts -> (ids [B, L], mask [B, L]), left padded; each prompt is cut to 128 tokens.""" head, tail = text_chat_pieces(tokenizer) rows = [head + _ids(tokenizer, prompt)[:MAX_PROMPT_TOKENS] + tail for prompt in prompts] length = max(len(row) for row in rows) ids = torch.full((len(rows), length), tokenizer.pad_token_id, dtype=torch.long) mask = torch.zeros((len(rows), length), dtype=torch.long) for index, row in enumerate(rows): ids[index, length - len(row) :] = torch.tensor(row, dtype=torch.long) mask[index, length - len(row) :] = 1 return ids, mask
def encode_instruction(tokenizer, instruction, cut=True): ids = _ids(tokenizer, instruction) return ids[:MAX_PROMPT_TOKENS] if cut else ids
def image_requests(tokenizer, instructions, grid, image_token_id): """Requests with an image -> (input_ids [B, L], attention_mask [B, L], position_ids [3, B, L]), left padded: [head] [one image token per visual token] [mid] [instruction] [tail]. The visual tokens take the rotary positions (start, start + row, start + column) after the head tokens, and the text after them continues from start + max(grid_height, grid_width).""" head, mid, tail = image_chat_pieces(tokenizer) grid_height, grid_width = grid start = len(head) image_rows = torch.arange(grid_height).repeat_interleave(grid_width) image_columns = torch.arange(grid_width).repeat(grid_height) image_positions = torch.stack([torch.full_like(image_rows, start), start + image_rows, start + image_columns]) text_before = torch.arange(start).view(1, -1).expand(3, -1) rows, positions = [], [] for instruction in instructions: rows.append(head + [image_token_id] * (grid_height * grid_width) + mid + instruction + tail) text_after = start + max(grid_height, grid_width) + torch.arange(len(mid) + len(instruction) + len(tail)) positions.append(torch.cat([text_before, image_positions, text_after.view(1, -1).expand(3, -1)], 1)) length = max(len(row) for row in rows) ids = torch.full((len(rows), length), tokenizer.pad_token_id, dtype=torch.long) mask = torch.zeros((len(rows), length), dtype=torch.long) position_ids = torch.zeros((3, len(rows), length), dtype=torch.long) for index, row in enumerate(rows): ids[index, length - len(row) :] = torch.tensor(row, dtype=torch.long) mask[index, length - len(row) :] = 1 position_ids[:, index, length - len(row) :] = positions[index] return ids, mask, position_ids
def i2i_texts(task, caption="", wording=0): """An image-to-image request -> (instruction the transformer reads, text the decoder reads).""" if task in STYLE_INSTRUCTIONS: text = STYLE_INSTRUCTIONS[task] return STYLE_PREFIX + text, text instruction = I2I_INSTRUCTIONS[task][wording] if "{cap}" in instruction: return instruction.replace("{cap}", caption), caption return instruction, instruction
def clip_clean(text): """open_clip's text cleaning before tokenization: ftfy's fixes and HTML entities unescaped.""" text = ftfy.fix_text(text) return html.unescape(html.unescape(text)).strip()
def clip_input_ids(clip_tokenizer, texts): """Texts -> [B, 77] ids as open_clip makes them: start, tokens, end, cut to 77 with the end token last, padded with 0.""" rows = [] for text in texts: ids = [clip_tokenizer.bos_token_id] + _ids(clip_tokenizer, clip_clean(text)) + [clip_tokenizer.eos_token_id] if len(ids) > CLIP_CONTEXT: ids = ids[:CLIP_CONTEXT] ids[-1] = clip_tokenizer.eos_token_id rows.append(ids + [0] * (CLIP_CONTEXT - len(ids))) return torch.tensor(rows, dtype=torch.long)
def load_square(image, size=IMAGE_SIZE): """An image (PIL, path or URL) -> uint8 [size, size, 3]: shorter side to `size` (bicubic), centre crop.""" image = load_image(image) width, height = image.size if (width, height) != (size, size): scale = size / min(width, height) image = image.resize((max(size, round(width * scale)), max(size, round(height * scale))), PIL.Image.BICUBIC) left, top = (image.size[0] - size) // 2, (image.size[1] - size) // 2 image = image.crop((left, top, left + size, top + size)) return np.asarray(image, dtype=np.uint8)
def to_gray(image): """uint8 [H, W, 3] -> three equal channels of luma (ITU-R BT.601), the colorization task's input.""" luma = 0.299 * image[..., 0] + 0.587 * image[..., 1] + 0.114 * image[..., 2] luma = luma.round().clip(0, 255).astype(np.uint8) return np.repeat(luma[..., None], 3, axis=2)
# Colours of the dense prediction pictures, as in the paper's figures.PALETTE = np.array( [ [230, 159, 0], [204, 121, 167], [240, 228, 186], [213, 94, 0], [166, 118, 82], [86, 180, 233], [0, 158, 115], [240, 200, 60], [180, 70, 110], [120, 90, 200], [40, 40, 40], [200, 205, 215], [110, 200, 230], ], dtype=np.uint8,)DEPTH_RAMP = np.array([[252, 253, 191], [252, 137, 97], [183, 55, 121], [81, 18, 124], [0, 0, 4]], dtype=np.float32)
def seg_view(seg, picture=None): """Class indices [H, W] -> uint8 [H, W, 3]; the picture shows through at 15 % when given.""" out = PALETTE[seg].astype(np.float32) if picture is not None: out = 0.85 * out + 0.15 * picture return out.astype(np.uint8)
def depth_view(depth): """Depth [H, W] -> uint8 [H, W, 3]: nearer is brighter, over the picture's 2-98 % range.""" low, high = np.percentile(depth, 2), np.percentile(depth, 98) ramp_position = np.clip((depth - low) / max(float(high - low), 1e-3), 0, 1) * (len(DEPTH_RAMP) - 1) lower = np.minimum(ramp_position.astype(int), len(DEPTH_RAMP) - 2) fraction = (ramp_position - lower)[..., None] return (DEPTH_RAMP[lower] * (1 - fraction) + DEPTH_RAMP[lower + 1] * fraction).astype(np.uint8)
def normal_view(normal): """Unit normals [H, W, 3] -> uint8 [H, W, 3]: (normal + 1) / 2 as RGB.""" return ((np.clip(normal, -1, 1) + 1) * 127.5).astype(np.uint8)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412# Copyright 2026 The HuggingFace Team and The Jeveration Authors. All rights reserved.## Licensed under the Apache License, Version 2.0. See the LICENSE and NOTICE files in this repository.## Adapted from the Jeveration code (https://github.com/Carol-lyh/Jeveration, Apache-2.0): jeveration/model.py,# backbone.py, heads.py, random_state.py, prompts.py and dense.py, with the same computations. The image head's packed# attention projections are split into `attn.to_q`, `to_k`, `to_v` and `to_out.0`, and short module names are spelled# out (see `TRANSFORMER_RENAMES` in convert_jeveration_to_diffusers.py).
import mathfrom dataclasses import dataclass
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom transformers.masking_utils import create_causal_mask, create_recurrent_attention_maskfrom transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig, Qwen3_5VisionConfigfrom transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5TextModel, Qwen3_5VisionModel
from diffusers import ModelMixinfrom diffusers.configuration_utils import ConfigMixin, register_to_configfrom diffusers.models.attention import AttentionMixin, AttentionModuleMixinfrom diffusers.models.attention_dispatch import dispatch_attention_fnfrom diffusers.utils import BaseOutput
# Output channels of the dense heads: 13 NYUv2 classes, log-depth, surface normal.DENSE_CHANNELS = {"seg": 13, "depth": 1, "normal": 3}
def sinusoid(timesteps, dim): """[B] -> [B, dim]: sines and cosines of the timesteps at frequencies 1 ... 1/10000.""" half = dim // 2 freqs = torch.exp(-math.log(10000.0) * torch.arange(half, device=timesteps.device, dtype=torch.float32) / half) angles = timesteps.float()[:, None] * freqs[None] return torch.cat([torch.sin(angles), torch.cos(angles)], dim=1)
class TimeMLP(nn.Module): def __init__(self, hidden, dim): super().__init__() self.dim = dim self.net = nn.Sequential(nn.Linear(dim, hidden), nn.SiLU(), nn.Linear(hidden, hidden))
def forward(self, timesteps, dtype): return self.net(sinusoid(timesteps, self.dim).to(dtype))
class CondEmbed(nn.Module): """The masked share of the random state -> the image head's condition vector."""
def __init__(self, dim, freq): super().__init__() self.freq = freq self.net = nn.Sequential(nn.Linear(5 * freq, dim), nn.SiLU(), nn.Linear(dim, dim))
def forward(self, masked_share, dtype): zero, one = torch.zeros_like(masked_share), torch.ones_like(masked_share) features = [sinusoid(value, self.freq) for value in (masked_share, zero, zero, zero, one)] return self.net(torch.cat(features, 1).to(dtype))
class JeverationAttnProcessor: """Unmasked self-attention over all positions."""
_attention_backend = None _parallel_config = None
def __call__(self, attn, hidden_states): query = attn.to_q(hidden_states).unflatten(-1, (attn.heads, -1)) key = attn.to_k(hidden_states).unflatten(-1, (attn.heads, -1)) value = attn.to_v(hidden_states).unflatten(-1, (attn.heads, -1)) hidden_states = dispatch_attention_fn( query, key, value, backend=self._attention_backend, parallel_config=self._parallel_config ) return attn.to_out[0](hidden_states.flatten(2, 3).to(query.dtype))
class JeverationAttention(nn.Module, AttentionModuleMixin): _default_processor_cls = JeverationAttnProcessor _available_processors = [JeverationAttnProcessor]
def __init__(self, dim, heads): super().__init__() self.heads = heads self.to_q = nn.Linear(dim, dim) self.to_k = nn.Linear(dim, dim) self.to_v = nn.Linear(dim, dim) self.to_out = nn.ModuleList([nn.Linear(dim, dim), nn.Dropout(0.0)]) self.set_processor(JeverationAttnProcessor())
def forward(self, hidden_states): return self.processor(self, hidden_states)
class HeadBlock(nn.Module): """Bidirectional self-attention over the code positions and an MLP, both modulated by the condition."""
def __init__(self, width, heads, cond_dim, mlp_ratio=4): super().__init__() self.norm1 = nn.LayerNorm(width, elementwise_affine=False, eps=1e-6) self.attn = JeverationAttention(width, heads) self.norm2 = nn.LayerNorm(width, elementwise_affine=False, eps=1e-6) self.mlp = nn.Sequential( nn.Linear(width, mlp_ratio * width), nn.GELU(approximate="tanh"), nn.Linear(mlp_ratio * width, width) ) self.modulation = nn.Linear(cond_dim, 6 * width)
def forward(self, hidden_states, cond): shift_attn, scale_attn, gate_attn, shift_mlp, scale_mlp, gate_mlp = ( self.modulation(F.silu(cond)).unsqueeze(1).chunk(6, dim=-1) ) norm_hidden_states = self.norm1(hidden_states) * (1 + scale_attn) + shift_attn hidden_states = hidden_states + gate_attn * self.attn(norm_hidden_states) norm_hidden_states = self.norm2(hidden_states) * (1 + scale_mlp) + shift_mlp return hidden_states + gate_mlp * self.mlp(norm_hidden_states)
class ImageHead(nn.Module): """Decision tokens' final states + the random state + the condition -> (code-space projection, features)."""
def __init__(self, in_dim, code_dim, num_codes, width, depth, heads, cond_dim): super().__init__() self.hidden_proj = nn.Linear(in_dim, width) self.state_proj = nn.Linear(code_dim, width) self.pos_embed = nn.Parameter(torch.zeros(num_codes, width)) self.blocks = nn.ModuleList([HeadBlock(width, heads, cond_dim) for _ in range(depth)]) self.norm_out = nn.LayerNorm(width, elementwise_affine=False, eps=1e-6) self.norm_out_modulation = nn.Linear(cond_dim, 2 * width) self.proj_out = nn.Linear(width, code_dim)
def forward(self, decision_states, random_state, cond): hidden_states = self.hidden_proj(decision_states) + self.state_proj(random_state) + self.pos_embed for block in self.blocks: hidden_states = block(hidden_states, cond) shift, scale = self.norm_out_modulation(F.silu(cond)).unsqueeze(1).chunk(2, dim=-1) features = self.norm_out(hidden_states) * (1 + scale) + shift return self.proj_out(features), features
def patchify(images, vision_config): """uint8 [B, H, W, 3] -> the vision tower's input: patches [B * grid_height * grid_width, 3 * temporal_patch * patch * patch] in its merge order, and grid_thw [B, 3].""" patch, merge, temporal_patch = ( vision_config.patch_size, vision_config.spatial_merge_size, vision_config.temporal_patch_size, ) batch_size, height, width, _ = images.shape grid_height, grid_width = height // patch, width // patch patches = images.permute(0, 3, 1, 2).float().div(127.5).sub(1.0) patches = patches.reshape( batch_size, 3, grid_height // merge, merge, patch, grid_width // merge, merge, patch ).permute(0, 2, 5, 3, 6, 1, 4, 7) patches = ( patches.unsqueeze(6) .expand(-1, -1, -1, -1, -1, -1, temporal_patch, -1, -1) .reshape(batch_size * grid_height * grid_width, 3 * temporal_patch * patch * patch) ) grid_thw = torch.tensor([[1, grid_height, grid_width]] * batch_size, dtype=torch.long, device=images.device) return patches, grid_thw
def assemble(outputs, grid_height, grid_width, sub, channels): """The queries' outputs [N, grid_height * grid_width, window * window * channels] (window = 2 * sub) -> maps [N, channels, grid_height * sub, grid_width * sub], tent-weighted overlap-add.""" num_rows = outputs.shape[0] window = 2 * sub tent = 1.0 - (torch.arange(window, device=outputs.device, dtype=torch.float32) + 0.5 - sub).abs() / sub tent_2d = (tent[:, None] * tent[None, :]).flatten() num_cells = grid_height * grid_width columns = ( outputs.float() .view(num_rows, num_cells, window, window, channels) .permute(0, 4, 2, 3, 1) .reshape(num_rows, channels * window * window, num_cells) ) weights = tent_2d.repeat(channels).view(1, channels * window * window, 1) fold = { "output_size": (grid_height * sub, grid_width * sub), "kernel_size": window, "stride": sub, "padding": sub // 2, } return F.fold(columns * weights, **fold) / F.fold(weights.expand(1, -1, num_cells), **fold)
@dataclassclass JeverationTransformerOutput(BaseOutput): """ Args: logits (`torch.Tensor`, *optional*): Logits `[B, N, K]` of the code distribution, when the request carried a random state. dense_maps (`dict[str, torch.Tensor]`, *optional*): Task -> raw maps `[rows, C, grid_height * sub, grid_width * sub]` (logits, log-depth or normal) of that task's rows, in order, when the request carried dense tasks. """
logits: torch.Tensor | None = None dense_maps: dict[str, torch.Tensor] | None = None
class JeverationTransformer(ModelMixin, ConfigMixin, AttentionMixin): """Qwen3.5-4B (language model and vision tower) with Jeveration's adapters merged in, the decision-token inputs, the image head and the dense heads. One backbone pass decides all 128 image codes, or every dense prediction."""
# The random state is drawn in float32 from these, as in the reference. _keep_in_fp32_modules = ["mask_emb", "codebook_std"] _no_split_modules = ["Qwen3_5DecoderLayer", "Qwen3_5VisionBlock"] # Block-level group offload: also split the backbone and the vision tower into per-layer groups, and give the token # embedding its own group, as it is used before the backbone's forward. _group_offload_block_modules = ["language_model", "visual", "embed_tokens"]
@register_to_config def __init__( self, text_config: dict, vision_config: dict, image_token_id: int = 248056, num_codes: int = 128, code_dim: int = 64, codebook_size: int = 8192, head_width: int = 2048, head_depth: int = 8, head_heads: int = 16, cond_dim: int = 512, time_dim: int = 256, mask_prob: float = 0.6, state_noise: float = 0.1, dense_input_size: tuple = (576, 768), dense_sub: int = 8, dense_head_width: int = 1024, ): super().__init__() text = Qwen3_5TextConfig(**text_config) text._attn_implementation = "sdpa" vision = Qwen3_5VisionConfig(**vision_config) vision._attn_implementation = "sdpa" self.language_model = Qwen3_5TextModel(text) self.visual = Qwen3_5VisionModel(vision) hidden = text.hidden_size
self.state_proj = nn.Linear(code_dim, hidden) self.decision_pos_embed = nn.Parameter(torch.zeros(num_codes, hidden)) self.mask_emb = nn.Parameter(torch.zeros(code_dim)) # Two time embeddings of the decision tokens: the masked share, and a second time input that is 0 at inference. self.time_embed = TimeMLP(hidden, time_dim) self.interval_embed = TimeMLP(hidden, time_dim) self.cond_embed = CondEmbed(cond_dim, time_dim) self.head = ImageHead(hidden, code_dim, num_codes, head_width, head_depth, head_heads, cond_dim) self.code_head = nn.Linear(code_dim, codebook_size) self.code_wide = nn.Linear(head_width, codebook_size)
cell = vision.patch_size * vision.spatial_merge_size grid_height, grid_width = (side // cell for side in dense_input_size) window = 2 * dense_sub self.dense_queries = nn.Parameter(torch.zeros(grid_height * grid_width, hidden)) self.dense_vision_proj = nn.Linear(hidden, hidden) self.dense_heads = nn.ModuleDict( { task: nn.Sequential( nn.Linear(hidden, dense_head_width), nn.SiLU(), nn.Linear(dense_head_width, window * window * channels), ) for task, channels in DENSE_CHANNELS.items() } ) # The tokenizer's codebook, standardised with the code statistics: the random state is drawn from it. self.register_buffer("codebook_std", torch.zeros(codebook_size, code_dim))
def sample_random_state(self, batch, generator=None): """The shared random state -> (state [batch, N, C], masked share of each row [batch]). The draws are made on the generator's device, so a CUDA generator gives the reference's values and a CPU one works too.""" config = self.config num_codes, device = config.num_codes, self.codebook_std.device draw_device = generator.device if generator is not None else device masked = (torch.rand(batch, num_codes, generator=generator, device=draw_device) < config.mask_prob).to(device) codes = torch.randint(0, config.codebook_size, (batch, num_codes), generator=generator, device=draw_device).to( device ) state = torch.where( masked.unsqueeze(-1), self.mask_emb.view(1, 1, -1).float().expand(batch, num_codes, -1), self.codebook_std[codes], ) sigma = config.state_noise noise = torch.randn(state.shape, generator=generator, device=draw_device).to(device) state = math.sqrt(1 - sigma**2) * state + sigma * noise return state, masked.float().mean(1)
def forward( self, input_ids: torch.Tensor, attention_mask: torch.Tensor, position_ids: torch.Tensor | None = None, pixel_values: torch.Tensor | None = None, random_state: torch.Tensor | None = None, masked_share: torch.Tensor | None = None, dense_tasks: list[str] | None = None, return_dict: bool = True, ): """ One backbone pass over a request followed by either the 128 decision tokens (built from `random_state`) or the dense queries (one task per row, `dense_tasks`).
Args: input_ids (`torch.Tensor`): The request in the chat format `[B, L]`, left padded. An image request holds one `image_token_id` per visual token, in raster order. attention_mask (`torch.Tensor`): Padding mask `[B, L]`, 1 for real tokens. position_ids (`torch.Tensor`, *optional*): Rotary positions `[3, B, L]` (temporal, height, width) of an image request. Without them every axis counts 0, 1, 2, ... over the whole sequence, as for a text request. pixel_values (`torch.Tensor`, *optional*): The images of an image request, uint8 `[B, H, W, 3]` with sides multiple of 32. random_state (`torch.Tensor`, *optional*): The decision tokens' random state `[B, N, C]`, from `sample_random_state`. masked_share (`torch.Tensor`, *optional*): The masked share of each row of the random state `[B]`. dense_tasks (`list[str]`, *optional*): The dense task of each row (`seg`, `depth` or `normal`), instead of a random state. return_dict (`bool`, defaults to `True`): Whether to return a `JeverationTransformerOutput` instead of a tuple.
Returns: `JeverationTransformerOutput` or `tuple`: the code logits, or the dense maps per task. """ language_model = self.language_model dtype = self.dtype batch_size, prompt_length = input_ids.shape inputs_embeds = language_model.embed_tokens(input_ids) if pixel_values is not None: image_mask = input_ids == self.config.image_token_id patches, grid_thw = patchify(pixel_values, self.visual.config) image_embeds = self.visual(patches.to(dtype), grid_thw=grid_thw, return_dict=True) image_embeds = image_embeds.pooler_output.view(batch_size, -1, inputs_embeds.shape[-1]) inputs_embeds = inputs_embeds.masked_scatter(image_mask[..., None], image_embeds)
if dense_tasks is None: time_embeds = self.time_embed(masked_share, dtype) + self.interval_embed( torch.zeros_like(masked_share), dtype ) tail = self.state_proj(random_state.to(dtype)) + self.decision_pos_embed + time_embeds[:, None] else: tail = self.dense_queries.unsqueeze(0) + self.dense_vision_proj(image_embeds) num_tail = tail.shape[1] hidden_states = torch.cat([inputs_embeds, tail], 1) mask = torch.cat([attention_mask, attention_mask.new_ones(batch_size, num_tail)], 1) length = hidden_states.shape[1] text_positions = torch.arange(length, device=input_ids.device).view(1, -1).expand(batch_size, -1) if position_ids is None: rope_positions = text_positions.unsqueeze(0).expand(3, -1, -1) else: next_position = position_ids[:, :, -1].amax(0)[:, None] + 1 if dense_tasks is None: tail_positions = (next_position + torch.arange(num_tail, device=next_position.device)).expand( 3, -1, -1 ) else: image_rows = position_ids[1][image_mask].view(batch_size, -1) image_cols = position_ids[2][image_mask].view(batch_size, -1) tail_positions = torch.stack([next_position.expand(-1, num_tail), image_rows, image_cols]) rope_positions = torch.cat([position_ids, tail_positions], 2)
# The tail (decision tokens or dense queries) attends to itself in both directions in the full-attention # layers; everything else is causal. block_ids = torch.full((batch_size, length), -1, dtype=torch.long, device=input_ids.device) block_ids[:, prompt_length:] = 0 full_mask = create_causal_mask( config=language_model.config, inputs_embeds=hidden_states, attention_mask=mask, past_key_values=None, position_ids=text_positions, block_sequence_ids=block_ids, ) # A padding row attends to nothing; letting every position see itself leaves the real ones unchanged. full_mask = full_mask | torch.eye(length, dtype=torch.bool, device=full_mask.device) linear_mask = create_recurrent_attention_mask( config=language_model.config, inputs_embeds=hidden_states, attention_mask=mask ) hidden_states = language_model( inputs_embeds=hidden_states, attention_mask={"full_attention": full_mask, "linear_attention": linear_mask}, position_ids=torch.cat([text_positions[None], rope_positions], 0), use_cache=False, ).last_hidden_state hidden_states = hidden_states[:, -num_tail:]
logits, dense_maps = None, None if dense_tasks is None: proj, features = self.head(hidden_states, random_state.to(dtype), self.cond_embed(masked_share, dtype)) logits = self.code_head(proj) + self.code_wide(features) else: cell = self.visual.config.patch_size * self.visual.config.spatial_merge_size grid_height, grid_width = (pixel_values.shape[1] // cell, pixel_values.shape[2] // cell) dense_maps = {} for task in dict.fromkeys(dense_tasks): rows = [row for row, name in enumerate(dense_tasks) if name == task] dense_maps[task] = assemble( self.dense_heads[task](hidden_states[rows]), grid_height, grid_width, self.config.dense_sub, DENSE_CHANNELS[task], )
if not return_dict: return (logits, dense_maps) return JeverationTransformerOutput(logits=logits, dense_maps=dense_maps).gitignoreAdded+2
LICENSEAdded+202
NOTICEAdded+8
README.mdAdded+101
__init__.pyAdded
components.pyAdded+63
convert_jeveration_to_diffusers.pyAdded+258
decide.pyAdded+64
decoders.pyAdded+182
dense.pyAdded+71
encoders.pyAdded+247
image_decoder_jeveration.pyAdded+205
modular_blocks_jeveration.pyAdded+91
modular_config.jsonAdded+12
modular_model_index.jsonAdded+4
prompts_jeveration.pyAdded+245
transformer_jeveration.pyAdded+412