verl 0.6.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (379) hide show
  1. scripts/__init__.py +13 -0
  2. scripts/converter_hf_to_mcore.py +562 -0
  3. scripts/diagnose.py +312 -0
  4. scripts/init_random_model.py +95 -0
  5. scripts/legacy_model_merger.py +781 -0
  6. scripts/print_cfg.py +35 -0
  7. scripts/rollout_viewer.py +565 -0
  8. tests/__init__.py +13 -0
  9. tests/interactions/__init__.py +15 -0
  10. tests/interactions/test_gsm8k_interaction.py +422 -0
  11. tests/interactions/test_interaction_registry.py +206 -0
  12. tests/single_controller/__init__.py +13 -0
  13. tests/single_controller/test_auto_padding_on_cpu.py +152 -0
  14. tests/single_controller/test_colocated_workers.py +83 -0
  15. tests/single_controller/test_colocated_workers_fused.py +83 -0
  16. tests/single_controller/test_data_transfer.py +107 -0
  17. tests/single_controller/test_decorator_on_cpu.py +141 -0
  18. tests/single_controller/test_device_mesh_register.py +100 -0
  19. tests/single_controller/test_driverfunc_to_worker.py +84 -0
  20. tests/single_controller/test_fused_workers_on_cpu.py +90 -0
  21. tests/single_controller/test_high_level_scheduling_api.py +86 -0
  22. tests/single_controller/test_nested_worker.py +68 -0
  23. tests/single_controller/test_ray_collectives.py +113 -0
  24. tests/single_controller/test_ray_local_envs_on_cpu.py +91 -0
  25. tests/single_controller/test_ray_utils_on_cpu.py +54 -0
  26. tests/single_controller/test_rvdz.py +51 -0
  27. tests/single_controller/test_worker_group_basics.py +130 -0
  28. tests/single_controller/test_worker_group_torch.py +111 -0
  29. tests/special_e2e/__init__.py +13 -0
  30. tests/special_e2e/check_custom_rwd_fn.py +33 -0
  31. tests/special_e2e/check_results.py +53 -0
  32. tests/special_e2e/envs/__init__.py +17 -0
  33. tests/special_e2e/envs/digit_completion/__init__.py +22 -0
  34. tests/special_e2e/envs/digit_completion/task.py +179 -0
  35. tests/special_e2e/envs/digit_completion/tokenizer.py +155 -0
  36. tests/test_base_config_on_cpu.py +42 -0
  37. tests/test_protocol_on_cpu.py +994 -0
  38. tests/test_protocol_v2_on_cpu.py +595 -0
  39. tests/trainer/__init__.py +16 -0
  40. tests/trainer/config/__init__.py +13 -0
  41. tests/trainer/config/test_algo_config_on_cpu.py +204 -0
  42. tests/trainer/config/test_legacy_config_on_cpu.py +176 -0
  43. tests/trainer/ppo/__init__.py +16 -0
  44. tests/trainer/ppo/test_core_algos_on_cpu.py +317 -0
  45. tests/trainer/ppo/test_metric_utils_on_cpu.py +324 -0
  46. tests/trainer/ppo/test_rollout_is.py +289 -0
  47. tests/trainer/ppo/test_rollout_is_integration.py +241 -0
  48. verl/__init__.py +100 -0
  49. verl/base_config.py +86 -0
  50. verl/experimental/__init__.py +13 -0
  51. verl/experimental/agent_loop/__init__.py +21 -0
  52. verl/experimental/agent_loop/agent_loop.py +905 -0
  53. verl/experimental/agent_loop/single_turn_agent_loop.py +64 -0
  54. verl/experimental/agent_loop/tool_agent_loop.py +469 -0
  55. verl/experimental/agent_loop/tool_parser.py +161 -0
  56. verl/experimental/dataset/__init__.py +13 -0
  57. verl/experimental/dataset/sampler.py +40 -0
  58. verl/experimental/dynamic_dataset/__init__.py +13 -0
  59. verl/experimental/dynamic_dataset/dynamicgen_dataset.py +112 -0
  60. verl/interactions/__init__.py +15 -0
  61. verl/interactions/base.py +72 -0
  62. verl/interactions/gsm8k_interaction.py +87 -0
  63. verl/interactions/utils/__init__.py +14 -0
  64. verl/interactions/utils/interaction_registry.py +85 -0
  65. verl/interactions/weather_interaction.py +79 -0
  66. verl/model_merger/__init__.py +13 -0
  67. verl/model_merger/__main__.py +73 -0
  68. verl/model_merger/base_model_merger.py +362 -0
  69. verl/model_merger/fsdp_model_merger.py +265 -0
  70. verl/model_merger/megatron_model_merger.py +546 -0
  71. verl/models/__init__.py +13 -0
  72. verl/models/llama/__init__.py +13 -0
  73. verl/models/llama/megatron/__init__.py +34 -0
  74. verl/models/llama/megatron/checkpoint_utils/__init__.py +13 -0
  75. verl/models/llama/megatron/checkpoint_utils/llama_loader.py +317 -0
  76. verl/models/llama/megatron/checkpoint_utils/llama_loader_depracated.py +458 -0
  77. verl/models/llama/megatron/checkpoint_utils/llama_saver.py +442 -0
  78. verl/models/llama/megatron/layers/__init__.py +34 -0
  79. verl/models/llama/megatron/layers/parallel_attention.py +460 -0
  80. verl/models/llama/megatron/layers/parallel_decoder.py +150 -0
  81. verl/models/llama/megatron/layers/parallel_linear.py +106 -0
  82. verl/models/llama/megatron/layers/parallel_mlp.py +74 -0
  83. verl/models/llama/megatron/layers/parallel_rmsnorm.py +48 -0
  84. verl/models/llama/megatron/modeling_llama_megatron.py +688 -0
  85. verl/models/mcore/__init__.py +32 -0
  86. verl/models/mcore/config_converter.py +396 -0
  87. verl/models/mcore/loader.py +495 -0
  88. verl/models/mcore/mbridge.py +23 -0
  89. verl/models/mcore/model_forward.py +207 -0
  90. verl/models/mcore/model_forward_fused.py +326 -0
  91. verl/models/mcore/model_initializer.py +276 -0
  92. verl/models/mcore/patch_v012.py +215 -0
  93. verl/models/mcore/qwen2_5_vl/__init__.py +21 -0
  94. verl/models/mcore/qwen2_5_vl/attention.py +224 -0
  95. verl/models/mcore/qwen2_5_vl/model.py +340 -0
  96. verl/models/mcore/qwen2_5_vl/rope_utils.py +266 -0
  97. verl/models/mcore/qwen2_5_vl/vision_config.py +85 -0
  98. verl/models/mcore/qwen2_5_vl/vision_model.py +309 -0
  99. verl/models/mcore/qwen2_5_vl/vision_transformer_block.py +265 -0
  100. verl/models/mcore/registry.py +276 -0
  101. verl/models/mcore/saver.py +497 -0
  102. verl/models/mcore/util.py +405 -0
  103. verl/models/mcore/weight_converter.py +479 -0
  104. verl/models/qwen2/__init__.py +13 -0
  105. verl/models/qwen2/megatron/__init__.py +34 -0
  106. verl/models/qwen2/megatron/checkpoint_utils/__init__.py +13 -0
  107. verl/models/qwen2/megatron/checkpoint_utils/qwen2_loader.py +337 -0
  108. verl/models/qwen2/megatron/checkpoint_utils/qwen2_loader_depracated.py +475 -0
  109. verl/models/qwen2/megatron/checkpoint_utils/qwen2_saver.py +448 -0
  110. verl/models/qwen2/megatron/layers/__init__.py +26 -0
  111. verl/models/qwen2/megatron/layers/parallel_attention.py +399 -0
  112. verl/models/qwen2/megatron/layers/parallel_decoder.py +150 -0
  113. verl/models/qwen2/megatron/layers/parallel_linear.py +79 -0
  114. verl/models/qwen2/megatron/layers/parallel_mlp.py +74 -0
  115. verl/models/qwen2/megatron/layers/parallel_rmsnorm.py +48 -0
  116. verl/models/qwen2/megatron/modeling_qwen2_megatron.py +737 -0
  117. verl/models/registry.py +62 -0
  118. verl/models/transformers/__init__.py +13 -0
  119. verl/models/transformers/apertus.py +118 -0
  120. verl/models/transformers/dense_common.py +193 -0
  121. verl/models/transformers/glm4v.py +533 -0
  122. verl/models/transformers/kimi_vl.py +192 -0
  123. verl/models/transformers/llama.py +241 -0
  124. verl/models/transformers/monkey_patch.py +425 -0
  125. verl/models/transformers/npu_patch.py +207 -0
  126. verl/models/transformers/qwen2.py +243 -0
  127. verl/models/transformers/qwen2_vl.py +548 -0
  128. verl/models/transformers/qwen3_vl.py +336 -0
  129. verl/models/weight_loader_registry.py +57 -0
  130. verl/protocol.py +1237 -0
  131. verl/py.typed +0 -0
  132. verl/single_controller/__init__.py +26 -0
  133. verl/single_controller/base/__init__.py +18 -0
  134. verl/single_controller/base/decorator.py +446 -0
  135. verl/single_controller/base/worker.py +313 -0
  136. verl/single_controller/base/worker_group.py +255 -0
  137. verl/single_controller/ray/__init__.py +29 -0
  138. verl/single_controller/ray/base.py +888 -0
  139. verl/third_party/__init__.py +13 -0
  140. verl/third_party/sglang/__init__.py +26 -0
  141. verl/third_party/sglang/parallel_state.py +328 -0
  142. verl/third_party/torch/__init__.py +87 -0
  143. verl/third_party/torch/distributed/__init__.py +87 -0
  144. verl/third_party/torch/distributed/_state_dict_utils.py +840 -0
  145. verl/third_party/torch/distributed/checkpoint/__init__.py +87 -0
  146. verl/third_party/torch/distributed/checkpoint/state_dict.py +1493 -0
  147. verl/third_party/vllm/__init__.py +64 -0
  148. verl/tools/__init__.py +14 -0
  149. verl/tools/base_tool.py +93 -0
  150. verl/tools/geo3k_tool.py +101 -0
  151. verl/tools/gsm8k_tool.py +110 -0
  152. verl/tools/image_zoom_in_tool.py +392 -0
  153. verl/tools/mcp_base_tool.py +117 -0
  154. verl/tools/mcp_search_tool.py +69 -0
  155. verl/tools/sandbox_fusion_tools.py +195 -0
  156. verl/tools/schemas.py +123 -0
  157. verl/tools/search_tool.py +279 -0
  158. verl/tools/utils/__init__.py +14 -0
  159. verl/tools/utils/search_r1_like_utils.py +245 -0
  160. verl/tools/utils/tool_registry.py +130 -0
  161. verl/trainer/__init__.py +13 -0
  162. verl/trainer/config/__init__.py +19 -0
  163. verl/trainer/config/_generated_ppo_megatron_trainer.yaml +548 -0
  164. verl/trainer/config/_generated_ppo_trainer.yaml +532 -0
  165. verl/trainer/config/actor/actor.yaml +212 -0
  166. verl/trainer/config/actor/dp_actor.yaml +42 -0
  167. verl/trainer/config/actor/megatron_actor.yaml +20 -0
  168. verl/trainer/config/algorithm.py +105 -0
  169. verl/trainer/config/config.py +77 -0
  170. verl/trainer/config/critic/critic.yaml +176 -0
  171. verl/trainer/config/critic/dp_critic.yaml +65 -0
  172. verl/trainer/config/critic/megatron_critic.yaml +43 -0
  173. verl/trainer/config/data/legacy_data.yaml +112 -0
  174. verl/trainer/config/engine/fsdp.yaml +53 -0
  175. verl/trainer/config/engine/megatron.yaml +78 -0
  176. verl/trainer/config/evaluation.yaml +15 -0
  177. verl/trainer/config/generation.yaml +58 -0
  178. verl/trainer/config/model/hf_model.yaml +64 -0
  179. verl/trainer/config/npu_profile/npu_profile.yaml +34 -0
  180. verl/trainer/config/optim/fsdp.yaml +35 -0
  181. verl/trainer/config/optim/megatron.yaml +49 -0
  182. verl/trainer/config/ppo_megatron_trainer.yaml +195 -0
  183. verl/trainer/config/ppo_trainer.yaml +330 -0
  184. verl/trainer/config/ref/dp_ref.yaml +26 -0
  185. verl/trainer/config/ref/megatron_ref.yaml +19 -0
  186. verl/trainer/config/ref/ref.yaml +99 -0
  187. verl/trainer/config/reward_model/dp_reward_model.yaml +55 -0
  188. verl/trainer/config/reward_model/megatron_reward_model.yaml +65 -0
  189. verl/trainer/config/reward_model/reward_model.yaml +97 -0
  190. verl/trainer/config/rollout/rollout.yaml +297 -0
  191. verl/trainer/config/sft_trainer.yaml +85 -0
  192. verl/trainer/config/sft_trainer_engine.yaml +68 -0
  193. verl/trainer/constants_ppo.py +52 -0
  194. verl/trainer/fsdp_sft_trainer.py +846 -0
  195. verl/trainer/main_eval.py +80 -0
  196. verl/trainer/main_generation.py +153 -0
  197. verl/trainer/main_generation_server.py +193 -0
  198. verl/trainer/main_ppo.py +412 -0
  199. verl/trainer/ppo/__init__.py +13 -0
  200. verl/trainer/ppo/core_algos.py +1531 -0
  201. verl/trainer/ppo/metric_utils.py +490 -0
  202. verl/trainer/ppo/mismatch_helper.py +459 -0
  203. verl/trainer/ppo/ray_trainer.py +1288 -0
  204. verl/trainer/ppo/reward.py +192 -0
  205. verl/trainer/ppo/utils.py +65 -0
  206. verl/trainer/sft_trainer.py +393 -0
  207. verl/utils/__init__.py +25 -0
  208. verl/utils/activation_offload.py +558 -0
  209. verl/utils/attention_utils.py +100 -0
  210. verl/utils/checkpoint/__init__.py +17 -0
  211. verl/utils/checkpoint/checkpoint_handler.py +204 -0
  212. verl/utils/checkpoint/checkpoint_manager.py +238 -0
  213. verl/utils/checkpoint/fsdp_checkpoint_manager.py +367 -0
  214. verl/utils/checkpoint/megatron_checkpoint_manager.py +557 -0
  215. verl/utils/config.py +197 -0
  216. verl/utils/dataset/__init__.py +19 -0
  217. verl/utils/dataset/dataset_utils.py +70 -0
  218. verl/utils/dataset/multiturn_sft_dataset.py +375 -0
  219. verl/utils/dataset/rl_dataset.py +383 -0
  220. verl/utils/dataset/rm_dataset.py +144 -0
  221. verl/utils/dataset/sft_dataset.py +186 -0
  222. verl/utils/dataset/vision_utils.py +117 -0
  223. verl/utils/debug/__init__.py +17 -0
  224. verl/utils/debug/metrics.py +109 -0
  225. verl/utils/debug/performance.py +17 -0
  226. verl/utils/debug/trajectory_tracker.py +109 -0
  227. verl/utils/device.py +95 -0
  228. verl/utils/distributed.py +90 -0
  229. verl/utils/experimental/__init__.py +13 -0
  230. verl/utils/experimental/torch_functional.py +216 -0
  231. verl/utils/flops_counter.py +396 -0
  232. verl/utils/fs.py +305 -0
  233. verl/utils/fsdp_utils.py +694 -0
  234. verl/utils/groupwise.py +223 -0
  235. verl/utils/hdfs_io.py +149 -0
  236. verl/utils/import_utils.py +156 -0
  237. verl/utils/kernel/__init__.py +31 -0
  238. verl/utils/kernel/kernels.py +1586 -0
  239. verl/utils/kernel/linear_cross_entropy.py +119 -0
  240. verl/utils/logger/__init__.py +32 -0
  241. verl/utils/logger/aggregate_logger.py +140 -0
  242. verl/utils/logging_utils.py +32 -0
  243. verl/utils/megatron/__init__.py +13 -0
  244. verl/utils/megatron/dist_checkpointing.py +56 -0
  245. verl/utils/megatron/memory.py +38 -0
  246. verl/utils/megatron/optimizer.py +108 -0
  247. verl/utils/megatron/pipeline_parallel.py +71 -0
  248. verl/utils/megatron/sequence_parallel.py +52 -0
  249. verl/utils/megatron/tensor_parallel.py +186 -0
  250. verl/utils/megatron_utils.py +1107 -0
  251. verl/utils/memory_buffer.py +218 -0
  252. verl/utils/memory_utils.py +292 -0
  253. verl/utils/metric/__init__.py +17 -0
  254. verl/utils/metric/utils.py +54 -0
  255. verl/utils/model.py +743 -0
  256. verl/utils/net_utils.py +61 -0
  257. verl/utils/npu_utils.py +129 -0
  258. verl/utils/profiler/__init__.py +40 -0
  259. verl/utils/profiler/config.py +156 -0
  260. verl/utils/profiler/empty_annotations.py +40 -0
  261. verl/utils/profiler/mstx_profile.py +271 -0
  262. verl/utils/profiler/nvtx_profile.py +200 -0
  263. verl/utils/profiler/performance.py +240 -0
  264. verl/utils/profiler/profile.py +371 -0
  265. verl/utils/py_functional.py +318 -0
  266. verl/utils/ray_utils.py +81 -0
  267. verl/utils/rendezvous/__init__.py +13 -0
  268. verl/utils/rendezvous/ray_backend.py +73 -0
  269. verl/utils/reward_score/__init__.py +134 -0
  270. verl/utils/reward_score/geo3k.py +36 -0
  271. verl/utils/reward_score/gsm8k.py +72 -0
  272. verl/utils/reward_score/math_batch.py +26 -0
  273. verl/utils/reward_score/math_dapo.py +272 -0
  274. verl/utils/reward_score/math_reward.py +224 -0
  275. verl/utils/reward_score/math_verify.py +39 -0
  276. verl/utils/reward_score/prime_code/__init__.py +73 -0
  277. verl/utils/reward_score/prime_code/testing_util.py +683 -0
  278. verl/utils/reward_score/prime_code/utils.py +60 -0
  279. verl/utils/reward_score/prime_math/__init__.py +411 -0
  280. verl/utils/reward_score/prime_math/grader.py +384 -0
  281. verl/utils/reward_score/prime_math/math_normalize.py +192 -0
  282. verl/utils/reward_score/sandbox_fusion/__init__.py +121 -0
  283. verl/utils/reward_score/sandbox_fusion/utils.py +578 -0
  284. verl/utils/reward_score/search_r1_like_qa_em.py +156 -0
  285. verl/utils/rollout_skip.py +132 -0
  286. verl/utils/rollout_trace.py +237 -0
  287. verl/utils/seqlen_balancing.py +404 -0
  288. verl/utils/tensordict_utils.py +244 -0
  289. verl/utils/tokenizer.py +88 -0
  290. verl/utils/torch_dtypes.py +80 -0
  291. verl/utils/torch_functional.py +777 -0
  292. verl/utils/tracking.py +470 -0
  293. verl/utils/transformers_compat.py +57 -0
  294. verl/utils/ulysses.py +328 -0
  295. verl/utils/vllm/__init__.py +26 -0
  296. verl/utils/vllm/patch.py +113 -0
  297. verl/utils/vllm/utils.py +122 -0
  298. verl/version/version +1 -0
  299. verl/workers/__init__.py +13 -0
  300. verl/workers/actor/__init__.py +18 -0
  301. verl/workers/actor/base.py +66 -0
  302. verl/workers/actor/dp_actor.py +503 -0
  303. verl/workers/actor/megatron_actor.py +679 -0
  304. verl/workers/config/__init__.py +32 -0
  305. verl/workers/config/actor.py +247 -0
  306. verl/workers/config/critic.py +246 -0
  307. verl/workers/config/engine.py +120 -0
  308. verl/workers/config/model.py +154 -0
  309. verl/workers/config/optimizer.py +114 -0
  310. verl/workers/config/reward_model.py +146 -0
  311. verl/workers/config/rollout.py +192 -0
  312. verl/workers/critic/__init__.py +18 -0
  313. verl/workers/critic/base.py +40 -0
  314. verl/workers/critic/dp_critic.py +261 -0
  315. verl/workers/critic/megatron_critic.py +335 -0
  316. verl/workers/engine/__init__.py +33 -0
  317. verl/workers/engine/base.py +263 -0
  318. verl/workers/engine/fsdp/__init__.py +16 -0
  319. verl/workers/engine/fsdp/transformer_impl.py +1010 -0
  320. verl/workers/engine/fsdp/utils.py +61 -0
  321. verl/workers/engine/megatron/__init__.py +17 -0
  322. verl/workers/engine/megatron/transformer_impl.py +673 -0
  323. verl/workers/engine/megatron/utils.py +35 -0
  324. verl/workers/engine/mindspeed/__init__.py +17 -0
  325. verl/workers/engine/mindspeed/transformer_impl.py +45 -0
  326. verl/workers/engine/utils.py +120 -0
  327. verl/workers/fsdp_workers.py +1926 -0
  328. verl/workers/megatron_workers.py +1265 -0
  329. verl/workers/reward_manager/__init__.py +29 -0
  330. verl/workers/reward_manager/abstract.py +45 -0
  331. verl/workers/reward_manager/batch.py +132 -0
  332. verl/workers/reward_manager/dapo.py +153 -0
  333. verl/workers/reward_manager/naive.py +126 -0
  334. verl/workers/reward_manager/prime.py +192 -0
  335. verl/workers/reward_manager/registry.py +55 -0
  336. verl/workers/reward_model/__init__.py +17 -0
  337. verl/workers/reward_model/base.py +58 -0
  338. verl/workers/reward_model/megatron/__init__.py +17 -0
  339. verl/workers/reward_model/megatron/reward_model.py +349 -0
  340. verl/workers/roles/__init__.py +26 -0
  341. verl/workers/roles/actor.py +193 -0
  342. verl/workers/roles/critic.py +212 -0
  343. verl/workers/roles/hybrid_engine.py +13 -0
  344. verl/workers/roles/reward_model.py +203 -0
  345. verl/workers/roles/reward_model_engine/__init__.py +17 -0
  346. verl/workers/roles/reward_model_engine/base.py +94 -0
  347. verl/workers/roles/reward_model_engine/sglang_reward_model.py +283 -0
  348. verl/workers/roles/utils/__init__.py +13 -0
  349. verl/workers/roles/utils/losses.py +138 -0
  350. verl/workers/roles/utils/padding.py +119 -0
  351. verl/workers/rollout/__init__.py +19 -0
  352. verl/workers/rollout/base.py +102 -0
  353. verl/workers/rollout/hf_rollout.py +177 -0
  354. verl/workers/rollout/naive/__init__.py +17 -0
  355. verl/workers/rollout/naive/naive_rollout.py +120 -0
  356. verl/workers/rollout/replica.py +231 -0
  357. verl/workers/rollout/schemas.py +672 -0
  358. verl/workers/rollout/sglang_rollout/__init__.py +12 -0
  359. verl/workers/rollout/sglang_rollout/async_sglang_server.py +302 -0
  360. verl/workers/rollout/sglang_rollout/http_server_engine.py +954 -0
  361. verl/workers/rollout/sglang_rollout/sglang_rollout.py +1615 -0
  362. verl/workers/rollout/sglang_rollout/utils.py +108 -0
  363. verl/workers/rollout/tokenizer.py +163 -0
  364. verl/workers/rollout/utils.py +68 -0
  365. verl/workers/rollout/vllm_rollout/__init__.py +42 -0
  366. verl/workers/rollout/vllm_rollout/vllm_async_server.py +500 -0
  367. verl/workers/rollout/vllm_rollout/vllm_rollout_spmd.py +619 -0
  368. verl/workers/sharding_manager/__init__.py +13 -0
  369. verl/workers/sharding_manager/base.py +35 -0
  370. verl/workers/sharding_manager/fsdp_sglang.py +223 -0
  371. verl/workers/sharding_manager/fsdp_ulysses.py +72 -0
  372. verl/workers/sharding_manager/fsdp_vllm.py +355 -0
  373. verl/workers/sharding_manager/megatron_sglang.py +227 -0
  374. verl/workers/sharding_manager/megatron_vllm.py +227 -0
  375. verl-0.6.0.dist-info/METADATA +330 -0
  376. verl-0.6.0.dist-info/RECORD +379 -0
  377. verl-0.6.0.dist-info/WHEEL +5 -0
  378. verl-0.6.0.dist-info/licenses/LICENSE +202 -0
  379. verl-0.6.0.dist-info/top_level.txt +3 -0
