Views
No views yet
1git clone https://github.com/HITsz-TMG/Uni-MoE.git
2cd Uni-MoE-21conda create -n uni_moe_2 python=3.11
2conda activate uni_moe_2
3pip install torch==2.5.1 torchaudio==2.5.1 torchvision==0.20.1
4pip install -r requirements.txt
5pip install flash-attn==2.6.0.post1 --no-build-isolation
6pip install clip==1.0@git+https://github.com/openai/CLIP.git@dcba3cb2e2827b402d2701e7e1c7d9fed8a20ef11import os
2import sys
3from typing import Dict, Optional, Sequence, List, Any, Union
4
5import torch, torchaudio
6import transformers
7from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig
8from uni_moe.model.modeling_out import GrinQwen2VLOutForConditionalGeneration
9from uni_moe.model.processing_qwen2_vl import Qwen2VLProcessor
10from uni_moe.qwen_vl_utils import process_mm_info
11from PIL import Image
12from uni_moe.model import deepspeed_moe_inference_utils
13import torch.distributed as dist
14
15
16def load_unimoe(model_path: str):
17 processor = Qwen2VLProcessor.from_pretrained(model_path)
18 model = GrinQwen2VLOutForConditionalGeneration.from_pretrained(
19 model_path, attn_implementation="flash_attention_2", torch_dtype=torch.bfloat16
20 )
21 model.cuda()
22
23 # sync processors
24 processor.data_args = model.config
25
26 return model, processor
27
28
29EXAMPLES = [
30 # generation
31 {
32 "prompt": "<image>\nImage generation: In the art piece, a realistically depicted young girl with flowing blonde hair gazes intently into the distance, her eyes reflecting the vibrant hues of a spring forest. The verdant greens and soft pastels of the budding trees are captured in subtle brushstrokes, giving the scene a serene and tranquil atmosphere. The minimalist composition focuses on the girl's expression of wonder and the lush woodland background, while the texture of the oil paint adds depth and richness to the canvas.",
33 "input_image": None,
34 "out_name": "genarate.png",
35 },
36 # edition
37 {
38 "prompt": "<image>\nAdd a dog standing near the fence in the foreground, close to the road.",
39 "input_image": "examples/assets/visual_gen/input_images/edit.jpg",
40 "out_name": "edit.png",
41 }
42]
43
44
45def make_message(prompt: str, image_path: str = None) -> List[Dict[str, Any]]:
46 """Return messages list compatible with the processor.apply_chat_template
47 If image_path is provided, include it as first message of type image.
48 """
49 user_items = []
50 if image_path is not None:
51 user_items.append({"type": "image", "image": image_path})
52 else:
53 user_items.append({"type": "image", "image": "examples/assets/visual_gen/input_images/white.png"})
54 user_items.append({"type": "text", "text": prompt})
55 return [{"role": "user", "content": user_items}]
56
57
58def run_batch(model_path: str, examples: List[Dict[str, Any]], save_dir: str):
59 os.makedirs(save_dir, exist_ok=True)
60 model, processor = load_unimoe(model_path)
61
62 for i, ex in enumerate(examples, start=1):
63 print(f"\n=== [{i}/{len(examples)}] prompt={ex['prompt']}")
64 messages = make_message(ex['prompt'], ex.get('input_image'))
65 print(messages)
66
67 texts = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
68 texts = texts.replace("<image>","<|vision_start|><|image_pad|><|vision_end|>").replace("<audio>","<|audio_start|><|audio_pad|><|audio_end|>").replace("<video>","<|vision_start|><|video_pad|><|vision_end|>")
69
70 image_inputs, video_inputs, audio_inputs = process_mm_info(messages)
71
72 inputs = processor(
73 text=texts,
74 images=image_inputs,
75 videos=video_inputs,
76 audios=audio_inputs,
77 padding=True,
78 return_tensors="pt",
79 )
80
81 # ensure batch dim
82 if inputs.get("input_ids") is None:
83 print("Warning: input_ids missing, skipping example")
84 continue
85 inputs["input_ids"] = inputs["input_ids"].unsqueeze(0)
86
87 # prepare save path
88 base_out = os.path.splitext(ex['out_name'])[0]
89 save_name = f"{base_out}.png"
90 save_path = os.path.join(save_dir, save_name)
91
92 # call generate_visualgen
93 output_ids = model.generate_visualgen(
94 input_ids=inputs["input_ids"].to(device=model.device),
95 pixel_values = inputs["pixel_values"].to(dtype=torch.bfloat16,device=model.device) if "pixel_values" in inputs else None,
96 image_grid_thw=inputs.get("image_grid_thw", None),
97 pixel_values_videos=inputs.get("pixel_values_videos", None),
98 video_grid_thw=inputs.get("video_grid_thw", None),
99 audio_features=inputs.get("audio_features", None),
100 audio_grid_thw=inputs.get("audio_grid_thw", None),
101 use_cache=True,
102 attention_mask=inputs["input_ids"].ne(processor.tokenizer.pad_token_id),
103 pad_token_id=processor.tokenizer.eos_token_id,
104 golden_caption_emb=None,
105 golden_task_emb=None,
106 golden_visual_emb=None,
107 image_path=ex.get("input_image", None),
108 save_path=save_path,
109 do_sample=False,
110 num_beams=1,
111 temperature=0.0,
112 max_new_tokens=4096,
113 )
114
115 decoded = processor.batch_decode(output_ids[:, inputs["input_ids"].shape[-1]:], skip_special_tokens=True)[0]
116 print("Generated text output:\n", decoded)
117 print("Saved image to:", save_path)
118
119
120if __name__ == "__main__":
121 MODEL_PATH = "HIT-TMG/Uni-MoE-2.0-Image"
122 SAVE_DIR = "Path to Save Images"
123 run_batch(MODEL_PATH, EXAMPLES, SAVE_DIR)
124