Skip to content

Commit a165d9f

Browse files
committed
Merge branch 'develop' of https://github.com/PaddlePaddle/PaddleFormers into merge_paddlefleet_to_paddleformers
2 parents 785fa81 + c2cac26 commit a165d9f

2 files changed

Lines changed: 172 additions & 0 deletions

File tree

paddleformers/cli/train/deepseek_v3_pretrain/modeling.py

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,20 @@
5454

5555
from paddle import _C_ops
5656

57+
_flash_mask_available = False
58+
try:
59+
if paddle.cuda.is_available() and paddle.cuda.get_device_capability()[0] == 10:
60+
from paddlefleet_ops.flash_mask.cute.interface import (
61+
_flash_attn_bwd as _flash_attn_v4_bwd,
62+
)
63+
from paddlefleet_ops.flash_mask.cute.interface import (
64+
_flash_attn_fwd as _flash_attn_v4_fwd,
65+
)
66+
67+
_flash_mask_available = True
68+
except (ImportError, AttributeError):
69+
_flash_mask_available = False
70+
5771
try:
5872
from paddle.nn.functional.flash_attention import flash_attention
5973
except:
@@ -2990,6 +3004,17 @@ def forward(
29903004
False, # pack_gqa_
29913005
0, # sm_margin
29923006
)
3007+
elif fa_version == 4:
3008+
attn_out, softmax_lse = _flash_attn_v4_fwd(
3009+
query_states,
3010+
key_states,
3011+
value_states,
3012+
softmax_scale=softmax_scale,
3013+
causal=True,
3014+
return_lse=True,
3015+
startend_row_indices=None,
3016+
pack_gqa=False,
3017+
)
29933018
else:
29943019
raise AssertionError(f"invalid {fa_version=}")
29953020

@@ -3064,6 +3089,55 @@ def forward(
30643089
softmax_scale,
30653090
recompute_fa3,
30663091
)
3092+
elif fa_version == 4:
3093+
if recompute_fa3:
3094+
ctx.save_for_backward(
3095+
q_init,
3096+
kv_init,
3097+
None,
3098+
None,
3099+
q_ln_weight,
3100+
kv_ln_weight,
3101+
q_up_weight,
3102+
kv_up_weight,
3103+
rotary_emb,
3104+
num_heads,
3105+
q_head_dim,
3106+
qk_nope_head_dim,
3107+
v_head_dim,
3108+
qk_rope_head_dim,
3109+
position_ids,
3110+
eps,
3111+
custom_map.q_lens,
3112+
custom_map.out_proj_weight,
3113+
kv_lora_rank,
3114+
softmax_scale,
3115+
recompute_fa3,
3116+
)
3117+
else:
3118+
ctx.save_for_backward(
3119+
q_init,
3120+
kv_init,
3121+
attn_out,
3122+
softmax_lse,
3123+
q_ln_weight,
3124+
kv_ln_weight,
3125+
q_up_weight,
3126+
kv_up_weight,
3127+
rotary_emb,
3128+
num_heads,
3129+
q_head_dim,
3130+
qk_nope_head_dim,
3131+
v_head_dim,
3132+
qk_rope_head_dim,
3133+
position_ids,
3134+
eps,
3135+
custom_map.q_lens,
3136+
custom_map.out_proj_weight,
3137+
kv_lora_rank,
3138+
softmax_scale,
3139+
recompute_fa3,
3140+
)
30673141
else:
30683142
raise AssertionError(f"invalid {fa_version=}")
30693143

@@ -3141,6 +3215,30 @@ def backward(ctx, dout):
31413215
softmax_scale,
31423216
recompute_fa3,
31433217
) = ctx.saved_tensor()
3218+
elif fa_version == 4:
3219+
(
3220+
q_init,
3221+
kv_init,
3222+
attn_out,
3223+
softmax_lse,
3224+
q_ln_weight,
3225+
kv_ln_weight,
3226+
q_up_weight,
3227+
kv_up_weight,
3228+
rotary_emb,
3229+
num_heads,
3230+
q_head_dim,
3231+
qk_nope_head_dim,
3232+
v_head_dim,
3233+
qk_rope_head_dim,
3234+
position_ids,
3235+
eps,
3236+
q_lens,
3237+
out_proj_weight,
3238+
kv_lora_rank,
3239+
softmax_scale,
3240+
recompute_fa3,
3241+
) = ctx.saved_tensor()
31443242
else:
31453243
raise AssertionError(f"invalid {fa_version=}")
31463244

@@ -3149,6 +3247,8 @@ def backward(ctx, dout):
31493247
assert attn_out is not None and softmax_lse is not None
31503248
if fa_version == 3 and not recompute_fa3:
31513249
assert attn_out is not None and softmax_lse is not None
3250+
if fa_version == 4 and not recompute_fa3:
3251+
assert attn_out is not None and softmax_lse is not None
31523252

