Ascend-SACT/LLaDA2.0-Uni
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

LLaDA2.0-Uni 模型推理部署

本文档旨在指导用户在昇腾 910B 算力节点上,部署 LLaDA2.0-Uni 模型推理服务。

模型简介

LLaDA2.0-Uni 是一个统一的基于 dLLM 的混合专家 (MoE) 模型,它无缝地集成了多模态理解和生成。支持:

🖼️文生图——高保真图像合成,并可选择进行思考/推理。

🔍图像理解——视觉问答、图像描述、文档理解等。

✏️图像编辑——基于指令的编辑,支持单参考或多参考。

🎨交错生成和推理——为交错生成提供初步支持,并解锁高级交错推理。

⚡冲刺加速——KV 缓存重用和自适应解掩码,实现更快的推理。

部署环境

• 硬件:Atlas 800T A2 (昇腾 910B2 芯片)

• 驱动:Ascend HDK 25.3.rc1.2

部署准备

镜像文件

使用灵境 V4.2 镜像部署 LLaDA2.0-Uni 模型,镜像中已安装好所需软件及依赖包。

# 拉取镜像
docker pull swr.cn-north-4.myhuaweicloud.com/ascend-sact/ascend-a2-ubuntu:v4.2

参考文档 灵镜——让昇腾没有难跑的模型 — 开箱即用、一站式、可复现的昇腾容器镜像

版本配套信息

软件推荐版本
CANN9.0.0
torch2.11.0
torch-npu2.11.0rc4
Python3.13

权重下载

pip install modelscope

# 下载模型权重
cd /path/models/
modelscope download --model inclusionAI/LLaDA2.0-Uni --local_dir ./LLaDA2.0-Uni/

源码下载

# 下载模型源码
cd /path/code/
git clone https://github.com/inclusionAI/LLaDA2.0-Uni.git

昇腾适配

算子替换

源码中使用了flash-attention库中的flash_attn_func,昇腾并未适配该接口,需要替换为torch_npu的npu_fusion_attention。

涉及decoder/decoder_model.py文件:

@@ -32,7 +32,17 @@ try:
 except ImportError:
     _HAS_DISPATCH_ATTENTION = False
 from diffusers.models.modeling_outputs import Transformer2DModelOutput
-from flash_attn import flash_attn_func
+
+import importlib.metadata
+import importlib.util
+
+def _is_package_available(name: str) -> bool:
+    return importlib.util.find_spec(name) is not None
+
+if not _is_package_available("torch_npu"):
+    from flash_attn import flash_attn_func
+else:
+    import torch_npu
 
 ADALN_EMBED_DIM = 256
 SEQ_MULTI_OF = 32
@@ -155,11 +170,20 @@ class ZSingleStreamAttnProcessor:
                 parallel_config=self._parallel_config,
             )
         else:
-            hidden_states = flash_attn_func(
-                query, key, value,
-                dropout_p=0.0,
-                causal=False,
-            )
+            if query.device.type == "npu":
+                head_num = query.shape[2]
+                hidden_states = torch_npu.npu_fusion_attention(
+                    query, key, value,
+                    head_num,
+                    "BSND",
+                    keep_prob=1.0,
+                    scale=1.0 / math.sqrt(query.shape[-1]))[0]
+            else:
+                hidden_states = flash_attn_func(
+                    query, key, value,
+                    dropout_p=0.0,
+                    causal=False,
+                )
 
         # Reshape back
         hidden_states = hidden_states.flatten(2, 3)

参考文档 FlashAttentionScore-融合算子替换-NPU亲和适配优化-性能调优方法-性能调优-PyTorch训练模型迁移调优-模型开发

代码修改

昇腾NPU不支持对DT_COMPLEX64(即torch.complex64)类型的张量进行aclnnIndex操作,因此需要对代码中使用的torch.complex64进行修改。

涉及decoder/decoder_model.py文件:

@@ -117,10 +127,15 @@ class ZSingleStreamAttnProcessor:
         # Apply RoPE
         def apply_rotary_emb(x_in: torch.Tensor, freqs_cis: torch.Tensor) -> torch.Tensor:
             with torch.amp.autocast("cuda", enabled=False):
-                x = torch.view_as_complex(x_in.float().reshape(*x_in.shape[:-1], -1, 2))
-                freqs_cis = freqs_cis.unsqueeze(2)
-                x_out = torch.view_as_real(x * freqs_cis).flatten(3)
-                return x_out.type_as(x_in)  # todo
+                x = x_in.float()
+                x_pairs = x.reshape(*x.shape[:-1], -1, 2)
+                a, b = x_pairs[..., 0], x_pairs[..., 1]
+                f_pairs = freqs_cis.reshape(*freqs_cis.shape[:-1], -1, 2).unsqueeze(2)
+                cos, sin = f_pairs[..., 0], f_pairs[..., 1]
+                out_a = a * cos - b * sin
+                out_b = a * sin + b * cos
+                x_out = torch.stack([out_a, out_b], dim=-1).flatten(-2)
+                return x_out.type_as(x_in)
 
         if freqs_cis is not None:
             query = apply_rotary_emb(query, freqs_cis)
@@ -351,7 +375,11 @@ class RopeEmbedder:
                 freqs = 1.0 / (theta ** (torch.arange(0, d, 2, dtype=torch.float64, device="cpu") / d))
                 timestep = torch.arange(e, device=freqs.device, dtype=torch.float64)
                 freqs = torch.outer(timestep, freqs).float()
