Back to all posts
Engineering

BAGEL 复现

ByteDance's BAGEL model uses a Mixture-of-Transformer-Experts architecture for unified image understanding, generation, and editing, requiring Ampere GPUs for full bfloat16 support.

Paper: arXiv: 2505.14683
Model: HuggingFace: ByteDance-Seed/BAGEL-7B-MoT
Code: GitHub: bytedance-seed/Bagel
Project: bagel-ai.org

1. 环境初始化

git clone https://github.com/bytedance-seed/Bagel.git
cd Bagel

1.1 安装环境依赖

BAGEL 官方推荐使用 Python 3.10 的 conda 环境。安装步骤如下:

# 创建并激活 conda 环境(Python 3.10)
conda create -n bagel python=3.10 -y
conda activate bagel

# 安装 PyTorch(根据 CUDA 版本选择合适的命令)
# CUDA 11.8:
pip install torch==2.5.0 torchvision==0.20.0 torchaudio==2.5.0 --index-url https://download.pytorch.org/whl/cu118
# 或 CUDA 12.1:
pip install torch==2.5.0 torchvision==0.20.0 torchaudio==2.5.0 --index-url https://download.pytorch.org/whl/cu121

# 安装 requirements
pip install -r requirements.txt

# 安装 flash_attn(需预编译 wheel,官方版本锁定为 2.5.8)
pip install flash_attn==2.5.8 --no-build-isolation

flash_attn 安装要点:BAGEL 对 flash_attn 版本要求较严格,官方依赖锁定为 flash_attn==2.5.8。若编译失败,建议从 Hugging Face 社区下载预编译的 wheel 包:https://huggingface.co/lld ...

安培架构(Ampere)兼容性说明
- flash_attn==2.5.8 需要 CUDA 计算能力 ≥ 8.0,即仅支持安培架构及更新的 GPU(如 A100, RTX 3090, RTX 4090)。Volta(V100)、Turing(T4/RTX 2080)等旧架构无法运行原版 flash_attn
- BAGEL 官方权重使用 bfloat16 格式,而 V100 等旧卡不原生支持 bfloat16,会直接报错。
- 解决方案
1. 使用安培或更新的 GPU(推荐)。
2. 改用社区提供的 DFloat11 压缩版DFloat11/BAGEL-7B-MoT-DF11),显存需求降至 ~22 GB,且无需 flash_attn。
3. 使用 GGUF 量化版 通过 llama.cpp 运行(兼容旧卡,性能略降)。
4. 若坚持使用旧卡,可手动注释 requirements.txt 中的 flash-attn,并将模型权重转换为 fp16/fp32(不保证完全兼容)。

2. 模型权重下载(精简)

使用 huggingface_hub + 国内镜像下载到数据盘:

export HF_ENDPOINT=https://hf-mirror.com
hf download ByteDance-Seed/BAGEL-7B-MoT \
  --local-dir /root/autodl-tmp/BAGEL-7B-MoT \
  --max-workers 4

若中断,单文件续传:

hf download ByteDance-Seed/BAGEL-7B-MoT model-00002-of-00006.safetensors \
  --local-dir /root/autodl-tmp/BAGEL-7B-MoT

3. 推理环境确认与基本命令

推理使用已配置的 bagel conda 环境,推荐在仓库目录下运行。

3.1 激活环境

conda activate bagel
cd /root/autodl-tmp/Bagel

3.2 使用 Transformers 进行推理

加载模型和处理器:

import torch
from transformers import AutoProcessor, AutoModelForCausalLM
from PIL import Image

# 加载模型和处理器
model_id = "/root/autodl-tmp/BAGEL-7B-MoT"  # 或 "ByteDance-Seed/BAGEL-7B-MoT"

model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.bfloat16,          # 使用 bfloat16 节省显存
    trust_remote_code=True,              # 必须开启
    device_map="auto",                   # 自动分配到 GPU
)

processor = AutoProcessor.from_pretrained(
    model_id,
    trust_remote_code=True,              # 必须开启
)

3.3 图像理解(看图问答)

image_path = "/path/to/your_image.jpg"
question = "Describe this image in detail."

raw_image = Image.open(image_path).convert("RGB")
messages = [{"role": "user", "content": f"<|image_1|>\n{question}"}]

text = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)

inputs = processor(
    text=text,
    images=raw_image,
    return_tensors="pt",
).to(model.device)

with torch.inference_mode():
    outputs = model.generate(
        **inputs,
        do_sample=True,
        temperature=0.7,
        top_p=0.8,
        max_new_tokens=512,
        eos_token_id=processor.tokenizer.eos_token_id,
        pad_token_id=processor.tokenizer.pad_token_id,
    )