31533253
q_ln_t, q_ln_invar = paddle.incubate.nn.functional.fused_rms_norm_ext(
31543254
q_init, q_ln_weight, eps
@@ -3328,6 +3428,71 @@ def backward(ctx, dout):
33283428
0.0,
33293429
0,
33303430
)
3431+
elif fa_version == 4:
3432+
# recompute fa4
3433+
if recompute_fa3:
3434+
with paddle.no_grad():
3435+
attn_out, softmax_lse = _flash_attn_v4_fwd(
3436+
query_states,
3437+
key_states,
3438+
value_states,
3439+
softmax_scale=softmax_scale,
3440+
causal=True,
3441+
return_lse=True,
3442+
startend_row_indices=None,
3443+
pack_gqa=False,
3444+
)
3445+
3446+
# padding x and quant
3447+
bsz = value_states.shape[0]
3448+
attn_out_reshape = attn_out.reshape([bsz * q_lens, -1]).contiguous()
3449+
d_attn_out_reshape_shape = attn_out_reshape.shape
3450+
attn_out_reshape = FP8LinearFunctionBase.padding(attn_out_reshape, 0)
3451+
(
3452+
attn_out_reshape_t_fp8,
3453+
attn_out_reshape_t_scale,
3454+
) = paddle.incubate.nn.functional.fp8_quant_blockwise(
3455+
attn_out_reshape,
3456+
output_scale_transpose=True,
3457+
quant_method="1x128",
3458+
input_transpose=True,
3459+
return_transpose_only=True,
3460+
)
3461+
dout_2d = dout.reshape([-1, dout.shape[-1]])
3462+
3463+
# ===== dx = deep_gemm(dout_fp8, w_fp8)
3464+
d_attn_out, dout_t_fp8, dout_t_scale = FP8LinearFunctionBase.compute_fp8_linear(
3465+
dout_2d, out_proj_weight, weight_transpose=False, return_mode="with_input_transpose_quant"
3466+
)
3467+
d_attn_out = d_attn_out.reshape(d_attn_out_reshape_shape)
3468+
FP8LinearFunctionBase.compute_expert_w_grad(
3469+
attn_out_reshape_t_fp8,
3470+
attn_out_reshape_t_scale,
3471+
dout_t_fp8,
3472+
dout_t_scale,
3473+
True,
3474+
True,
3475+
out_proj_weight,
3476+
paddle.float32,
3477+
)
3478+
3479+
dout = d_attn_out
3480+
dout = dout.reshape(attn_out.shape)
3481+
3482+
with paddle.no_grad():
3483+
flashmask_info = None
3484+
q_grad, k_grad, v_grad = _flash_attn_v4_bwd(
3485+
query_states,
3486+
key_states,
3487+
value_states,
3488+
attn_out,
3489+
dout,
3490+
softmax_lse,
3491+
flashmask_info,
3492+
softmax_scale=softmax_scale,
3493+
causal=True,
3494+
deterministic=bool(paddle.get_flags(["FLAGS_cudnn_deterministic"])["FLAGS_cudnn_deterministic"]),
3495+
)
33313496
else:
33323497
raise AssertionError(f"invalid {fa_version=}")
33333498

@@ -3511,6 +3676,9 @@ def __init__(
35113676
super().__init__()
35123677
self._dtype = self._helper.get_default_dtype()
35133678

3679+
if paddle.cuda.is_available() and paddle.cuda.get_device_capability()[0] >= 10 and _flash_mask_available:
3680+
fa_version = 4
3681+
35143682
self.q_ln_weight = paddle.create_parameter(
35153683
shape=[q_norm_hidden_size],
35163684
dtype=self._dtype,

paddleformers/transformers/deepseek_v4/modeling.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -513,6 +513,8 @@ def _gen_aoa_config(cls, config: DeepseekV4Config):
513513
"embed.weight -> model.embedding.embed_tokens.weight",
514514
"norm.weight -> model.norm.weight",
515515
]
516+
if mtp_num_layers > 0:
517+
stmts.append("embed.weight -> model.mtp_embedding.embed_tokens.weight")
516518
if config.tie_word_embeddings:
517519
stmts += ["embed.weight -> model.lm_head.weight"]
518520
else:
@@ -835,6 +837,8 @@ def _gen_inv_aoa_config(cls, config: DeepseekV4Config):
835837
"model.embedding.embed_tokens.weight -> embed.weight",
836838
"model.norm.weight -> norm.weight",
837839
]
840+
if mtp_num_layers > 0:
841+
stmts.append("model.mtp_embedding.embed_tokens.weight -> embed.weight")
838842
if config.tie_word_embeddings:
839843
stmts += ["model.lm_head.weight -> _"]
840844
else:

0 commit comments

Comments
 (0)