-                freqs_cis_i = torch.polar(torch.ones_like(freqs), freqs).to(torch.complex64)  # complex64
+                # Interleave [cos_0, sin_0, cos_1, sin_1, ...] to avoid complex tensors
+                # (NPU does not support DT_COMPLEX64 for aclnnIndex and other ops)
+                cos = freqs.cos()
+                sin = freqs.sin()
+                freqs_cis_i = torch.stack([cos, sin], dim=-1).reshape(cos.shape[0], -1)
                 freqs_cis.append(freqs_cis_i)
 
             return freqs_cis

测试验证

文生图测试

测试代码:

import gc
import torch
import torch_npu
from torch_npu.contrib import transfer_to_npu
from transformers import AutoModelForCausalLM, AutoTokenizer
from decoder import decode_vq_tokens

model_path = "/path/models/LLaDA2.0-Uni"
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    model_path, device_map="cuda", torch_dtype="bfloat16", trust_remote_code=True
).eval()
model.tokenizer = tokenizer

# Generate image tokens
result = model.generate_image(
    "A modern Scandinavian kitchen with white cabinetry, marble countertops, and a single orchid on the island. A Nordic woman with sleek blonde ponytail, wearing an oversized sweater and dainty silver necklaces, stirs a matcha bowl with a bamboo whisk, eyes sparkling with quiet joy. Shot with 50mm, f/2.5, diffused window light, cool white balance, low saturation, clean skin retouch. Mood: serene, wholesome, hygge.",
    image_h=1024, image_w=1024,
    steps=8, cfg_scale=2.0,
)

# Free the LLM before decoding to save NPU memory
del model
gc.collect()
torch.cuda.empty_cache()

# Decode to PIL image
image = decode_vq_tokens(
    result["token_ids"], result["h"], result["w"], model_path, "cuda",
    num_steps=8, decode_mode="decoder-turbo",
)
image.save("output.png")

文生图效果:

t2i_output.png

图像理解测试

测试代码:

import torch
import torch_npu
from torch_npu.contrib import transfer_to_npu
from transformers import AutoModelForCausalLM, AutoTokenizer
from encoder.image_tokenizer import ImageTokenizer
from decoder.smart_img_process import smart_resize_images

model_path = "/path/models/LLaDA2.0-Uni"
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    model_path, device_map="cuda", torch_dtype="bfloat16", trust_remote_code=True
).eval()
model.tokenizer = tokenizer

# Encode image to discrete tokens
image_tokenizer = ImageTokenizer(model_path=model_path, device="cuda")
pil_image = smart_resize_images(["/path/code/LLaDA2.0-Uni/assets/understanding_example.png"])[0]
info = image_tokenizer.encode_with_info(pil_image)
image_tokens = [x + model.config.image_token_offset for x in info["token_ids"]]
_, h, w = info["grid_thw"]

# Understand the image
response = model.understand_image(
    image_tokens, h, w,
    question="Describe this image in detail.",
    steps=32, gen_length=2048,
    use_sprint=True,
    threshold=0.93,
    keep_ratio=0.5,
    cache_warmup_steps=1,
    image_keep_ratio=1.0,
    text_keep_ratio=1.0,
)
print(response)

原始图片:

understanding_example.png

图像理解效果:

The image is a table titled "Table 3.16" that presents data on the number of seats up for reelection by political party. The table is divided into five columns and four rows, including the header row. The columns are labeled as follows: "Up for reelection:", "Democratic party," "Republican party," "Other," and "Total." The rows are labeled with two dates: "November 2014," "November 2016," and "Total."

Under the "Up for reelection:" column, the table lists the dates "November 2014" and "November 2016." The "Democratic party" column shows the number "20" for "November 2014" and "10" for "November 2016." The "Republican party" column shows the number "13" for "November 2014" and "24" for "November 2016." The "Other" column shows the number "0" for both dates. The "Total" column is empty for both dates.

The table is bordered with a thin black line, and the text is aligned to the left. The background of the table is white, and the text is black, making it easy to read. The table appears to be a simple, straightforward representation of statistical data.

图像编辑测试

测试代码:

import gc
import torch
import torch_npu
from torch_npu.contrib import transfer_to_npu
from transformers import AutoModelForCausalLM, AutoTokenizer
from encoder.image_tokenizer import ImageTokenizer
from decoder.smart_img_process import smart_resize_images
from decoder.utils import generate_crop_size_list, var_center_crop
from decoder import decode_vq_tokens
from PIL import Image

model_path = "/path/models/LLaDA2.0-Uni"
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    model_path, device_map="cuda", torch_dtype="bfloat16", trust_remote_code=True
).eval()
model.tokenizer = tokenizer

# Encode source image
image_tokenizer = ImageTokenizer(model_path=model_path, device="cuda")
pil_image = smart_resize_images(["/path/code/LLaDA2.0-Uni/assets/edit_example.png"], single_max_pixels=512*512)[0]
info = image_tokenizer.encode_with_info(pil_image)
image_tokens = [x + model.config.image_token_offset for x in info["token_ids"]]
_, h, w = info["grid_thw"]

# Edit the image
result = model.edit_image(
    image_tokens, h, w,
    instruction="Change the background to a beach.",
    steps=8, cfg_text_scale=4.0,
)

# Free the LLM before decoding to save NPU memory
del model
gc.collect()
torch.cuda.empty_cache()

# Decode to PIL image
edited_image = decode_vq_tokens(
    result["token_ids"], result["h"], result["w"], model_path, "cuda",
    num_steps=8, decode_mode="decoder-turbo",
)
edited_image.save("edited.png")

原始图片:

edit_example.png

图像编辑效果:

edited.png