Qwen3.5-35B-A3B fp16训练报错
System Info
bf16训练正常,fp16训练报错:
File "/usr/lib/python3.10/concurrent/futures/_base.py", line 458, in result return self.__get_result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 403, in __get_result raise self._exception File "/usr/local/lib/python3.10/dist-packages/verl/single_controller/ray/base.py", line 932, in func return getattr(self.worker_dict[key], name)(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/verl/single_controller/base/decorator.py", line 427, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/verl/utils/profiler/performance.py", line 105, in f return self.log(decorated_function, *args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/verl/utils/profiler/performance.py", line 118, in log output = func(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/verl/utils/profiler/profile.py", line 173, in wrapper return func(self_instance, *args, **kwargs_inner) File "/usr/local/lib/python3.10/dist-packages/verl/workers/megatron_workers.py", line 763, in update_actor global_num_tokens = data.meta_info["global_token_num"] File "/usr/local/lib/python3.10/dist-packages/verl/utils/profiler/performance.py", line 105, in f return self.log(decorated_function, *args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/verl/utils/profiler/performance.py", line 118, in log output = func(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/verl/workers/actor/megatron_actor.py", line 894, in update_policy raise NotImplementedError NotImplementedError
看报错的位置应该是优化器更新失败,更具体的错误就没报出来了: update_successful, grad_norm, num_zeros_in_grad = self.actor_optimizer.step() data = {"actor/grad_norm": grad_norm} append_to_dict(metrics, data)
if update_successful:
# allgather already execute in optimizer.step in new megatron
pass
else:
raise NotImplementedError
Information
- [ ] The official example scripts
- [x] My own modified scripts
Tasks
- [ ] An officially supported task in the
examplesfolder (such as GLUE/SQuAD, ...) - [x] My own task or dataset (give details below)
Reproduction
添加的训练参数: actor_rollout_ref.rollout.dtype="float16" actor_rollout_ref.actor.megatron.dtype="float16" +actor_rollout_ref.actor.model.override_model_config.model_config="{text_config:{dtype:float16}}" 注:第3个参数会报错,需要在McoreActorConfig中添加model: dict[str, Any] = field(default_factory=dict)
Expected behavior
正常执行
Thank you for the detailed error report. The issue occurs when the Megatron optimizer's step() returns update_successful=False for fp16 training.
Root cause analysis:
The error originates from megatron_actor.py:894:
if update_successful:
pass
else:
raise NotImplementedError
This indicates that Megatron's fp16 optimizer encountered an issue during the gradient update step. Common causes include:
-
Gradient overflow/underflow in fp16: The gradients may exceed fp16's dynamic range (
~65504max), causing the optimizer to reject the update. -
Loss scaling issues: fp16 training typically requires loss scaling to prevent gradient underflow. Megatron's dynamic loss scaler may have failed to find a valid scale.
Debugging suggestions:
- Check gradient norms before the error:
# Add logging in megatron_actor.py before optimizer.step()
print(f"Grad norm: {grad_norm}, Loss scale: {self.actor_optimizer.loss_scale}")
- Enable gradient clipping to prevent overflow:
actor_rollout_ref.actor.optim.clip_grad: 1.0
- Try static loss scaling instead of dynamic:
actor_rollout_ref.actor.megatron.loss_scale: 65536
-
Alternative: Qwen3.5-35B-A3B is a MoE model with large parameter counts. fp16 may not provide sufficient numerical stability for the expert routing computations. Consider:
- Using bf16 (your working config)
- Using fp32 for specific layers:
actor_rollout_ref.actor.megatron.fp32_param_tolerance: 0.0
Why bf16 works but fp16 doesn't: bf16 has the same dynamic range as fp32 (8 exponent bits) but reduced precision (7 mantissa bits vs 10 for fp16). This makes bf16 more stable for large models with gradient variance.
Could you share:
- Your full training config
- The gradient norm values before the error
This will help identify whether it's a scaling issue or a specific layer incompatibility.
@shinesun07 May I ask which image version you are using?
Thank you for the detailed error report. The issue occurs when the Megatron optimizer's
step()returnsupdate_successful=Falsefor fp16 training.Root cause analysis:
The error originates from
megatron_actor.py:894:if update_successful: pass else: raise NotImplementedError This indicates that Megatron's fp16 optimizer encountered an issue during the gradient update step. Common causes include:
- Gradient overflow/underflow in fp16: The gradients may exceed fp16's dynamic range (
~65504max), causing the optimizer to reject the update.- Loss scaling issues: fp16 training typically requires loss scaling to prevent gradient underflow. Megatron's dynamic loss scaler may have failed to find a valid scale.
Debugging suggestions:
- Check gradient norms before the error:
Add logging in megatron_actor.py before optimizer.step()
print(f"Grad norm: {grad_norm}, Loss scale: {self.actor_optimizer.loss_scale}") 2. Enable gradient clipping to prevent overflow:
actor_rollout_ref.actor.optim.clip_grad: 1.0 3. Try static loss scaling instead of dynamic:
actor_rollout_ref.actor.megatron.loss_scale: 65536 4. Alternative: Qwen3.5-35B-A3B is a MoE model with large parameter counts. fp16 may not provide sufficient numerical stability for the expert routing computations. Consider:
- Using bf16 (your working config)
- Using fp32 for specific layers:
actor_rollout_ref.actor.megatron.fp32_param_tolerance: 0.0Why bf16 works but fp16 doesn't: bf16 has the same dynamic range as fp32 (8 exponent bits) but reduced precision (7 mantissa bits vs 10 for fp16). This makes bf16 more stable for large models with gradient variance.
Could you share:
- Your full training config
- The gradient norm values before the error
This will help identify whether it's a scaling issue or a specific layer incompatibility.
使用fp16主要是参考这篇文章:Defeating the Training-Inference Mismatch via FP16,之前训Qwen3-30B-A3B都是正常的
从这个数值来看,应该不是scale超范围的问题(如果是scale的问题一般应该也不会第一步就报错)
Grad norm: 0.05284526653879948, Loss scale: tensor([32768.], device='cuda:0')
另,需要这么改:
current_loss_scale = 0
for opt in self.actor_optimizer.chained_optimizers:
current_loss_scale = opt.get_loss_scale()
print(f"{opt.get_loss_scale()=}")
print(f"Grad norm: {grad_norm}, Loss scale: {current_loss_scale}")
详细参数: export ALL_OFFLOAD=True DATA=( data.train_files=${train_data} data.val_files=${valid_data} data.train_batch_size=16 data.max_prompt_length=2048 data.max_response_length=512 data.truncation='error' data.filter_overlong_prompts=True data.filter_overlong_prompts_workers=32 +data.apply_chat_template_kwargs='{enable_thinking:False}' +data.add_extra_data=False data.return_raw_chat=True data.shuffle=True )
MODEL=( actor_rollout_ref.model.path=Qwen3.5/Qwen3.5-35B-A3B actor_rollout_ref.model.trust_remote_code=True actor_rollout_ref.model.use_remove_padding=False actor_rollout_ref.model.use_fused_kernels=False )
ACTOR=( actor_rollout_ref.actor.optim.lr=4e-6 actor_rollout_ref.actor.optim.lr_warmup_steps=0 actor_rollout_ref.actor.ppo_mini_batch_size=16 actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=1 actor_rollout_ref.actor.ppo_max_token_len_per_gpu=2560 actor_rollout_ref.actor.use_dynamic_bsz=False actor_rollout_ref.actor.use_kl_loss=True actor_rollout_ref.actor.kl_loss_coef=0.05 actor_rollout_ref.actor.kl_loss_type=low_var_kl actor_rollout_ref.actor.entropy_coeff=0 actor_rollout_ref.actor.megatron.use_mbridge=True actor_rollout_ref.actor.megatron.vanilla_mbridge=True actor_rollout_ref.actor.megatron.use_remove_padding=False actor_rollout_ref.actor.megatron.tensor_model_parallel_size=1 actor_rollout_ref.actor.megatron.pipeline_model_parallel_size=2 actor_rollout_ref.actor.megatron.context_parallel_size=1 actor_rollout_ref.actor.megatron.expert_model_parallel_size=8 actor_rollout_ref.actor.megatron.expert_tensor_parallel_size=1 actor_rollout_ref.actor.megatron.virtual_pipeline_model_parallel_size=null actor_rollout_ref.actor.megatron.param_offload=${ALL_OFFLOAD} actor_rollout_ref.actor.megatron.optimizer_offload=${ALL_OFFLOAD} actor_rollout_ref.actor.megatron.grad_offload=${ALL_OFFLOAD} actor_rollout_ref.actor.megatron.dtype=float16 ++actor_rollout_ref.actor.megatron.override_transformer_config.attention_backend=auto +actor_rollout_ref.actor.megatron.override_transformer_config.recompute_method=uniform +actor_rollout_ref.actor.megatron.override_transformer_config.recompute_granularity=full +actor_rollout_ref.actor.megatron.override_transformer_config.recompute_num_layers=1 +actor_rollout_ref.actor.megatron.override_transformer_config.moe_aux_loss_coeff=0.01 +actor_rollout_ref.actor.megatron.override_transformer_config.moe_z_loss_coeff=0.001 +actor_rollout_ref.actor.optim.override_optimizer_config.optimizer_offload_fraction=1 +actor_rollout_ref.actor.optim.override_optimizer_config.overlap_cpu_optimizer_d2h_h2d=True +actor_rollout_ref.actor.optim.override_optimizer_config.use_precision_aware_optimizer=True +actor_rollout_ref.actor.optim.override_optimizer_config.optimizer_cpu_offload=True +actor_rollout_ref.actor.log_ratio_detail=True actor_rollout_ref.actor.loss_agg_mode="token-mean" actor_rollout_ref.actor.policy_loss.loss_mode=gspo actor_rollout_ref.actor.clip_ratio_low=0.008 actor_rollout_ref.actor.clip_ratio_high=0.02 +actor_rollout_ref.actor.megatron.override_transformer_config.masked_softmax_fusion=True +actor_rollout_ref.actor.megatron.override_transformer_config.bias_activation_fusion=True +actor_rollout_ref.actor.megatron.override_transformer_config.bias_dropout_fusion=True +actor_rollout_ref.actor.megatron.override_transformer_config.deallocate_pipeline_outputs=True +actor_rollout_ref.actor.megatron.override_transformer_config.persist_layer_norm=True +actor_rollout_ref.actor.megatron.override_transformer_config.moe_grouped_gemm=True +actor_rollout_ref.actor.megatron.override_transformer_config.moe_router_dtype=fp32 +actor_rollout_ref.actor.megatron.override_transformer_config.gradient_accumulation_fusion=True +actor_rollout_ref.actor.checkpoint.mbridge_config.distributed_filesystem=True +actor_rollout_ref.actor.checkpoint.mbridge_config.memory_efficient=True ++actor_rollout_ref.actor.checkpoint.async_save=True +actor_rollout_ref.actor.model.override_model_config.model_config="{text_config:{dtype:float16}}" ) ROLLOUT=( actor_rollout_ref.rollout.name=vllm actor_rollout_ref.rollout.tensor_model_parallel_size=2 actor_rollout_ref.rollout.gpu_memory_utilization=0.7 actor_rollout_ref.rollout.n=4 actor_rollout_ref.rollout.mode=async actor_rollout_ref.rollout.enforce_eager=True actor_rollout_ref.rollout.dtype=${dtype} actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=1 actor_rollout_ref.rollout.log_prob_use_dynamic_bsz=False actor_rollout_ref.rollout.log_prob_max_token_len_per_gpu=2560 actor_rollout_ref.rollout.enable_chunked_prefill=True actor_rollout_ref.rollout.max_num_batched_tokens=2560 actor_rollout_ref.rollout.temperature=1.0 actor_rollout_ref.rollout.top_p=0.9 actor_rollout_ref.rollout.top_k=-1 +actor_rollout_ref.rollout.repetition_penalty=1.0 +actor_rollout_ref.rollout.val_kwargs.repetition_penalty=1.05 actor_rollout_ref.rollout.val_kwargs.do_sample=False actor_rollout_ref.rollout.val_kwargs.n=1 actor_rollout_ref.rollout.free_cache_engine=True actor_rollout_ref.rollout.max_num_seqs=256 ) REF=( actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=1 actor_rollout_ref.ref.log_prob_use_dynamic_bsz=False actor_rollout_ref.ref.log_prob_max_token_len_per_gpu=2560 actor_rollout_ref.ref.megatron.tensor_model_parallel_size=1 actor_rollout_ref.ref.megatron.pipeline_model_parallel_size=2 actor_rollout_ref.ref.megatron.context_parallel_size=1 actor_rollout_ref.ref.megatron.expert_model_parallel_size=8 actor_rollout_ref.ref.megatron.expert_tensor_parallel_size=1 actor_rollout_ref.ref.megatron.virtual_pipeline_model_parallel_size=null actor_rollout_ref.ref.megatron.param_offload=${ALL_OFFLOAD} ) ALGORITHM=( algorithm.adv_estimator=grpo algorithm.use_kl_in_reward=False algorithm.kl_ctrl.kl_coef=0.0 )
TRAINER=( trainer.critic_warmup=0 trainer.logger='["console","wandb"]' trainer.project_name=${project_name} trainer.experiment_name=${exp_name} trainer.n_gpus_per_node=8 trainer.nnodes=2 trainer.save_freq=100 trainer.val_before_train=False trainer.test_freq=5 trainer.total_epochs=5 trainer.default_local_dir=${output} trainer.rollout_data_dir=${output}/rollout_data trainer.validation_data_dir=${output}/validation_data trainer.log_val_generations=5 reward.num_workers=8 )
@shinesun07 May I ask which image version you are using?
不是镜像,自定义环境:
absl-py 2.4.0
accelerate 1.13.0
aiohappyeyeballs 2.6.1
aiohttp 3.13.3
aiohttp-cors 0.8.1
aiosignal 1.4.0
annotated-doc 0.0.4
annotated-types 0.7.0
anthropic 0.86.0
antlr4-python3-runtime 4.9.3
anyio 4.12.1
apache-tvm-ffi 0.1.9
apex 0.1
astor 0.8.1
async-timeout 5.0.1
attrs 25.4.0
av 16.1.0
blake3 1.0.8
cachetools 7.0.5
causal-conv1d 1.6.1
cbor2 5.8.0
certifi 2026.2.25
cffi 2.0.0
charset-normalizer 3.4.6
click 8.3.1
cloudpickle 3.1.2
codetiming 1.4.0
colorful 0.5.8
compressed-tensors 0.13.0
cryptography 46.0.5
cuda-bindings 12.9.4
cuda-pathfinder 1.4.3
cuda-python 12.9.4
cupy-cuda12x 14.0.1
datasets 4.7.0
depyf 0.20.0
dill 0.4.1
diskcache 5.6.3
distlib 0.4.0
distro 1.9.0
dnspython 2.8.0
docstring-parser 0.17.0
einops 0.8.2
email-validator 2.3.0
exceptiongroup 1.3.1
fastapi 0.135.1
fastapi-cli 0.0.24
fastapi-cloud-cli 0.15.0
fastar 0.8.0
filelock 3.25.2
fla-core 0.4.1
flash-attn 2.8.3
flash-linear-attention 0.4.1
flashinfer-python 0.6.4
frozenlist 1.8.0
fsspec 2026.2.0
gguf 0.18.0
gitdb 4.0.12
gitpython 3.1.46
google-api-core 2.30.0
google-auth 2.49.0
googleapis-common-protos 1.73.0
grpcio 1.78.0
grpcio-reflection 1.78.0
h11 0.16.0
hf-xet 1.4.2
httpcore 1.0.9
httptools 0.7.1
httpx 0.28.1
httpx-sse 0.4.3
huggingface-hub 1.7.1
hydra-core 1.3.2
idna 3.11
ijson 3.5.0
importlib-metadata 8.7.1
interegular 0.3.3
jinja2 3.1.6
jiter 0.13.0
jmespath 1.1.0
jsonschema 4.26.0
jsonschema-specifications 2025.9.1
kaldi-native-fbank 1.22.3
lark 1.2.2
llguidance 1.3.0
llvmlite 0.44.0
lm-format-enforcer 0.11.3
loguru 0.7.3
markdown 3.10.2
markdown-it-py 4.0.0
markupsafe 3.0.3
mbridge 0.15.1
mcp 1.26.0
mdurl 0.1.2
megatron-core 0.16.0
mistral-common 1.10.0
ml-dtypes 0.5.4
model-hosting-container-standards 0.1.14
mpmath 1.3.0
msgpack 1.1.2
msgspec 0.20.0
multidict 6.7.1
multiprocess 0.70.18
networkx 3.4.2
ninja 1.13.0
numba 0.61.2
numpy 2.2.6
nvdlfw-inspect 0.2.2
nvidia-cublas-cu12 12.8.4.1
nvidia-cuda-cupti-cu12 12.8.90
nvidia-cuda-nvrtc-cu12 12.8.93
nvidia-cuda-runtime-cu12 12.8.90
nvidia-cudnn-cu12 9.10.2.21
nvidia-cudnn-frontend 1.18.0
nvidia-cufft-cu12 11.3.3.83
nvidia-cufile-cu12 1.13.1.3
nvidia-curand-cu12 10.3.9.90
nvidia-cusolver-cu12 11.7.3.90
nvidia-cusparse-cu12 12.5.8.93
nvidia-cusparselt-cu12 0.7.1
nvidia-cutlass-dsl 4.4.2
nvidia-cutlass-dsl-libs-base 4.4.2
nvidia-ml-py 13.590.48
nvidia-nccl-cu12 2.27.5
nvidia-nvjitlink-cu12 12.8.93
nvidia-nvshmem-cu12 3.4.5
nvidia-nvtx-cu12 12.8.90
omegaconf 2.3.0
onnx 1.20.1
onnx-ir 0.2.0
onnxscript 0.6.2
openai 2.24.0
openai-harmony 0.0.8
opencensus 0.11.4
opencensus-context 0.1.3
opencv-python-headless 4.13.0.92
opentelemetry-api 1.40.0
opentelemetry-exporter-otlp 1.40.0
opentelemetry-exporter-otlp-proto-common 1.40.0
opentelemetry-exporter-otlp-proto-grpc 1.40.0
opentelemetry-exporter-otlp-proto-http 1.40.0
opentelemetry-exporter-prometheus 0.61b0
opentelemetry-proto 1.40.0
opentelemetry-sdk 1.40.0
opentelemetry-semantic-conventions 0.61b0
opentelemetry-semantic-conventions-ai 0.4.15
orjson 3.11.7
outlines-core 0.2.11
packaging 26.0
pandas 2.3.3
partial-json-parser 0.2.1.1.post7
peft 0.18.1
pillow 12.1.1
pip 26.0.1
platformdirs 4.9.4
prometheus-client 0.24.1
prometheus-fastapi-instrumentator 7.1.0
propcache 0.4.1
proto-plus 1.27.1
protobuf 6.33.6
psutil 7.2.2
py-cpuinfo 9.0.0
py-spy 0.4.1
pyarrow 23.0.1
pyasn1 0.6.2
pyasn1-modules 0.4.2
pybase64 1.4.3
pybind11 3.0.2
pycountry 26.2.16
pycparser 3.0
pydantic 2.12.5
pydantic-core 2.41.5
pydantic-extra-types 2.11.1
pydantic-settings 2.13.1
pygments 2.19.2
pyjwt 2.12.1
pylatexenc 2.10
python-dateutil 2.9.0.post0
python-discovery 1.1.3
python-dotenv 1.2.2
python-json-logger 4.0.0
python-multipart 0.0.22
pytz 2026.1.post1
pyvers 0.1.0
pyyaml 6.0.3
pyzmq 27.1.0
quack-kernels 0.3.4
qwen-vl-utils 0.0.14
ray 2.54.0
referencing 0.37.0
regex 2026.2.28
requests 2.32.5
rich 14.3.3
rich-toolkit 0.19.7
rignore 0.7.6
rpds-py 0.30.0
rsa 4.9.1
safetensors 0.7.0
sentencepiece 0.2.1
sentry-sdk 2.55.0
setproctitle 1.3.7
setuptools 82.0.1
shellingham 1.5.4
six 1.17.0
smart-open 7.5.1
smmap 5.0.3
sniffio 1.3.1
sse-starlette 3.3.3
starlette 0.52.1
supervisor 4.3.0
sympy 1.14.0
tabulate 0.10.0
tensorboard 2.20.0
tensorboard-data-server 0.7.2
tensordict 0.10.0
tiktoken 0.12.0
tokenizers 0.22.2
tomli 2.4.0
torch 2.10.0+cu128
torch-c-dlpack-ext 0.1.5
torchaudio 2.10.0+cu128
torchdata 0.11.0
torchvision 0.25.0+cu128
tqdm 4.67.3
transformer-engine 2.12.0
transformer-engine-cu12 2.12.0
transformer-engine-torch 2.12.0
transformers 5.3.0
triton 3.6.0
typer 0.24.1
typer-slim 0.24.0
typing-extensions 4.15.0
typing-inspection 0.4.2
tzdata 2025.3
urllib3 2.6.3
uvicorn 0.42.0
uvloop 0.22.1
verl 0.8.0.dev0
virtualenv 21.2.0
vllm 0.17.1
wandb 0.25.1
watchfiles 1.1.1
websockets 16.0
werkzeug 3.1.6
wrapt 2.1.2
xgrammar 0.1.29
xxhash 3.6.0
yarl 1.23.0
zipp 3.23.0