# 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 ] 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/ and source_image_decoder/ (the 512-px TA-TiTok decoders with the codebook), text_encoder/ (CLIP ViT-L/14-336's text tower as a transformers CLIPTextModel), tokenizer/ (Qwen3.5), clip_tokenizer/ and modular_model_index.json. Values are not changed apart from the merged adapters; packed attention projections are split into q, k and v, and the reference's short module names get descriptive ones (`TRANSFORMER_RENAMES`, `DECODER_RENAMES`). """ import argparse import json import re from pathlib import Path import torch from huggingface_hub import hf_hub_download, snapshot_download from safetensors import safe_open from transformers import AutoTokenizer, CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers.utils import logging from .components import JEVERATION_WEIGHTS_REPO from .image_decoder_jeveration import JeverationImageDecoder from .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 `` and `` and the output projection `` -> `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") write_index(output_dir) # Component -> (library, class) as the blocks load it; the blocks load the weights through components.py. INDEX_COMPONENTS = { "transformer": ("transformer_jeveration", "JeverationTransformer"), "image_decoder": ("image_decoder_jeveration", "JeverationImageDecoder"), "source_image_decoder": ("image_decoder_jeveration", "JeverationImageDecoder"), "text_encoder": ("transformers", "CLIPTextModel"), "tokenizer": ("transformers", "AutoTokenizer"), "clip_tokenizer": ("transformers", "CLIPTokenizer"), } def write_index(output_dir): """The root modular_model_index.json: the Hub counts a diffusers repo's downloads by this file.""" output_dir = Path(output_dir) version = json.loads((output_dir / "transformer" / "config.json").read_text())["_diffusers_version"] index = {"_class_name": "ModularPipeline", "_diffusers_version": version} for name, (library, cls) in INDEX_COMPONENTS.items(): index[name] = [library, cls, {"pretrained_model_name_or_path": JEVERATION_WEIGHTS_REPO, "subfolder": name}] (output_dir / "modular_model_index.json").write_text(json.dumps(index, indent=2) + "\n") 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()