| import os |
| from copy import deepcopy |
| from typing import ( |
| Any, |
| AsyncIterable, |
| Callable, |
| Dict, |
| Generator, |
| List, |
| NamedTuple, |
| Optional, |
| Tuple, |
| Union, |
| ) |
| import requests |
| from io import BytesIO |
|
|
| from PIL import Image |
| import torch |
| from accelerate import infer_auto_device_map, load_checkpoint_and_dispatch, init_empty_weights |
|
|
| from data.transforms import ImageTransform |
| from data.data_utils import pil_img2rgb, add_special_tokens |
| from modeling.bagel import ( |
| BagelConfig, Bagel, Qwen2Config, Qwen2ForCausalLM, SiglipVisionConfig, SiglipVisionModel |
| ) |
| from modeling.qwen2 import Qwen2Tokenizer |
| from modeling.bagel.qwen2_navit import NaiveCache |
| from modeling.autoencoder import load_ae |
| from safetensors.torch import load_file |
|
|
|
|
|
|
|
|
|
|
| model_path = "/mnt/beegfs/Workspace/Models/BAGEL-7B-MoT" |
|
|
| |
| llm_config = Qwen2Config.from_json_file(os.path.join(model_path, "llm_config.json")) |
| llm_config.qk_norm = True |
| llm_config.tie_word_embeddings = False |
| llm_config.layer_module = "Qwen2MoTDecoderLayer" |
|
|
| |
| vit_config = SiglipVisionConfig.from_json_file(os.path.join(model_path, "vit_config.json")) |
| vit_config.rope = False |
| vit_config.num_hidden_layers = vit_config.num_hidden_layers - 1 |
|
|
| |
| vae_model, vae_config = load_ae(local_path=os.path.join(model_path, "ae.safetensors")) |
|
|
| |
| config = BagelConfig( |
| visual_gen=True, |
| visual_und=True, |
| llm_config=llm_config, |
| vit_config=vit_config, |
| vae_config=vae_config, |
| vit_max_num_patch_per_side=70, |
| connector_act='gelu_pytorch_tanh', |
| latent_patch_size=2, |
| max_latent_size=64, |
| ) |
|
|
| with init_empty_weights(): |
| language_model = Qwen2ForCausalLM(llm_config) |
| vit_model = SiglipVisionModel(vit_config) |
| model = Bagel(language_model, vit_model, config) |
| model.vit_model.vision_model.embeddings.convert_conv2d_to_linear(vit_config, meta=True) |
|
|
| |
| tokenizer = Qwen2Tokenizer.from_pretrained(model_path) |
| tokenizer, new_token_ids, _ = add_special_tokens(tokenizer) |
|
|
| |
| vae_transform = ImageTransform(1024, 512, 16) |
| vit_transform = ImageTransform(980, 224, 14) |
|
|
|
|
|
|
|
|
|
|
| |
| import os, torch |
| from accelerate import infer_auto_device_map, load_checkpoint_and_dispatch |
| from safetensors.torch import load_file as safe_load |
|
|
| |
| max_mem_per_gpu = "40GiB" |
|
|
| def build_cuda_only_device_map(model, same_device_modules): |
| assert torch.cuda.device_count() >= 1, "需要至少 1 张 CUDA GPU。" |
| cuda_count = torch.cuda.device_count() |
| max_memory = {i: max_mem_per_gpu for i in range(cuda_count)} |
|
|
| device_map = infer_auto_device_map( |
| model, |
| max_memory=max_memory, |
| no_split_module_classes=["Bagel", "Qwen2MoTDecoderLayer"], |
| ) |
|
|
| |
| bad_devices = {v for v in device_map.values() if isinstance(v, str) and v not in [f"cuda:{i}" for i in range(cuda_count)]} |
| if bad_devices: |
| raise RuntimeError(f"发现非 CUDA 设备分配 {bad_devices},请增大 max_mem_per_gpu 或减少模型容量以避免 CPU/offload。") |
|
|
| |
| if cuda_count == 1: |
| first_device = next(iter(device_map.values())) |
| first_device = first_device if isinstance(first_device, str) else f"cuda:{first_device['cuda_device']}" |
| for k in same_device_modules: |
| device_map[k] = first_device |
| else: |
| |
| anchor = device_map.get(same_device_modules[0]) |
| if anchor is None: |
| |
| anchor = "cuda:0" |
| for k in same_device_modules: |
| device_map[k] = anchor |
|
|
| return device_map |
|
|
| same_device_modules = [ |
| 'language_model.model.embed_tokens', |
| 'time_embedder', |
| 'latent_pos_embed', |
| 'vae2llm', |
| 'llm2vae', |
| 'connector', |
| 'vit_pos_embed' |
| ] |
|
|
| device_map = build_cuda_only_device_map(model, same_device_modules) |
| print("Device map (CUDA-only) built:", device_map) |
|
|
| |
| |
| |
| model = load_checkpoint_and_dispatch( |
| model, |
| checkpoint=os.path.join(model_path, "ema.safetensors"), |
| device_map=device_map, |
| dtype=torch.bfloat16, |
| offload_buffers=False, |
| force_hooks=True, |
| ) |
| model = model.eval() |
| print("[Stage-1] 原始权重已加载到 CUDA。") |
|
|
| |
| |
| |
| |
| |
|
|
| |
| finetuned_ckpt = "/mnt/beegfs/Workspace/ICLR_2026/Bagel-GUI/results/checkpoints/0064000/ema_bf16.safetensors" |
|
|
| def load_and_override(model, ckpt_path): |
| """ |
| 将 ckpt_path 中与当前模型 state_dict 同名且形状一致的权重,按位复制到现有参数上。 |
| 复制前将张量 to(param.device, dtype=param.dtype),以杜绝 CPU/GPU 混放或 dtype 不一致。 |
| """ |
| print(f"[Stage-2] 读取训练后权重:{ckpt_path}") |
| ft_state = safe_load(ckpt_path) |
| model_state = model.state_dict() |
|
|
| matched, skipped_shape, skipped_missing = 0, 0, 0 |
| with torch.no_grad(): |
| for k, v in ft_state.items(): |
| if k in model_state: |
| tgt = model_state[k] |
| if tgt.shape == v.shape: |
| |
| dev = tgt.device |
| dt = tgt.dtype |
| tgt.copy_(v.to(dev, dtype=dt)) |
| matched += 1 |
| else: |
| skipped_shape += 1 |
| else: |
| skipped_missing += 1 |
|
|
| print(f"[Stage-2] 覆盖完成:匹配 {matched} 个;形状不符跳过 {skipped_shape} 个;缺失键跳过 {skipped_missing} 个。") |
| return matched |
|
|
| _ = load_and_override(model, finetuned_ckpt) |
|
|
| |
| def assert_all_cuda(module): |
| bad = [] |
| for n, p in module.named_parameters(recurse=True): |
| if p.device.type != "cuda": |
| bad.append(("param", n, str(p.device))) |
| for n, b in module.named_buffers(recurse=True): |
| if b.device.type != "cuda": |
| bad.append(("buffer", n, str(b.device))) |
| if bad: |
| lines = "\n".join([f" - {t}\t{name}\t@{dev}" for (t, name, dev) in bad[:20]]) |
| raise RuntimeError(f"发现非 CUDA 张量(共{len(bad)}个,列出前20个):\n{lines}") |
| print("[Check] 所有参数与缓冲区均在 CUDA。") |
|
|
| assert_all_cuda(model) |
| print("Model ready ✓") |
|
|
|
|
|
|
|
|
|
|
|
|
| from inferencer import InterleaveInferencer |
|
|
| inferencer = InterleaveInferencer( |
| model=model, |
| vae_model=vae_model, |
| tokenizer=tokenizer, |
| vae_transform=vae_transform, |
| vit_transform=vit_transform, |
| new_token_ids=new_token_ids |
| ) |
|
|
| import random |
| import numpy as np |
|
|
| seed = 42 |
| random.seed(seed) |
| np.random.seed(seed) |
| torch.manual_seed(seed) |
| if torch.cuda.is_available(): |
| torch.cuda.manual_seed(seed) |
| torch.cuda.manual_seed_all(seed) |
| torch.backends.cudnn.deterministic = True |
| torch.backends.cudnn.benchmark = False |
|
|
|
|
|
|
| inference_hyper=dict( |
| cfg_text_scale=4.0, |
| cfg_img_scale=2.0, |
| cfg_interval=[0.0, 1.0], |
| timestep_shift=3.0, |
| num_timesteps=50, |
| cfg_renorm_min=0.0, |
| cfg_renorm_type="text_channel", |
| ) |
|
|
|
|
|
|
| image = Image.open('train_verify/5813_0.png') |
| |
| prompt = ' Swipe up on the screen. ' |
|
|
|
|
| |
| image.save("input_image.png") |
|
|
| print(prompt) |
| print('-'*10) |
|
|
| |
| output_dict = inferencer(image=image, text=prompt, **inference_hyper) |
|
|
| |
| out_img = output_dict['image'] |
| if isinstance(out_img, Image.Image): |
| out_img.save("output_image.png") |
| elif isinstance(out_img, torch.Tensor): |
| from torchvision.transforms.functional import to_pil_image |
| to_pil_image(out_img[0].cpu()).save("output_image.png") |
|
|
| print("保存完成:input_image.png, output_image.png") |
|
|