scripts/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
@@ -0,0 +1,562 @@
1
+ # Copyright 2025 Bytedance Ltd. and/or its affiliates
2
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import argparse
17
+ import os
18
+ import warnings
19
+ from contextlib import contextmanager
20
+ from importlib.metadata import version
21
+ from typing import Any, Callable, ContextManager, Optional
22
+
23
+ import numpy as np
24
+ import torch
25
+ import torch.distributed as dist
26
+
27
+ try:
28
+ # NPU patch
29
+ import mindspeed.megatron_adaptor # noqa: F401
30
+ except ImportError:
31
+ pass
32
+
33
+ from accelerate import init_empty_weights
34
+ from megatron.core import dist_checkpointing
35
+ from megatron.core import parallel_state as mpu
36
+ from megatron.core.dist_checkpointing.mapping import ShardedTensor
37
+ from megatron.core.dist_checkpointing.serialization import StrictHandling
38
+ from megatron.core.models.gpt.gpt_model import ModelType
39
+ from megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seed
40
+ from packaging.version import Version
41
+ from transformers import AutoConfig
42
+
43
+ from verl.model_merger.megatron_model_merger import get_dynamic_pipeline_shards
44
+ from verl.models.mcore import hf_to_mcore_config
45
+ from verl.utils.device import get_device_name, get_torch_device
46
+ from verl.utils.megatron_utils import get_model
47
+
48
+
49
+ def _init_args():
50
+ """
51
+ Examples:
52
+
53
+ 1. single rank conversion for any model:
54
+ > python converter_hf_to_mcore.py --hf_model_path %{hf_model} --output_path ${output_path}
55
+ 2. distributed conversion for DeepseekV3 671B:
56
+ > torchrun --nproc_per_node 1 --nnodes 4 --node_rank ${RANK} converter_hf_to_mcore.py \
57
+ --hf_model_path %{hf_model} --output_path ${output_path}
58
+ """
59
+ parser = argparse.ArgumentParser()
60
+ parser.add_argument("--hf_model_path", type=str, required=True, help="The path for the huggingface model")
61
+ parser.add_argument("--output_path", type=str, required=True, help="The path for the output mcore model")
62
+ parser.add_argument("--use_cpu_initialization", action="store_true", help="Whether to use cpu initialization")
63
+ parser.add_argument("--test", action="store_true", help="Whether to test the conversion")
64
+ parser.add_argument("--trust_remote_code", action="store_true", help="Whether to trust remote code")
65
+ args = parser.parse_args()
66
+ return args
67
+
68
+
69
+ def test_conversion(megatron_model_provider, tfconfig, output_path, model):
70
+ ########### test ###########
71
+ # load model
72
+ model_test = get_model(
73
+ model_provider_func=megatron_model_provider,
74
+ model_type=ModelType.encoder_or_decoder,
75
+ wrap_with_ddp=True,
76
+ transformer_config=tfconfig,
77
+ )
78
+ ref_state_dict = model_test[0].module.sharded_state_dict()
79
+ dist_checkpointing.load(ref_state_dict, output_path, strict=StrictHandling.ASSUME_OK_UNEXPECTED)
80
+
81
+ dut_state_dict = model[0].module.state_dict()
82
+ for name in dut_state_dict.keys():
83
+ if dut_state_dict[name] is None:
84
+ print(f"[Warning] {name} is none in dut_state_dict")
85
+ continue
86
+ dut_data = dut_state_dict[name].data
87
+ if name in ref_state_dict:
88
+ ref_data = ref_state_dict[name]
89
+ if isinstance(ref_data, ShardedTensor):
90
+ ref_data = ref_data.data.view(ref_data.local_shape)
91
+ else:
92
+ ref_data = ref_data.data
93
+ assert dut_data.shape == ref_data.shape, f"{name=} {dut_data.shape=} {ref_data.shape=}"
94
+ assert (dut_data == ref_data).all(), f"{name} is not equal"
95
+ print(f"{name} is equal")
96
+ else:
97
+ print(f"[Warning] {name} is not in ref_state_dict")
98
+ for name in ref_state_dict.keys():
99
+ if ref_state_dict[name] is None:
100
+ print(f"[Warning] {name} is none in ref_state_dict")
101
+ continue
102
+ ref_data = ref_state_dict[name]
103
+ if isinstance(ref_data, ShardedTensor):
104
+ ref_data = ref_data.data.view(ref_data.local_shape)
105
+ else:
106
+ ref_data = ref_data.data
107
+ if name in dut_state_dict:
108
+ dut_data = dut_state_dict[name].data
109
+ assert dut_data.shape == ref_data.shape, f"{name=} {dut_data.shape=} {ref_data.shape=}"
110
+ assert (dut_data == ref_data).all(), f"{name} is not equal"
111
+ print(f"{name} is equal")
112
+ else:
113
+ print(f"[Warning] {name} is not in dut_state_dict")
114
+ print("Conversion test passed!")
115
+
116
+
117
+ @torch.inference_mode()
118
+ def convert_checkpoint_from_transformers_to_megatron(
119
+ hf_model, model, hf_config, layer_start_end: Optional[tuple[int, int]] = None
120
+ ):
121
+ if layer_start_end is None:
122
+ layer_start_end = (0, len(model.decoder.layers))
123
+ layer_start, layer_end = layer_start_end
124
+ pp_rank = mpu.get_pipeline_model_parallel_rank()
125
+ pp_size = mpu.get_pipeline_model_parallel_world_size()
126
+ numel = 0
127
+
128
+ num_attention_heads = hf_config.num_attention_heads
129
+ num_key_value_heads = hf_config.num_key_value_heads
130
+ hidden_dim = hf_config.hidden_size
131
+ head_dim = getattr(hf_config, "head_dim", hidden_dim // num_attention_heads)
132
+ if num_attention_heads != num_key_value_heads:
133
+ print("[WARNING] Converting GQA model")
134
+ has_qkv_bias = getattr(hf_config, "qkv_bias", False) or getattr(hf_config, "attention_bias", False)
135
+ has_share_expert = getattr(hf_config, "shared_expert_intermediate_size", None)
136
+ if pp_rank == 0:
137
+ numel += safe_copy(hf_model.model.embed_tokens.weight, model.embedding.word_embeddings.weight)
138
+
139
+ assert len(model.decoder.layers) == (layer_end - layer_start), (
140
+ f"Expected {len(model.decoder.layers)} layers, but got {layer_end - layer_start}"
141
+ )
142
+ for layer_idx, (layer, hf_layer) in enumerate(
143
+ zip(model.decoder.layers, hf_model.model.layers[layer_start:layer_end], strict=True)
144
+ ):
145
+ global_layer_idx = layer_idx + layer_start
146
+ numel_cur = numel
147
+ numel += safe_copy(hf_layer.input_layernorm.weight, layer.self_attention.linear_qkv.layer_norm_weight)
148
+
149
+ q = hf_layer.self_attn.q_proj.weight.view(
150
+ [num_key_value_heads, head_dim * num_attention_heads // num_key_value_heads, -1]
151
+ )
152
+ k = hf_layer.self_attn.k_proj.weight.view([num_key_value_heads, head_dim, -1])
153
+ v = hf_layer.self_attn.v_proj.weight.view([num_key_value_heads, head_dim, -1])
154
+ qkv = torch.cat([q, k, v], dim=1).view(-1, hidden_dim).contiguous()
155
+ numel += safe_copy(qkv, layer.self_attention.linear_qkv.weight)
156
+
157
+ if has_qkv_bias:
158
+ q_bias = hf_layer.self_attn.q_proj.bias.view([num_key_value_heads, -1])
159
+ k_bias = hf_layer.self_attn.k_proj.bias.view([num_key_value_heads, -1])
160
+ v_bias = hf_layer.self_attn.v_proj.bias.view([num_key_value_heads, -1])
161
+ qkv_bias = torch.cat([q_bias, k_bias, v_bias], dim=1).view(-1).contiguous()
162
+ numel += safe_copy(qkv_bias, layer.self_attention.linear_qkv.bias)
163
+
164
+ if hasattr(hf_layer.self_attn, "q_norm"):
165
+ numel += safe_copy(hf_layer.self_attn.q_norm.weight.data, layer.self_attention.q_layernorm.weight)
166
+ numel += safe_copy(hf_layer.self_attn.k_norm.weight.data, layer.self_attention.k_layernorm.weight)
167
+
168
+ numel += safe_copy(hf_layer.self_attn.o_proj.weight, layer.self_attention.linear_proj.weight)
169
+ numel += safe_copy(hf_layer.post_attention_layernorm.weight, layer.pre_mlp_layernorm.weight)
170
+
171
+ numel += safe_copy(hf_layer.mlp.gate.weight, layer.mlp.router.weight)
172
+
173
+ for idx, hf_expert in enumerate(hf_layer.mlp.experts):
174
+ fc1_weight = torch.cat([hf_expert.gate_proj.weight, hf_expert.up_proj.weight])
175
+ numel += safe_copy(fc1_weight, layer.mlp.experts.linear_fc1._parameters[f"weight{idx}"])
176
+ numel += safe_copy(hf_expert.down_proj.weight, layer.mlp.experts.linear_fc2._parameters[f"weight{idx}"])
177
+
178
+ if has_share_expert:
179
+ numel += safe_copy(hf_layer.mlp.shared_expert_gate.weight, layer.mlp.shared_experts.gate_weight)
180
+ shared_fc1_weight = torch.cat(
181
+ [hf_layer.mlp.shared_expert.gate_proj.weight, hf_layer.mlp.shared_expert.up_proj.weight]
182
+ )
183
+ numel += safe_copy(shared_fc1_weight, layer.mlp.shared_experts.linear_fc1.weight)
184
+ numel += safe_copy(hf_layer.mlp.shared_expert.down_proj.weight, layer.mlp.shared_experts.linear_fc2.weight)
185
+ print(f"{pp_rank=} {global_layer_idx=} {layer_idx=} {numel=} numel this layer={numel - numel_cur}")
186
+
187
+ if pp_rank == pp_size - 1:
188
+ numel += safe_copy(hf_model.model.norm.weight, model.decoder.final_layernorm.weight)
189
+ numel += safe_copy(hf_model.lm_head.weight, model.output_layer.weight)
190
+ return numel
191
+
192
+
193
+ def safe_copy(
194
+ src_tensor: torch.Tensor,
195
+ dst_tensor: torch.Tensor,
196
+ skip_dtype_assert: bool = False,
197
+ ):
198
+ if not skip_dtype_assert:
199
+ if src_tensor.dtype != dst_tensor.dtype:
200
+ raise ValueError(f"Get source dtype {src_tensor.dtype}, but target dtype {dst_tensor.dtype}")
201
+ assert src_tensor.shape == dst_tensor.shape
202
+ dst_tensor.data.copy_(src_tensor.data)
203
+ return src_tensor.numel()
204
+
205
+
206
+ @torch.inference_mode()
207
+ def convert_checkpoint_from_transformers_to_megatron_qwen2_5_vl(hfmodel, mgmodel, hf_config):
208
+ mgmodel = mgmodel.bfloat16()
209
+ hfmodel = hfmodel.bfloat16()
210
+ num_attention_heads = hf_config.num_attention_heads
211
+ num_query_groups = hf_config.num_key_value_heads
212
+ hidden_size = hf_config.hidden_size
213
+ head_dim = hidden_size // num_attention_heads
214
+
215
+ # 1. vision model
216
+ if Version(version("transformers")) < Version("4.52.0"):
217
+ print("Using transformers < 4.52 API to load vision model")
218
+ hfvision = hfmodel.visual
219
+ else:
220
+ hfvision = hfmodel.model.visual
221
+ mgvision = mgmodel.vision_model
222
+ vision_hidden_size = mgvision.config.hidden_size
223
+ vision_num_query_groups = mgvision.config.num_query_groups
224
+ vision_head_dim = vision_hidden_size // mgvision.config.num_attention_heads
225
+ copied_numel = 0
226
+ safe_copy(hfvision.rotary_pos_emb.inv_freq, mgvision.rotary_pos_emb.inv_freq)
227
+ copied_numel += safe_copy(hfvision.patch_embed.proj.weight, mgvision.patch_embed.proj.weight)
228
+ for hfblock, mgblock in zip(hfvision.blocks, mgvision.decoder.layers, strict=True):
229
+ # norm1 --> linear_qkv.norm
230
+ copied_numel += safe_copy(hfblock.norm1.weight, mgblock.self_attention.linear_qkv.layer_norm_weight)
231
+ # norm2 --> mlp.linear_fc1.norm
232
+ copied_numel += safe_copy(hfblock.norm2.weight, mgblock.mlp.linear_fc1.layer_norm_weight)
233
+ # qkv --> self_attention.linear_qkv
234
+ converted_weight = (
235
+ hfblock.attn.qkv.weight.view(3, vision_num_query_groups, -1, vision_head_dim, vision_hidden_size)
236
+ .transpose(0, 1)
237
+ .flatten(1, 2)
238
+ .reshape(-1, vision_hidden_size)
239
+ .contiguous()
240
+ )
241
+ copied_numel += safe_copy(converted_weight, mgblock.self_attention.linear_qkv.weight)
242
+ converted_bias = (
243
+ hfblock.attn.qkv.bias.view(3, vision_num_query_groups, -1)
244
+ .transpose(0, 1)
245
+ .flatten(1, 2)
246
+ .view(-1)
247
+ .contiguous()
248
+ )
249
+ copied_numel += safe_copy(converted_bias, mgblock.self_attention.linear_qkv.bias)
250
+ # proj --> self_attention.linear_proj
251
+ copied_numel += safe_copy(hfblock.attn.proj.weight, mgblock.self_attention.linear_proj.weight)
252
+ copied_numel += safe_copy(hfblock.attn.proj.bias, mgblock.self_attention.linear_proj.bias)
253
+ # mlp --> mlp: gate
254
+ fc1_weight = torch.cat([hfblock.mlp.gate_proj.weight, hfblock.mlp.up_proj.weight])
255
+ fc1_bias = torch.cat([hfblock.mlp.gate_proj.bias, hfblock.mlp.up_proj.bias])
256
+ copied_numel += safe_copy(fc1_weight, mgblock.mlp.linear_fc1.weight)
257
+ copied_numel += safe_copy(fc1_bias, mgblock.mlp.linear_fc1.bias)
258
+ copied_numel += safe_copy(hfblock.mlp.down_proj.weight, mgblock.mlp.linear_fc2.weight)
259
+ copied_numel += safe_copy(hfblock.mlp.down_proj.bias, mgblock.mlp.linear_fc2.bias)
260
+
261
+ # 2. vision projector
262
+ hfprojector = hfvision.merger
263
+ mgprojector = mgvision.projection
264
+ copied_numel += safe_copy(hfprojector.ln_q.weight, mgvision.decoder.final_layernorm.weight)
265
+
266
+ copied_numel += safe_copy(hfprojector.mlp[0].weight, mgprojector.encoder.linear_fc1.weight)
267
+ copied_numel += safe_copy(hfprojector.mlp[0].bias, mgprojector.encoder.linear_fc1.bias)
268
+ copied_numel += safe_copy(hfprojector.mlp[2].weight, mgprojector.encoder.linear_fc2.weight)
269
+ copied_numel += safe_copy(hfprojector.mlp[2].bias, mgprojector.encoder.linear_fc2.bias)
270
+ n_params = sum([t.numel() for t in hfvision.state_dict().values()])
271
+ assert n_params == copied_numel, f"n_params={n_params} != copied_numel={copied_numel}"
272
+ # 3. llm [just Qwen2]
273
+ if Version(version("transformers")) < Version("4.52.0"):
274
+ print("Using transformers < 4.52 API to load llm")
275
+ hfllm = hfmodel.model
276
+ else:
277
+ hfllm = hfmodel.model.language_model
278
+ mgllm = mgmodel.language_model
279
+ copied_numel = 0
280
+ copied_numel += safe_copy(hfllm.embed_tokens.weight, mgllm.embedding.word_embeddings.weight)
281
+ layermaps = zip(mgllm.decoder.layers, hfllm.layers, strict=True)
282
+ for mglayer, hflayer in layermaps:
283
+ copied_numel += safe_copy(hflayer.input_layernorm.weight, mglayer.self_attention.linear_qkv.layer_norm_weight)
284
+
285
+ q_proj_weight = hflayer.self_attn.q_proj.weight.view(num_query_groups, -1, head_dim, hidden_size)
286
+ k_proj_weight = hflayer.self_attn.k_proj.weight.view(num_query_groups, -1, head_dim, hidden_size)
287
+ v_proj_weight = hflayer.self_attn.v_proj.weight.view(num_query_groups, -1, head_dim, hidden_size)
288
+ qkv_proj = torch.cat([q_proj_weight, k_proj_weight, v_proj_weight], dim=1).view(-1, hidden_size).contiguous()
289
+ copied_numel += safe_copy(qkv_proj, mglayer.self_attention.linear_qkv.weight)
290
+
291
+ q_proj_bias = hflayer.self_attn.q_proj.bias.view(num_query_groups, -1)
292
+ k_proj_bias = hflayer.self_attn.k_proj.bias.view(num_query_groups, -1)
293
+ v_proj_bias = hflayer.self_attn.v_proj.bias.view(num_query_groups, -1)
294
+ qkv_bias = torch.cat([q_proj_bias, k_proj_bias, v_proj_bias], dim=1).view(-1).contiguous()
295
+ copied_numel += safe_copy(qkv_bias, mglayer.self_attention.linear_qkv.bias)
296
+ copied_numel += safe_copy(hflayer.self_attn.o_proj.weight, mglayer.self_attention.linear_proj.weight)
297
+
298
+ fc1_weight = torch.cat([hflayer.mlp.gate_proj.weight, hflayer.mlp.up_proj.weight])
299
+ copied_numel += safe_copy(fc1_weight, mglayer.mlp.linear_fc1.weight)
300
+
301
+ copied_numel += safe_copy(hflayer.mlp.down_proj.weight, mglayer.mlp.linear_fc2.weight)
302
+ copied_numel += safe_copy(hflayer.post_attention_layernorm.weight, mglayer.mlp.linear_fc1.layer_norm_weight)
303
+
304
+ copied_numel += safe_copy(hfllm.norm.weight, mgllm.decoder.final_layernorm.weight)
305
+ if not hf_config.tie_word_embeddings:
306
+ safe_copy(hfmodel.lm_head.weight, mgllm.output_layer.weight)
307
+
308
+ n_params = sum([t.numel() for t in hfllm.state_dict().values()])
309
+
310
+ assert n_params == copied_numel, f"n_params={n_params} != copied_numel={copied_numel}"
311
+
312
+
313
+ @torch.inference_mode()
314
+ def convert_checkpoint_from_transformers_to_megatron_dpskv3(
315
+ hf_model,
316
+ model,
317
+ hf_config,
318
+ tfconfig,
319
+ layer_start_end: Optional[tuple[int, int]] = None,
320
+ ):
321
+ warnings.warn("MTP model is not supported yet", stacklevel=2)
322
+ if layer_start_end is None:
323
+ layer_start_end = (0, len(model.decoder.layers))
324
+ layer_start, layer_end = layer_start_end
325
+ numel: int = 0
326
+ pp_rank = mpu.get_pipeline_model_parallel_rank()
327
+ pp_size = mpu.get_pipeline_model_parallel_world_size()
328
+ if pp_rank == 0:
329
+ numel += safe_copy(hf_model.model.embed_tokens.weight, model.embedding.word_embeddings.weight)
330
+
331
+ assert len(model.decoder.layers) == (layer_end - layer_start), (
332
+ f"Expected {len(model.decoder.layers)} layers, but got {layer_end - layer_start}"
333
+ )
334
+ for layer_idx, (layer, hf_layer) in enumerate(
335
+ zip(model.decoder.layers, hf_model.model.layers[layer_start:layer_end], strict=True)
336
+ ):
337
+ global_layer_idx = layer_idx + layer_start
338
+ numel_cur: int = numel
339
+ numel += safe_copy(hf_layer.input_layernorm.weight, layer.input_layernorm.weight)
340
+
341
+ if hf_config.q_lora_rank is None:
342
+ numel += safe_copy(hf_layer.self_attn.q_proj.weight, layer.self_attention.linear_q_proj.weight)
343
+ else:
344
+ numel += safe_copy(hf_layer.self_attn.q_a_proj.weight, layer.self_attention.linear_q_down_proj.weight)
345
+ numel += safe_copy(hf_layer.self_attn.q_b_proj.weight, layer.self_attention.linear_q_up_proj.weight)
346
+ numel += safe_copy(
347
+ hf_layer.self_attn.q_a_layernorm.weight, layer.self_attention.linear_q_up_proj.layer_norm_weight
348
+ )
349
+
350
+ numel += safe_copy(
351
+ hf_layer.self_attn.kv_a_proj_with_mqa.weight, layer.self_attention.linear_kv_down_proj.weight
352
+ )
353
+ numel += safe_copy(hf_layer.self_attn.kv_b_proj.weight, layer.self_attention.linear_kv_up_proj.weight)
354
+ numel += safe_copy(
355
+ hf_layer.self_attn.kv_a_layernorm.weight, layer.self_attention.linear_kv_up_proj.layer_norm_weight
356
+ )
357
+ numel += safe_copy(hf_layer.self_attn.o_proj.weight, layer.self_attention.linear_proj.weight)
358
+
359
+ if not hasattr(layer.mlp, "router"):
360
+ numel += safe_copy(hf_layer.post_attention_layernorm.weight, layer.mlp.linear_fc1.layer_norm_weight)
361
+ numel += safe_copy(
362
+ torch.cat([hf_layer.mlp.gate_proj.weight, hf_layer.mlp.up_proj.weight]), layer.mlp.linear_fc1.weight
363
+ )
364
+ numel += safe_copy(hf_layer.mlp.down_proj.weight, layer.mlp.linear_fc2.weight)
365
+ else:
366
+ numel += safe_copy(hf_layer.mlp.gate.weight, layer.mlp.router.weight)
367
+ # NOTE: the e_score_correction_bias in mcore model will be initialized with bfloat16 and \
368
+ # recover to fp32 in the first forward. There is always a diff in the bias between two models (~0.3%)
369
+ numel += safe_copy(
370
+ hf_layer.mlp.gate.e_score_correction_bias, layer.mlp.router.expert_bias, skip_dtype_assert=True
371
+ )
372
+ if tfconfig.moe_grouped_gemm:
373
+ for i, hf_expert in enumerate(hf_layer.mlp.experts):
374
+ fc1_weight = torch.cat([hf_expert.gate_proj.weight, hf_expert.up_proj.weight])
375
+ linear_fc1_weighti = getattr(layer.mlp.experts.linear_fc1, "weight" + str(i))
376
+ numel += safe_copy(fc1_weight, linear_fc1_weighti)
377
+ linear_fc2_weighti = getattr(layer.mlp.experts.linear_fc2, "weight" + str(i))
378
+ numel += safe_copy(hf_expert.down_proj.weight, linear_fc2_weighti)
379
+ else:
380
+ for i, hf_expert in enumerate(hf_layer.mlp.experts):
381
+ expert = layer.mlp.experts.local_experts[i]
382
+ fc1_weight = torch.cat([hf_expert.gate_proj.weight, hf_expert.up_proj.weight])
383
+ numel += safe_copy(fc1_weight, expert.linear_fc1.weight)
384
+ numel += safe_copy(hf_expert.down_proj.weight, expert.linear_fc2.weight)
385
+ numel += safe_copy(hf_layer.post_attention_layernorm.weight, layer.pre_mlp_layernorm.weight)
386
+ shared_fc1_weight = torch.cat(
387
+ [hf_layer.mlp.shared_experts.gate_proj.weight, hf_layer.mlp.shared_experts.up_proj.weight]
388
+ )
389
+ numel += safe_copy(shared_fc1_weight, layer.mlp.shared_experts.linear_fc1.weight)
390
+ numel += safe_copy(hf_layer.mlp.shared_experts.down_proj.weight, layer.mlp.shared_experts.linear_fc2.weight)
391
+ print(f"{pp_rank=} {global_layer_idx=} {layer_idx=} {numel=} numel this layer={numel - numel_cur}")
392
+ assert numel - numel_cur == sum([i.numel() for i in hf_layer.state_dict().values()]), "numel mismatch"
393
+
394
+ if pp_rank == pp_size - 1:
395
+ numel += safe_copy(hf_model.model.norm.weight, model.decoder.final_layernorm.weight)
396
+ if not hf_config.tie_word_embeddings:
397
+ numel += safe_copy(hf_model.lm_head.weight, model.output_layer.weight)
398
+ print(f"{pp_rank=} {numel=}")
399
+ return numel
400
+
401
+
402
+ @contextmanager
403
+ def noop_context() -> Any:
404
+ yield
405
+
406
+
407
+ def support_distributed_convert(hf_config: AutoConfig) -> bool:
408
+ for arch in ["DeepseekV3ForCausalLM", "Qwen3MoeForCausalLM", "Qwen2MoeForCausalLM"]:
409
+ if arch in hf_config.architectures:
410
+ return True
411
+ return False
412
+
413
+
414
+ def convert_hf_to_mcore(hf_model_path, output_path, use_cpu_initialization=False, test=False, trust_remote_code=False):
415
+ os.makedirs(output_path, exist_ok=True)
416
+ if len(os.listdir(output_path)) > 0 and not test:
417
+ print(f"Output path {output_path} is not empty, skipping conversion")
418
+ return
419
+
420
+ # init torch distributed and mpu
421
+ if "WORLD_SIZE" not in os.environ:
422
+ os.environ["RANK"] = "0"
423
+ os.environ["WORLD_SIZE"] = "1"
424
+ os.environ["MASTER_ADDR"] = "localhost"
425
+ os.environ["MASTER_PORT"] = "12355"
426
+
427
+ torch.distributed.init_process_group("nccl")
428
+
429
+ rank = dist.get_rank()
430
+ local_rank = os.getenv("LOCAL_RANK", 0)
431
+ world_size = dist.get_world_size()
432
+ get_torch_device().set_device(f"{get_device_name()}:{local_rank}")
433
+
434
+ mpu.initialize_model_parallel(
435
+ tensor_model_parallel_size=1,
436
+ pipeline_model_parallel_size=world_size,
437
+ virtual_pipeline_model_parallel_size=None,
438
+ context_parallel_size=1,
439
+ expert_model_parallel_size=1,
440
+ )
441
+ model_parallel_cuda_manual_seed(0)
442
+
443
+ # init hf config
444
+ hf_config = AutoConfig.from_pretrained(hf_model_path)
445
+ print(hf_config, flush=True)
446
+
447
+ if world_size > 1 and not support_distributed_convert(hf_config):
448
+ raise NotImplementedError(f"distributed conversion is not supported for {hf_config.architectures} yet.")
449
+
450
+ pipeline_shards = get_dynamic_pipeline_shards(hf_config.num_hidden_layers, world_size)
451
+ print(f"Pipeline shards: {pipeline_shards}", flush=True)
452
+
453
+ tfconfig = hf_to_mcore_config(
454
+ hf_config,
455
+ torch.bfloat16,
456
+ num_layers_in_first_pipeline_stage=pipeline_shards[0] if len(pipeline_shards) > 1 else None,
457
+ num_layers_in_last_pipeline_stage=pipeline_shards[-1] if len(pipeline_shards) > 2 else None,
458
+ )
459
+ tfconfig.use_cpu_initialization = use_cpu_initialization
460
+ tie_word_embeddings = getattr(hf_config, "tie_word_embeddings", False)
461
+
462
+ # init megatron model
463
+ def megatron_model_provider(pre_process, post_process):
464
+ from verl.models.mcore import init_mcore_model
465
+
466
+ parallel_model = init_mcore_model(
467
+ tfconfig,
468
+ hf_config,
469
+ pre_process,
470
+ post_process,
471
+ share_embeddings_and_output_weights=tie_word_embeddings,
472
+ value=False,
473
+ )
474
+ return parallel_model
475
+
476
+ context: Callable[..., ContextManager] = init_empty_weights if use_cpu_initialization else noop_context
477
+ with context():
478
+ model = get_model(
479
+ model_provider_func=megatron_model_provider,
480
+ model_type=ModelType.encoder_or_decoder,
481
+ wrap_with_ddp=False,
482
+ transformer_config=tfconfig,
483
+ )
484
+
485
+ if use_cpu_initialization:
486
+ # convert meta device to empty tensor so it can use `copy_` function
487
+ model[0].module = model[0].module.to_empty(device="cpu")
488
+
489
+ with warnings.catch_warnings():
490
+ warnings.simplefilter("ignore")
491
+ from transformers import AutoModelForCausalLM, AutoModelForImageTextToText
492
+
493
+ # init hf model
494
+ if "Qwen2_5_VLForConditionalGeneration" in hf_config.architectures:
495
+ hf_model = AutoModelForImageTextToText.from_pretrained(
496
+ hf_model_path, torch_dtype=torch.bfloat16, trust_remote_code=trust_remote_code
497
+ )
498
+ else:
499
+ hf_model = AutoModelForCausalLM.from_pretrained(
500
+ hf_model_path, torch_dtype=torch.bfloat16, trust_remote_code=trust_remote_code
501
+ )
502
+ hf_state_dict = hf_model.state_dict()
503
+
504
+ # distributed convert
505
+ if world_size > 1 and support_distributed_convert(hf_config):
506
+ pipeline_cumsum = np.cumsum(pipeline_shards)
507
+ layer_start = 0 if rank == 0 else pipeline_cumsum[rank - 1]
508
+ layer_end = pipeline_cumsum[rank]
509
+ if "DeepseekV3ForCausalLM" in hf_config.architectures:
510
+ numel_partial: int = convert_checkpoint_from_transformers_to_megatron_dpskv3(
511
+ hf_model, model[0].module, hf_config, tfconfig=tfconfig, layer_start_end=(layer_start, layer_end)
512
+ )
513
+ elif "Qwen3MoeForCausalLM" in hf_config.architectures or "Qwen2MoeForCausalLM" in hf_config.architectures:
514
+ numel_partial: int = convert_checkpoint_from_transformers_to_megatron(
515
+ hf_model, model[0].module, hf_config, layer_start_end=(layer_start, layer_end)
516
+ )
517
+ else:
518
+ raise NotImplementedError(f"Distributed conversion is not supported for {hf_config.architectures} yet.")
519
+
520
+ numel_tensor = torch.tensor([numel_partial]).to(get_device_name())
521
+ dist.all_reduce(numel_tensor, op=dist.ReduceOp.SUM)
522
+ numel = int(numel_tensor.cpu().item())
523
+ print(f"total numel={numel} vs {hf_model.num_parameters()=}")
524
+ if numel != hf_model.num_parameters():
525
+ warnings.warn(f"numel mismatch: {numel=} != {hf_model.num_parameters()=}", stacklevel=1)
526
+
527
+ # load hf state dict to megatron model
528
+ elif "Qwen2MoeForCausalLM" in hf_config.architectures:
529
+ convert_checkpoint_from_transformers_to_megatron(hf_model, model[0].module, hf_config)
530
+ elif "Qwen2_5_VLForConditionalGeneration" in hf_config.architectures:
531
+ convert_checkpoint_from_transformers_to_megatron_qwen2_5_vl(hf_model, model[0].module, hf_config)
532
+ elif "DeepseekV3ForCausalLM" in hf_config.architectures:
533
+ convert_checkpoint_from_transformers_to_megatron_dpskv3(hf_model, model[0].module, hf_config, tfconfig=tfconfig)
534
+ elif "Qwen3MoeForCausalLM" in hf_config.architectures:
535
+ convert_checkpoint_from_transformers_to_megatron(hf_model, model[0].module, hf_config)
536
+ else:
537
+ assert not use_cpu_initialization, "use_cpu_initialization is only supported for MoE model"
538
+ from verl.models.mcore.loader import load_state_dict_to_megatron_gptmodel
539
+
540
+ load_state_dict_to_megatron_gptmodel(
541
+ state_dict=hf_state_dict,
542
+ wrapped_models=model,
543
+ config=hf_config,
544
+ params_dtype=torch.bfloat16,
545
+ is_value_model=False,
546
+ )
547
+
548
+ megatron_state_dict = model[0].module.sharded_state_dict()
549
+ del hf_state_dict, hf_model
550
+
551
+ # save megatron model
552
+ if len(os.listdir(output_path)) == 0:
553
+ dist_checkpointing.save(megatron_state_dict, output_path, sharded_strategy=None, async_sharded_save=False)
554
+ if test:
555
+ test_conversion(megatron_model_provider, tfconfig, output_path, model)
556
+
557
+
558
+ if __name__ == "__main__":
559
+ args = _init_args()
560
+ convert_hf_to_mcore(
561
+ args.hf_model_path, args.output_path, args.use_cpu_initialization, args.test, args.trust_remote_code
562
+ )