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" # Download from https://huggingface.co/ByteDance-Seed/BAGEL-7B-MoT # LLM config preparing 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 preparing 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 loading vae_model, vae_config = load_ae(local_path=os.path.join(model_path, "ae.safetensors")) # Bagel config preparing 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 Preparing tokenizer = Qwen2Tokenizer.from_pretrained(model_path) tokenizer, new_token_ids, _ = add_special_tokens(tokenizer) # Image Transform Preparing vae_transform = ImageTransform(1024, 512, 16) vit_transform = ImageTransform(980, 224, 14) # ========= Step 1: 设备规划(仅 GPU,禁止 CPU/offload) ========= import os, torch from accelerate import infer_auto_device_map, load_checkpoint_and_dispatch from safetensors.torch import load_file as safe_load # 单/多卡最大显存设置(按需调整;确保足够避免 CPU 回退) max_mem_per_gpu = "40GiB" # A100 80GiB 可设更高,例如 "78GiB" 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"], ) # 禁止任何 'cpu' 或 'disk' 的落点 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。") # 将若干关键子模块强制放在同一张 GPU 上 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: # 取 embed_tokens 的设备作为锚点 anchor = device_map.get(same_device_modules[0]) if anchor is None: # 回退到 cuda:0 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) # ========= Step 2: 装载原始权重(不启用 offload) ========= # 说明:为了“杜绝 CPU/GPU 混用”,这里将 offload 相关选项全部关闭 # 注意:这要求你的显存设置足以容纳模型;否则请调大 max_mem_per_gpu 或减少 batch/分辨率 model = load_checkpoint_and_dispatch( model, checkpoint=os.path.join(model_path, "ema.safetensors"), device_map=device_map, dtype=torch.bfloat16, offload_buffers=False, # 禁止 offload force_hooks=True, ) model = model.eval() print("[Stage-1] 原始权重已加载到 CUDA。") # 若你在“构图阶段”添加了新特殊 token,通常需要在这里同步词表尺寸(如已做可忽略) # try: # model.language_model.resize_token_embeddings(len(tokenizer)) # except Exception as e: # print("resize_token_embeddings 跳过:", e) # ========= Step 3: 加载你训练后的权重,进行“就地覆盖” ========= 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) # 全在 CPU 上的原始张量容器,不会改变模型设备分配 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: # 保持与目标参数一致的 device & dtype 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) # ========= Step 4: 终检 - 确保没有参数/缓冲区落在 CPU ========= 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 = 'Click on the First image of "saffola classic masala oats,Click on the First image of "saffola classic masala oats' 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")