response = processor.decode(outputs[0][inputs.input_ids.shape[-1]:], skip_special_tokens=True)
print(f"Assistant: {response}")

3.4 文生图(Text-to-Image)

prompt = "A snowy mountain at sunset, photorealistic, 4K, high quality."

messages = [{"role": "user", "content": prompt}]

inputs = processor(
    text=processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False),
    return_tensors="pt",
).to(model.device)

with torch.inference_mode():
    outputs = model.generate(
        **inputs,
        do_sample=True,
        temperature=0.7,
        top_p=0.8,
        max_new_tokens=1024,
        eos_token_id=processor.tokenizer.eos_token_id,
        pad_token_id=processor.tokenizer.pad_token_id,
    )

# 解码生成的图像 token 并保存
generated_image = processor.decode_image(outputs[0][inputs.input_ids.shape[-1]:])
generated_image.save("/root/autodl-tmp/outputs/generated_image.png")

3.5 图像编辑(Image Editing)

image_path = "/path/to/input_image.jpg"
edit_instruction = "Add a red scarf to the person and make the sky sunny."

raw_image = Image.open(image_path).convert("RGB")
messages = [{"role": "user", "content": f"<|image_1|>\n{edit_instruction}"}]

text = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
inputs = processor(text=text, images=raw_image, return_tensors="pt").to(model.device)

with torch.inference_mode():
    outputs = model.generate(**inputs, do_sample=True, temperature=0.7, max_new_tokens=1024)

edited_image = processor.decode_image(outputs[0][inputs.input_ids.shape[-1]:])
edited_image.save("/root/autodl-tmp/outputs/edited_image.png")

3.6 Gradio 网页界面

官方仓库包含一个 app.py 用于启动 Gradio WebUI:

python app.py --model_path /root/autodl-tmp/BAGEL-7B-MoT

如需指定端口:

python app.py --model_path /root/autodl-tmp/BAGEL-7B-MoT --server_port 7860 --share

3.7 使用官方 CLI 推理脚本

python inference.py \
  --model_path /root/autodl-tmp/BAGEL-7B-MoT \
  --prompt "A futuristic city skyline at night" \
  --task text_to_image \
  --save_path /root/autodl-tmp/outputs/images

注意:上述命令模板以官方 inference.py 的实际参数为准。若仓库未提供统一推理脚本,建议直接使用 Transformers 方式(第 3.2–3.5 节)。

4. 关键功能特性说明

4.1 Mixture-of-Transformer-Experts(MoT)架构

BAGEL 采用 MoT(混合 Transformer 专家) 架构,不同于传统 MoE(Mixture-of-Experts),其核心思想是将模型拆分为多个 Transformer 专家子网络,通过动态路由机制根据输入模态自动激活相关专家进行处理。MoT 架构使得 BAGEL 在 70 亿激活参数下实现了等效 140 亿参数的表达能力。该设计有效分离了理解与生成模块,最大化模型从多样化多模态信息中的学习能力,同时保证了端到端的统一推理。

4.2 双编码器设计

BAGEL 使用两个独立的编码器分别捕获图像的像素级特征(通过 VAE)和语义级特征(通过 ViT)。两者的融合对于复杂智能编辑能力的涌现具有关键作用。

4.3 文生视频与视频帧生成

BAGEL 的视频生成能力遵循 "Next Group of Token" 预测范式,模型被训练为预测下一组语言或视觉 token(作为压缩目标)。这一机制使其能够生成连贯的图像序列(video frames),支持:

  • 未来帧预测:输入前 3 帧视频即可预测后续 10 帧,在物理模拟场景中误差率低于 12%
  • 3D 操作与世界导航:通过大规模视频和网页数据训练,具备世界建模与导航能力
  • 视频帧生成:可直接从文本 prompt 生成高保真视频帧或交错的图文内容

注意:具体的视频帧生成命令需参照官方代码库中的实现。视频生成输出形式与 VILA-U 类似,模型内部按因果自回归顺序生成 8 帧(每帧 256 tokens),具有明确的帧顺序关系。

5. 硬件资源建议

量化级别 模型大小 峰值显存(推理) 最低推荐
BFloat16 原版 29.21 GB ~30 GB A100 40GB / H100
DFloat11 压缩 19.89 GB ~22 GB RTX 4090 / A6000
INT8 量化 ~15 GB ~16–18 GB RTX 3090 / 4080 SUPER
  • 最低要求:24 GB 显存(使用 DFloat11 或 INT8 量化版本)
  • 推荐配置:≥ 40 GB 显存(运行原版 BFloat16 模型)
  • 入门配置:可通过 vLLM 仅加载视觉理解能力(vision-to-text),降低显存占用

Share this post

Back to home

Comments