本文档旨在指导用户在昇腾 910B 算力节点上,部署 LLaDA-o 模型推理服务。
LLaDA-o 将扩散语言模型扩展到统一的多模态场景,在该场景中,文本和视觉信号在一个共享的生成框架内进行表示和处理。
亮点:
• 硬件:Atlas 800T A2 (昇腾 910B2 芯片)
• 驱动:Ascend HDK 25.3.rc1.2
使用灵境V4.2镜像部署LLaDA-o模型,镜像中已安装好所需软件及依赖包。
# 拉取镜像
docker pull swr.cn-north-4.myhuaweicloud.com/ascend-sact/ascend-a2-ubuntu:v4.2| 软件 | 推荐版本 |
|---|---|
| CANN | 9.0.0 |
| torch | 2.11.0 |
| torch-npu | 2.11.0rc4 |
| Python | 3.13 |
# 下载模型权重
cd /path/models/
hf download GSAI-ML/LLaDA-o --local-dir /path/models/LLaDA-o/# 下载模型源码
cd /path/code/
git clone https://github.com/ML-GSAI/LLaDA-o.git源码中使用了flash-attention库中的flash_attn_varlen_func,昇腾并未适配该接口,需要替换为torch_npu的npu_fusion_attention。
modeling/lladao/llada_navit.py:
@@ -8,7 +8,7 @@
#
# This modified file is released under the same license.
-
+import math
from dataclasses import dataclass
from functools import partial
from typing import List, Optional, Tuple
@@ -20,7 +20,17 @@ from torch.nn.attention.flex_attention import flex_attention
from torch.nn.functional import scaled_dot_product_attention
from transformers.utils import ModelOutput
-from flash_attn import flash_attn_varlen_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_varlen_func
+else:
+ import torch_npu
+
from modeling.llada.modeling_llada import (
LLaDAAttention,
LLaDAMLP,
@@ -538,16 +548,31 @@ class PackedAttentionMoT(LLaDAAttention):
cu_seqlens_q = torch.nn.functional.pad(torch.cumsum(query_lens, dim=0), (1, 0))
cu_seqlens_k = torch.nn.functional.pad(torch.cumsum(key_values_lens, dim=0), (1, 0))
- packed_attn_output = flash_attn_varlen_func(
- q=packed_query_states,
- k=merged_key_states,
- v=merged_value_states,
- cu_seqlens_q=cu_seqlens_q.to(torch.int32),
- cu_seqlens_k=cu_seqlens_k.to(torch.int32),
- max_seqlen_q=max(query_lens).item(),
- max_seqlen_k=max(key_values_lens).item(),
- causal=is_causal,
- )
+ if packed_query_states.device.type == "npu" and is_causal == False:
+ head_num = packed_query_states.shape[1]
+ packed_attn_output = torch_npu.npu_fusion_attention(
+ packed_query_states,
+ merged_key_states,
+ merged_value_states,
+ head_num,
+ pse=None,
+ atten_mask=None,
+ scale=1.0 / math.sqrt(packed_query_states.shape[-1]),
+ keep_prob=1,
+ input_layout="TND",
+ actual_seq_qlen=tuple(cu_seqlens_q.to(torch.int32)[1:].cpu().numpy().tolist()),
+ actual_seq_kvlen=tuple(cu_seqlens_k.to(torch.int32)[1:].cpu().numpy().tolist()))[0]
+ else:
+ packed_attn_output = flash_attn_varlen_func(
+ q=packed_query_states,
+ k=merged_key_states,
+ v=merged_value_states,
+ cu_seqlens_q=cu_seqlens_q.to(torch.int32),
+ cu_seqlens_k=cu_seqlens_k.to(torch.int32),
+ max_seqlen_q=max(query_lens).item(),
+ max_seqlen_k=max(key_values_lens).item(),
+ causal=is_causal,
+ )
packed_attn_output = packed_attn_output.reshape(-1, self.hidden_size)
if mode == 'und':
packed_attn_output = self.o_proj(packed_attn_output)modeling/lladao/siglip_navit.py
@@ -9,13 +9,24 @@
#
# This modified file is released under the same license.
+import math
import torch
from torch import nn
from transformers.activations import ACT2FN
from modeling.siglip.configuration_siglip import SiglipVisionConfig as _SiglipVisionConfig
from modeling.siglip.modeling_siglip import SiglipAttention, SiglipPreTrainedModel
-from flash_attn import flash_attn_varlen_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_varlen_func
+else:
+ import torch_npu
class SiglipVisionConfig(_SiglipVisionConfig):
@@ -229,16 +240,31 @@ class SiglipFlashAttention2(SiglipAttention):
query_states = torch.cat([qh, qw], dim=-1)
key_states = torch.cat([kh, kw], dim=-1)
- attn_output = flash_attn_varlen_func(
- query_states.to(torch.bfloat16),
- key_states.to(torch.bfloat16),
- value_states.to(torch.bfloat16),
- cu_seqlens_q=cu_seqlens,
- cu_seqlens_k=cu_seqlens,
- max_seqlen_q=max_seqlen,
- max_seqlen_k=max_seqlen,
- causal=False,
- )
+ if query_states.device.type == "npu":
+ head_num = query_states.shape[1]
+ attn_output = torch_npu.npu_fusion_attention(
+ query_states.to(torch.bfloat16),
+ key_states.to(torch.bfloat16),
+ value_states.to(torch.bfloat16),
+ head_num,
+ pse=None,
+ atten_mask=None,
+ scale=1.0 / math.sqrt(query_states.shape[-1]),
+ keep_prob=1,
+ input_layout="TND",
+ actual_seq_qlen=tuple(cu_seqlens[1:].cpu().numpy().tolist()),
+ actual_seq_kvlen=tuple(cu_seqlens[1:].cpu().numpy().tolist()))[0]
+ else:
+ attn_output = flash_attn_varlen_func(
+ query_states.to(torch.bfloat16),
+ key_states.to(torch.bfloat16),
+ value_states.to(torch.bfloat16),
+ cu_seqlens_q=cu_seqlens,
+ cu_seqlens_k=cu_seqlens,
+ max_seqlen_q=max_seqlen,
+ max_seqlen_k=max_seqlen,
+ causal=False,
+ )
attn_output = self.out_proj(attn_output.reshape(total_q_len, -1))
return attn_output参考文档 FlashAttentionScore-融合算子替换-NPU亲和适配优化-性能调优方法-性能调优-PyTorch训练模型迁移调优-模型开发
LLoDA-o代码基于transformers 4.49版本,而灵境V4.2镜像中使用的是transformers 5.12.1版本,两个版本在构造config时实现有差异。
新版本会把config中的"rope_scaling": null,自动转成"rope_scaling": {"rope_type": "default", "factor": 1.0}。
而代码中并未考虑这一情况,导致实际运行出错。
涉及modeling/llada/modeling_llada.py文件:
@@ -293,7 +293,12 @@ class LLaDAAttention(nn.Module):
self._init_rope()
def _init_rope(self):
- if self.config.rope_scaling is None:
+ scaling_type = (
+ self.config.rope_scaling.get("type")
+ if isinstance(self.config.rope_scaling, dict)
+ else None
+ )
+ if scaling_type is None:
self.rotary_emb = LLaDARotaryEmbedding(
self.head_dim,
max_position_embeddings=self.max_position_embeddings,LLaDA-o模型提供了流水线demo,可一次性完成文生图、图像理解、图像编辑验证。详细代码如下:
import os
import sys
from pathlib import Path
from IPython.display import display
import torch
import torch_npu
from torch_npu.contrib import transfer_to_npu
CANDIDATES = [Path.cwd(), Path.cwd() / "LLaDA-o"]
PROJECT_DIR = next((path for path in CANDIDATES if (path / "inferencer.py").exists()), None)
if PROJECT_DIR is None:
raise RuntimeError("Please launch the notebook from the repo root or the LLaDA-o directory.")
if str(PROJECT_DIR) not in sys.path:
sys.path.insert(0, str(PROJECT_DIR))
from demo_pipeline import (
DEFAULT_IMAGE_EDIT_ARGS,
DEFAULT_TEXT_TO_IMAGE_ARGS,
DEFAULT_UNDERSTANDING_ARGS,
LLaDAMultimodalDemo,
load_image,
set_seed,
)
def save_text(path, text):
path.write_text(text.strip() + "\n", encoding="utf-8")
print(f"Project dir: {PROJECT_DIR}")
# First download the model from https://huggingface.co/GSAI-ML/LLaDA-o
# Then set MODEL_PATH to the local directory you downloaded, or set LLADAO_MODEL_PATH.
MODEL_PATH = os.environ.get("LLADAO_MODEL_PATH", "/path/models/LLaDA-o")
MAX_MEM_PER_GPU = "40GiB"
OFFLOAD_DIR = "/tmp/lladao_offload"
OUTPUT_DIR = PROJECT_DIR / "demo_outputs"
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
SEED = 42
TEXT_TO_IMAGE_PROMPT = "A studio-quality product photo of a glass teapot shaped like a tiny planet, soft lighting."
UNDERSTANDING_PROMPT = "Describe this image in detail."
IMAGE_EDIT_PROMPT = (
"Turn the Earth-themed glass teapot into a Mars-themed glass teapot, "
"keep the transparent glass material, studio product photography, and soft lighting."
)
TEXT_TO_IMAGE_ARGS = dict(DEFAULT_TEXT_TO_IMAGE_ARGS)
UNDERSTANDING_ARGS = dict(DEFAULT_UNDERSTANDING_ARGS)
IMAGE_EDIT_ARGS = dict(DEFAULT_IMAGE_EDIT_ARGS)
BATCH_PROMPT_FILE = PROJECT_DIR / "prompt.txt"
BATCH_OUTPUT_DIR = OUTPUT_DIR / "batch_text_to_image"
BATCH_START_LINE = 0
print(f"Model path: {MODEL_PATH}")
print(f"Output dir: {OUTPUT_DIR}")
print(f"Batch prompt file: {BATCH_PROMPT_FILE}")
print(f"Batch output dir: {BATCH_OUTPUT_DIR}")
demo = LLaDAMultimodalDemo.from_pretrained(
model_path=MODEL_PATH,
max_mem_per_gpu=MAX_MEM_PER_GPU,
offload_dir=OFFLOAD_DIR,
)
print("Model ready.")
text_to_image_result = demo.text_to_image(
TEXT_TO_IMAGE_PROMPT,
seed=SEED,
**TEXT_TO_IMAGE_ARGS,
)
reference_image = text_to_image_result["image"]
text_to_image_path = OUTPUT_DIR / "01_text_to_image.png"
reference_image.save(text_to_image_path)
display(reference_image)
print(f"Saved: {text_to_image_path}")
understanding_result = demo.understand(
reference_image,
UNDERSTANDING_PROMPT,
**UNDERSTANDING_ARGS,
)
understanding_path = OUTPUT_DIR / "02_understanding.txt"
save_text(understanding_path, understanding_result["text"])
display(reference_image)
print(understanding_result["text"])
print(
f"valid/total tokens: {understanding_result['valid_tokens']}/{understanding_result['total_tokens']} | "
f"elapsed: {understanding_result['elapsed_seconds']:.2f}s"
)
print(f"Saved: {understanding_path}")
image_edit_result = demo.edit_image(
reference_image,
IMAGE_EDIT_PROMPT,
seed=SEED,
**IMAGE_EDIT_ARGS,
)
edited_image = image_edit_result["image"]
image_edit_path = OUTPUT_DIR / "03_image_edit.png"
edited_image.save(image_edit_path)
print("Source image:")
display(reference_image)
print("Edited image:")
display(edited_image)
print(f"Saved: {image_edit_path}")文生图效果:

图像理解效果:
The image features a glass teapot with a unique design, resembling the shape of the Earth. The teapot is set against a neutral background, which helps to highlight the details of the teapot. There is no text present in the image.图像编辑效果:
