Wendy-Fly commited on
Commit
efc25a7
·
verified ·
1 Parent(s): 686e837

Upload bagel_inference.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. bagel_inference.py +272 -0
bagel_inference.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from copy import deepcopy
3
+ from typing import (
4
+ Any,
5
+ AsyncIterable,
6
+ Callable,
7
+ Dict,
8
+ Generator,
9
+ List,
10
+ NamedTuple,
11
+ Optional,
12
+ Tuple,
13
+ Union,
14
+ )
15
+ import requests
16
+ from io import BytesIO
17
+
18
+ from PIL import Image
19
+ import torch
20
+ from accelerate import infer_auto_device_map, load_checkpoint_and_dispatch, init_empty_weights
21
+
22
+ from data.transforms import ImageTransform
23
+ from data.data_utils import pil_img2rgb, add_special_tokens
24
+ from modeling.bagel import (
25
+ BagelConfig, Bagel, Qwen2Config, Qwen2ForCausalLM, SiglipVisionConfig, SiglipVisionModel
26
+ )
27
+ from modeling.qwen2 import Qwen2Tokenizer
28
+ from modeling.bagel.qwen2_navit import NaiveCache
29
+ from modeling.autoencoder import load_ae
30
+ from safetensors.torch import load_file
31
+
32
+
33
+
34
+
35
+
36
+ model_path = "/mnt/beegfs/Workspace/Models/BAGEL-7B-MoT" # Download from https://huggingface.co/ByteDance-Seed/BAGEL-7B-MoT
37
+
38
+ # LLM config preparing
39
+ llm_config = Qwen2Config.from_json_file(os.path.join(model_path, "llm_config.json"))
40
+ llm_config.qk_norm = True
41
+ llm_config.tie_word_embeddings = False
42
+ llm_config.layer_module = "Qwen2MoTDecoderLayer"
43
+
44
+ # ViT config preparing
45
+ vit_config = SiglipVisionConfig.from_json_file(os.path.join(model_path, "vit_config.json"))
46
+ vit_config.rope = False
47
+ vit_config.num_hidden_layers = vit_config.num_hidden_layers - 1
48
+
49
+ # VAE loading
50
+ vae_model, vae_config = load_ae(local_path=os.path.join(model_path, "ae.safetensors"))
51
+
52
+ # Bagel config preparing
53
+ config = BagelConfig(
54
+ visual_gen=True,
55
+ visual_und=True,
56
+ llm_config=llm_config,
57
+ vit_config=vit_config,
58
+ vae_config=vae_config,
59
+ vit_max_num_patch_per_side=70,
60
+ connector_act='gelu_pytorch_tanh',
61
+ latent_patch_size=2,
62
+ max_latent_size=64,
63
+ )
64
+
65
+ with init_empty_weights():
66
+ language_model = Qwen2ForCausalLM(llm_config)
67
+ vit_model = SiglipVisionModel(vit_config)
68
+ model = Bagel(language_model, vit_model, config)
69
+ model.vit_model.vision_model.embeddings.convert_conv2d_to_linear(vit_config, meta=True)
70
+
71
+ # Tokenizer Preparing
72
+ tokenizer = Qwen2Tokenizer.from_pretrained(model_path)
73
+ tokenizer, new_token_ids, _ = add_special_tokens(tokenizer)
74
+
75
+ # Image Transform Preparing
76
+ vae_transform = ImageTransform(1024, 512, 16)
77
+ vit_transform = ImageTransform(980, 224, 14)
78
+
79
+
80
+
81
+
82
+
83
+ # ========= Step 1: 设备规划(仅 GPU,禁止 CPU/offload) =========
84
+ import os, torch
85
+ from accelerate import infer_auto_device_map, load_checkpoint_and_dispatch
86
+ from safetensors.torch import load_file as safe_load
87
+
88
+ # 单/多卡最大显存设置(按需调整;确保足够避免 CPU 回退)
89
+ max_mem_per_gpu = "40GiB" # A100 80GiB 可设更高,例如 "78GiB"
90
+
91
+ def build_cuda_only_device_map(model, same_device_modules):
92
+ assert torch.cuda.device_count() >= 1, "需要至少 1 张 CUDA GPU。"
93
+ cuda_count = torch.cuda.device_count()
94
+ max_memory = {i: max_mem_per_gpu for i in range(cuda_count)}
95
+
96
+ device_map = infer_auto_device_map(
97
+ model,
98
+ max_memory=max_memory,
99
+ no_split_module_classes=["Bagel", "Qwen2MoTDecoderLayer"],
100
+ )
101
+
102
+ # 禁止任何 'cpu' 或 'disk' 的落点
103
+ 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)]}
104
+ if bad_devices:
105
+ raise RuntimeError(f"发现非 CUDA 设备分配 {bad_devices},请增大 max_mem_per_gpu 或减少模型容量以避免 CPU/offload。")
106
+
107
+ # 将若干关键子模块强制放在同一张 GPU 上
108
+ if cuda_count == 1:
109
+ first_device = next(iter(device_map.values()))
110
+ first_device = first_device if isinstance(first_device, str) else f"cuda:{first_device['cuda_device']}"
111
+ for k in same_device_modules:
112
+ device_map[k] = first_device
113
+ else:
114
+ # 取 embed_tokens 的设备作为锚点
115
+ anchor = device_map.get(same_device_modules[0])
116
+ if anchor is None:
117
+ # 回退到 cuda:0
118
+ anchor = "cuda:0"
119
+ for k in same_device_modules:
120
+ device_map[k] = anchor
121
+
122
+ return device_map
123
+
124
+ same_device_modules = [
125
+ 'language_model.model.embed_tokens',
126
+ 'time_embedder',
127
+ 'latent_pos_embed',
128
+ 'vae2llm',
129
+ 'llm2vae',
130
+ 'connector',
131
+ 'vit_pos_embed'
132
+ ]
133
+
134
+ device_map = build_cuda_only_device_map(model, same_device_modules)
135
+ print("Device map (CUDA-only) built:", device_map)
136
+
137
+ # ========= Step 2: 装载原始权重(不启用 offload) =========
138
+ # 说明:为了“杜绝 CPU/GPU 混用”,这里将 offload 相关选项全部关闭
139
+ # 注意:这要求你的显存设置足以容纳模型;否则请调大 max_mem_per_gpu 或减少 batch/分辨率
140
+ model = load_checkpoint_and_dispatch(
141
+ model,
142
+ checkpoint=os.path.join(model_path, "ema.safetensors"),
143
+ device_map=device_map,
144
+ dtype=torch.bfloat16,
145
+ offload_buffers=False, # 禁止 offload
146
+ force_hooks=True,
147
+ )
148
+ model = model.eval()
149
+ print("[Stage-1] 原始权重已加载到 CUDA。")
150
+
151
+ # 若你在“构图阶段”添加了新特殊 token,通常需要在这里同步词表尺寸(如已做可忽略)
152
+ # try:
153
+ # model.language_model.resize_token_embeddings(len(tokenizer))
154
+ # except Exception as e:
155
+ # print("resize_token_embeddings 跳过:", e)
156
+
157
+ # ========= Step 3: 加载你训练后的权重,进行“就地覆盖” =========
158
+ finetuned_ckpt = "/mnt/beegfs/Workspace/ICLR_2026/Bagel-GUI/results/checkpoints/0064000/ema_bf16.safetensors"
159
+
160
+ def load_and_override(model, ckpt_path):
161
+ """
162
+ 将 ckpt_path 中与当前模型 state_dict 同名且形状一致的权重,按位复制到现有参数上。
163
+ 复制前将张量 to(param.device, dtype=param.dtype),以杜绝 CPU/GPU 混放或 dtype 不一致。
164
+ """
165
+ print(f"[Stage-2] 读取训练后权重:{ckpt_path}")
166
+ ft_state = safe_load(ckpt_path) # 全在 CPU 上的原始张量容器,不会改变模型设备分配
167
+ model_state = model.state_dict()
168
+
169
+ matched, skipped_shape, skipped_missing = 0, 0, 0
170
+ with torch.no_grad():
171
+ for k, v in ft_state.items():
172
+ if k in model_state:
173
+ tgt = model_state[k]
174
+ if tgt.shape == v.shape:
175
+ # 保持与目标参数一致的 device & dtype
176
+ dev = tgt.device
177
+ dt = tgt.dtype
178
+ tgt.copy_(v.to(dev, dtype=dt))
179
+ matched += 1
180
+ else:
181
+ skipped_shape += 1
182
+ else:
183
+ skipped_missing += 1
184
+
185
+ print(f"[Stage-2] 覆盖完成:匹配 {matched} 个;形状不符跳过 {skipped_shape} 个;缺失键跳过 {skipped_missing} 个。")
186
+ return matched
187
+
188
+ _ = load_and_override(model, finetuned_ckpt)
189
+
190
+ # ========= Step 4: 终检 - 确保没有参数/缓冲区落在 CPU =========
191
+ def assert_all_cuda(module):
192
+ bad = []
193
+ for n, p in module.named_parameters(recurse=True):
194
+ if p.device.type != "cuda":
195
+ bad.append(("param", n, str(p.device)))
196
+ for n, b in module.named_buffers(recurse=True):
197
+ if b.device.type != "cuda":
198
+ bad.append(("buffer", n, str(b.device)))
199
+ if bad:
200
+ lines = "\n".join([f" - {t}\t{name}\t@{dev}" for (t, name, dev) in bad[:20]])
201
+ raise RuntimeError(f"发现非 CUDA 张量(共{len(bad)}个,列出前20个):\n{lines}")
202
+ print("[Check] 所有参数与缓冲区均在 CUDA。")
203
+
204
+ assert_all_cuda(model)
205
+ print("Model ready ✓")
206
+
207
+
208
+
209
+
210
+
211
+
212
+ from inferencer import InterleaveInferencer
213
+
214
+ inferencer = InterleaveInferencer(
215
+ model=model,
216
+ vae_model=vae_model,
217
+ tokenizer=tokenizer,
218
+ vae_transform=vae_transform,
219
+ vit_transform=vit_transform,
220
+ new_token_ids=new_token_ids
221
+ )
222
+
223
+ import random
224
+ import numpy as np
225
+
226
+ seed = 42
227
+ random.seed(seed)
228
+ np.random.seed(seed)
229
+ torch.manual_seed(seed)
230
+ if torch.cuda.is_available():
231
+ torch.cuda.manual_seed(seed)
232
+ torch.cuda.manual_seed_all(seed)
233
+ torch.backends.cudnn.deterministic = True
234
+ torch.backends.cudnn.benchmark = False
235
+
236
+
237
+
238
+ inference_hyper=dict(
239
+ cfg_text_scale=4.0,
240
+ cfg_img_scale=2.0,
241
+ cfg_interval=[0.0, 1.0],
242
+ timestep_shift=3.0,
243
+ num_timesteps=50,
244
+ cfg_renorm_min=0.0,
245
+ cfg_renorm_type="text_channel",
246
+ )
247
+
248
+
249
+
250
+ image = Image.open('train_verify/5813_0.png')
251
+ # prompt = 'Click on the First image of "saffola classic masala oats,Click on the First image of "saffola classic masala oats'
252
+ prompt = ' Swipe up on the screen. '
253
+
254
+
255
+ # 保存输入图
256
+ image.save("input_image.png")
257
+
258
+ print(prompt)
259
+ print('-'*10)
260
+
261
+ # 推理
262
+ output_dict = inferencer(image=image, text=prompt, **inference_hyper)
263
+
264
+ # 保存输出图
265
+ out_img = output_dict['image']
266
+ if isinstance(out_img, Image.Image):
267
+ out_img.save("output_image.png")
268
+ elif isinstance(out_img, torch.Tensor):
269
+ from torchvision.transforms.functional import to_pil_image
270
+ to_pil_image(out_img[0].cpu()).save("output_image.png")
271
+
272
+ print("保存完成:input_image.png, output_image.png")