diff --git a/.gitignore b/.gitignore index 25c35b8..e0aee4f 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,10 @@ __pycache__/ .mypy_cache/ .ruff_cache/ .venv/ +.venv-*/ +*.egg-info/ +/.coverage +/htmlcov/ # macOS metadata .DS_Store @@ -46,6 +50,9 @@ tmp/ *.npz *.safetensors +# DeepSeek V4 CUDA gate receipts +rank_[0-9][0-9][0-9][0-9].json + # Per-run state that may be generated outside a top-level runs/ directory weights/ **/weights/ diff --git a/config.py b/config.py index 89ece3f..2d09bf8 100644 --- a/config.py +++ b/config.py @@ -713,6 +713,7 @@ class AsyncRLConfig: virtual_pipeline_model_parallel_size: int = 0 sequence_parallel: bool = True use_distributed_optimizer: bool = True + megatron_model_family: str = "default" # default | deepseek_v4 megatron_grad_reduce_in_fp32: bool = False megatron_use_precision_aware_optimizer: bool = False megatron_optimizer_cpu_offload: bool = False @@ -836,6 +837,30 @@ class AsyncRLConfig: default_factory=GlobalResourcePlannerConfig ) + def _validate_deepseek_v4_training(self) -> None: + if self.train_backend != "megatron_core" or not self.megatron_use_transformer_engine: + raise ValueError("DeepSeek V4 requires Megatron-Core with Transformer Engine") + if (self.train_tp_size, self.expert_tensor_parallel_size) != (1, 1): + raise ValueError("The CUDA DeepSeek V4 provider requires TP=ETP=1") + if self.train_cp_size < 1: + raise ValueError("DeepSeek V4 requires a positive CP size") + if self.train_pp_size < 2: + raise ValueError("The CUDA DeepSeek V4 training path requires PP >= 2") + if self.train_dp_size < 1 or self.n_samples < 1: + raise ValueError("DeepSeek V4 requires positive DP size and GRPO group size") + if self.batch_size % (self.train_dp_size * self.n_samples): + raise ValueError("DeepSeek V4 requires an equal number of complete GRPO groups per DP rank") + local_batch = self.batch_size // self.train_dp_size + if self.recompute_micro_batch_size < 1 or local_batch % self.recompute_micro_batch_size: + raise ValueError("DeepSeek V4 requires complete recompute microbatches") + if self.rollout_weight_sync_mode != "none" or self.require_rollout_weight_sync: + raise ValueError("DeepSeek V4 rollout weight publication has not been validated") + if self.megatron_streaming_export: + raise ValueError("Set megatron_streaming_export=false for DeepSeek V4 training checkpoints") + planner = self.global_resource_planner + if planner.enabled: + raise ValueError("DeepSeek V4 requires a static training topology until GRP/EHP validation") + def __post_init__(self): """Post init.""" if not self.tokenizer_path: @@ -861,6 +886,10 @@ def __post_init__(self): f"train_gpus={self.train_gpus}, model_parallel={denom}" ) self.train_dp_size = self.train_gpus // denom + if self.megatron_model_family not in {"default", "deepseek_v4"}: + raise ValueError("Unknown megatron_model_family") + if self.megatron_model_family == "deepseek_v4": + self._validate_deepseek_v4_training() if self.train_backend not in ["fsdp", "megatron3d", "megatron_core"]: raise ValueError( "train_backend must be 'fsdp', 'megatron3d', or 'megatron_core'" @@ -949,7 +978,7 @@ def __post_init__(self): "megatron_optimizer_offload_fraction requires " "megatron_optimizer_cpu_offload=true" ) - if self.train_pp_size != 1: + if self.train_pp_size != 1 and self.megatron_model_family != "deepseek_v4": raise ValueError( "MegatronCoreTrainEngine currently requires train_pp_size=1" ) @@ -964,10 +993,17 @@ def __post_init__(self): "expert_tensor_parallel_size must divide train_tp_size: " f"{self.expert_tensor_parallel_size} vs {self.train_tp_size}" ) - if self.train_dp_size % self.train_ep_size != 0: + # Megatron's V4 expert rank generator consumes the dense DP×CP + # slots and keeps the same pipeline groups. + expert_slots = self.train_dp_size + expert_axis = "train_dp_size" + if self.megatron_model_family == "deepseek_v4": + expert_slots *= self.train_cp_size + expert_axis = "DP × CP" + if expert_slots % self.train_ep_size != 0: raise ValueError( - "train_ep_size must divide train_dp_size: " - f"{self.train_ep_size} vs {self.train_dp_size}" + f"train_ep_size must divide {expert_axis}: " + f"{self.train_ep_size} vs {expert_slots}" ) if self.model_arch.num_experts > 1: if self.model_arch.num_experts % self.train_ep_size != 0: diff --git a/configs/deepseek_v4_flash_h20_32_train_gate.yaml b/configs/deepseek_v4_flash_h20_32_train_gate.yaml new file mode 100644 index 0000000..e1c0371 --- /dev/null +++ b/configs/deepseek_v4_flash_h20_32_train_gate.yaml @@ -0,0 +1,32 @@ +model_path: deepseek-ai/DeepSeek-V4-Flash +hardware_config: hardware_config/h20_3e_141g.yaml +model_arch_config: model_arch_config/deepseek-v4-flash.yaml +train_backend: megatron_core +megatron_model_family: deepseek_v4 +train_gpus: 32 +rollout_gpus: 0 +train_tp_size: 1 +train_pp_size: 4 +train_cp_size: 1 +train_ep_size: 8 +expert_tensor_parallel_size: 1 +sequence_parallel: false +megatron_use_transformer_engine: true +use_distributed_optimizer: true +megatron_use_precision_aware_optimizer: true +megatron_optimizer_cpu_offload: true +megatron_optimizer_offload_fraction: 1.0 +megatron_optimizer_pin_cpu_params: false +megatron_optimizer_pin_cpu_grads: false +megatron_streaming_export: false +global_resource_planner: + enabled: false +rollout_weight_sync_mode: none +sync_interval: 0 +batch_size: 16 +n_samples: 2 +micro_batch_size: 1 +recompute_micro_batch_size: 1 +max_seq_length: 1024 +learning_rate: 0.001 # Smoke-test update, chosen to observe changes in BF16 weights. +total_steps: 1 diff --git a/configs/model_arch_config/deepseek-v4-flash.yaml b/configs/model_arch_config/deepseek-v4-flash.yaml new file mode 100644 index 0000000..42f8670 --- /dev/null +++ b/configs/model_arch_config/deepseek-v4-flash.yaml @@ -0,0 +1,17 @@ +# Official DeepSeek-V4-Flash. Its packed FP4/FP8 checkpoint is loaded into BF16. +num_params: 285.0e+9 +active_num_params: 13.0e+9 +d_model: 4096 +n_layers: 43 +n_heads: 64 +n_kv_heads: 1 +head_dim: 512 +vocab_size: 129280 +intermediate_size: 2048 +dtype_bytes: 2 +is_moe: true +num_experts: 256 +num_shared_experts: 1 +num_activated_experts: 6 +expert_intermediate_size: 2048 +shared_expert_intermediate_size: 2048 diff --git a/docs/deepseek_v4_cuda.md b/docs/deepseek_v4_cuda.md new file mode 100644 index 0000000..458257d --- /dev/null +++ b/docs/deepseek_v4_cuda.md @@ -0,0 +1,155 @@ +# DeepSeek V4 Flash training on CUDA + +The opt-in `megatron_model_family: deepseek_v4` selects NVIDIA's native +DeepSeek V4 Bridge and Megatron hybrid model. Libra retains its GRPO loss, +policy logprob recomputation and distributed training checkpoint path. Both +training and recomputation use Megatron's non-interleaved pipeline scheduler. +The default Megatron backend keeps its existing PP=1 and dependency behavior. + +## Runtime and checkpoint + +Use an isolated CUDA training environment. The integration targets +[Megatron Bridge eea53e4](https://github.com/NVIDIA-NeMo/Megatron-Bridge/tree/eea53e431a8b0b4e9c4f47a76784c6f3200c9a1f) +and its +[matching Megatron-Core commit](https://github.com/NVIDIA/Megatron-LM/tree/43a2ef6d35a0188a4f0601a5ce5e569d2c011562). +Build the CUDA environment from the Bridge checkout with its pinned Megatron-LM +submodule, following the upstream container setup. That checkout requires Python +3.12, a recent Transformers release with `DeepseekV4ForCausalLM`, and a CUDA +build of Transformer Engine. Install Libra into that environment with +`python -m pip install --no-deps -e .`. Use the Bridge environment's torch, +Transformers and Megatron versions. Libra's Qwen Megatron install script pins +older versions for a separate stack. + +Make a complete local Hugging Face snapshot of +[deepseek-ai/DeepSeek-V4-Flash](https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash) +available at the same path on all training nodes. Megatron Bridge reads the +official packed checkpoint and loads BF16 training weights. The initial profile +uses the native attention and MoE layout with MTP disabled, unfused mHC, +and selective recomputation. Attention TP and expert TP are fixed at 1. +CP1 retains the unfused DSA path. CP>1 uses Megatron-Core's contiguous +packed attention with the cuDNN DSA backend and requires a compatible +cuDNN Frontend and FlashMLA sparse forward in the CUDA runtime. Older +Hopper FlashMLA with `topk_length` supports this path when Libra's indexer +loss is disabled. Requesting indexer LSE requires the extended FlashMLA API. + +## Context parallelism + +Set `train_cp_size` in the YAML and set `train_dp_size: 0` to derive DP +from the number of training GPUs. The resulting topology must satisfy +`train_gpus = TP × PP × CP × DP` and EP must divide `DP × CP`. +The global batch must still divide into complete GRPO groups and +microbatches on each logical DP replica. Choose CP at process startup. + +For example, with 48 training GPUs, PP3 and EP8, CP1, CP2, CP4 and CP8 +give DP16, DP8, DP4 and DP2 respectively. At PP4, EP4 fits the +12 ranks per pipeline stage. CP1, CP2, CP3, CP4, CP6 and CP12 then +give DP12, DP6, DP4, DP3, DP2 and DP1 respectively. These are topology +examples. Activation memory and expert communication locality depend on +the actual placement and workload. + +Each CP group handles the same logical trajectories. The packed +attention shards the padded sequence, preserving document boundaries and +global next-token targets across rank boundaries. Libra gathers scalar +logprobs before returning them to the trainer. GRPO uses global action +counts to normalize the local loss contributions and reports each +trajectory once. Additional right padding aligns shards and gives +Megatron enough rows for the attention boundary exchange. + +## 32×H20 training gate + +`configs/deepseek_v4_flash_h20_32_train_gate.yaml` uses all 32 H20s for +training across four 8-GPU nodes (`TP1 / PP4 / EP8 / DP8`), with CPU optimizer +offload and 1024-token synthetic trajectories. Confirm the GPUs are free and +there is enough host RAM for the offloaded optimizer state. The topology +follows the upstream 32-GPU Hopper recipe and requires validation on H20. + +From the repo root on each node, set the same reachable rank-zero address +and shared checkpoint/output paths. Set `NODE_RANK` to 0, 1, 2 or 3. + +```bash +torchrun --nnodes=4 --nproc-per-node=8 --node-rank="$NODE_RANK" \ + --master-addr="$MASTER_ADDR" --master-port=29500 \ + scripts/validate_deepseek_v4_cuda.py \ + --config configs/deepseek_v4_flash_h20_32_train_gate.yaml \ + --model "$MODEL_PATH" --output "$RUN_OUTPUT" +``` + +Success requires 32 per-rank receipts and +`LIBRA_DEEPSEEK_V4_CUDA_GATE_PASSED ranks=32`. The gate checks finite +recomputed logprobs and loss, one optimizer revision, a change in sampled +parameters, and GPU memory peaks. +Pass `--cp-size 2` or `--cp-size 4` to the same gate to derive a +matching DP degree. Use a fresh output directory for each run. The gate +also checks that CP peers reconstruct identical logprobs and that the +optimizer reports the configured global sample count. + +The gate measures a training update. A separate rollout allocation or a +validated colocated runtime is needed for generation during this run. Before +using this path for a full Libra efficiency benchmark, validate HF export, +rollout weight publication and consumption, and elastic training with the +chosen backend and parallel layout. + +## Compact replica memory + +For a compact BF16 replica, the distributed optimizer can allocate its new +parameter and gradient buffers while all original parameter storage is still +resident. The patch below moves independent, non-NCCL-registered gradient +allocation after the parameters are remapped. Apply it to a separate checkout +of the compatible Megatron-Core source used by each training rank. + +```bash +git -C "$MCORE_PATH" apply --check "$LIBRA_PATH/patches/mcore-defer-ddp-grad-allocation.patch" +git -C "$MCORE_PATH" apply "$LIBRA_PATH/patches/mcore-defer-ddp-grad-allocation.patch" +``` + +CUDA V4 still requires a static topology. Enabling EHP additionally requires +cross-host launch for the complete PP/EP replica, matching expert gradient +lanes, and full rollout weight publication. + +## Fixed-checkpoint rollout on 32 H20s + +Use four independent vLLM replicas with eight GPUs per replica (TP8, expert +parallelism enabled). Run MTP and DSpark as separate rollout configurations +with the matching official checkpoints. + +| Method | Checkpoint | Draft configuration | +| --- | --- | --- | +| MTP | `deepseek-ai/DeepSeek-V4-Flash` | One draft token on Hopper | +| DSpark | `deepseek-ai/DeepSeek-V4-Flash-DSpark` | Seven draft tokens, greedy drafting with target rejection sampling | + +Use a CUDA environment with vLLM 0.30.0 and a compatible PyTorch wheel. On +the QS H20 image with driver 570 and CUDA 13.3 compatibility libraries, prepend +`/usr/local/cuda/compat` to `LD_LIBRARY_PATH` for that process. Put complete +checkpoint snapshots at paths visible on each node. + +On each node, run the following in the rollout environment. Set +`METHOD=mtp` or `METHOD=dspark`, `MODEL_PATH` to the local snapshot, and +`SERVED_MODEL_NAME` to the same model name on all four replicas. + +```bash +python -m RL_Framework.scripts.deepseek_v4_spec_rollout serve \ + --method "$METHOD" --model "$MODEL_PATH" --model-name "$SERVED_MODEL_NAME" --enforce-eager +``` + +After readiness, verify each replica with the same served model name and port. +For cross-node clients, bind a private interface with `serve --host` and use +the four addresses in `vllm_endpoints`. The served model name must match the +model name sent by the rollout client. + +```bash +python -m RL_Framework.scripts.deepseek_v4_spec_rollout verify \ + --model-name "$SERVED_MODEL_NAME" +``` + +The verifier sends three sampled requests through Libra's `VLLMRolloutEngine`, +requires 64 tokens with finite logprobs per request, and checks that vLLM's +draft and accepted-token counters increased. Save the JSON from all four +nodes per mode. This gate covers fixed-checkpoint generation and standard +completion logprobs. V4 training leaves its MTP auxiliary loss disabled. +Decoupled PPO behavior capture and hot weight publication need separate +integration. + +On 2026-11-23, all four replicas passed on QS with H20-3e GPUs, vLLM +0.30.0, and eager execution. Each mode produced 768 output tokens with finite +logprobs across 12 requests. vLLM recorded 361 accepted draft tokens out +of 400 for MTP and 628 out of 1,134 for DSpark. diff --git a/engine/deepseek_v4_train_engine.py b/engine/deepseek_v4_train_engine.py new file mode 100644 index 0000000..c399697 --- /dev/null +++ b/engine/deepseek_v4_train_engine.py @@ -0,0 +1,369 @@ +"""CUDA DeepSeek V4 training using NVIDIA's native MCore hybrid model.""" + +from __future__ import annotations + +from collections import defaultdict +from contextlib import contextmanager +from functools import wraps +from inspect import signature +from math import lcm + +import torch +import torch.distributed as dist +import torch.nn.functional as F + +from RL_Framework.engine.megatron_core_train_engine import MegatronCoreTrainEngine + +_LOGPROB_CHUNK_SIZE = 512 + + +def _gradient_norms(_chunk_size, _overflow, tensor_lists, per_tensor=False): + # Megatron's DSA split combines views from several gradient buffers. + # Compute FP32 norms with PyTorch, grouping the foreach calls by dtype. + groups = defaultdict(list) + grads = tensor_lists[0] + for index, grad in enumerate(grads): + groups[grad.dtype].append((index, grad)) + norms = [None] * len(grads) + for group in groups.values(): + indices, tensors = zip(*group) + for index, norm in zip(indices, torch._foreach_norm(tensors, 2, dtype=torch.float32)): + norms[index] = norm + per_gradient = torch.stack(norms) + return torch.linalg.vector_norm(per_gradient).reshape(1), per_gradient if per_tensor else None + + +def _scale_gradients(_chunk_size, _overflow, tensor_lists, scale): + # Megatron clips in place and passes the same list as both source and target. + groups = defaultdict(list) + for source, target in zip(*tensor_lists): + if source is not target: + raise ValueError("Expected in-place Megatron gradient scaling") + groups[target.dtype].append(target) + if isinstance(scale, torch.Tensor): + scale = scale.reshape(()) + for group in groups.values(): + torch._foreach_mul_(group, scale) + + +@contextmanager +def _pytorch_gradient_clipping(): + from megatron.core.optimizer import clip_grads + + saved = ( + clip_grads.l2_norm_impl, + clip_grads.multi_tensor_scale_impl, + clip_grads.multi_tensor_scale_tensor_impl, + ) + clip_grads.l2_norm_impl = _gradient_norms + clip_grads.multi_tensor_scale_impl = _scale_gradients + clip_grads.multi_tensor_scale_tensor_impl = _scale_gradients + try: + yield + finally: + ( + clip_grads.l2_norm_impl, + clip_grads.multi_tensor_scale_impl, + clip_grads.multi_tensor_scale_tensor_impl, + ) = saved + + +def _configure_flash_mla_for_cp(): + from megatron.core.transformer.experimental_attention_variant.csa_utils import fused_sparse_attention + + fused_sparse_attention._ensure_flash_mla() + sparse_forward = fused_sparse_attention._flash_mla_sparse_fwd + parameters = signature(sparse_forward).parameters + if "indexer_topk" in parameters or getattr(sparse_forward, "_libra_zero_indexer_compat", False): + return + if "topk_length" not in parameters: + raise RuntimeError("DeepSeek V4 CP requires FlashMLA sparse forward with topk_length") + + @wraps(sparse_forward) + def forward_without_indexer_lse(*args, indexer_topk=0, **kwargs): + # Legacy Hopper FlashMLA returns the same three values in zero-indexer + # mode. Nonzero indexer_topk requires the extended four-value API. + if indexer_topk: + raise RuntimeError("FlashMLA does not support returning indexer LSE") + return sparse_forward(*args, **kwargs) + + forward_without_indexer_lse._libra_zero_indexer_compat = True + fused_sparse_attention._flash_mla_sparse_fwd = forward_without_indexer_lse + + +class DeepSeekV4TrainEngine(MegatronCoreTrainEngine): + """Run Libra's GRPO loss through the native Megatron 1F1B schedule.""" + + supports_pipeline_parallelism = True + dependency_guide = "docs/deepseek_v4_cuda.md" + + def _load_bridge(self, auto_bridge): + try: + from megatron.bridge.models.deepseek.deepseek_v4_bridge import DeepSeekV4Bridge + from megatron.core.config import set_experimental_flag + except ImportError as exc: + raise RuntimeError( + "DeepSeek V4 requires a CUDA Megatron Bridge/MCore build with native V4 " + "support. See docs/deepseek_v4_cuda.md for the compatible revisions." + ) from exc + set_experimental_flag(True) + bridge = super()._load_bridge(auto_bridge) + if not isinstance(bridge._model_bridge, DeepSeekV4Bridge): + raise ValueError("Expected a DeepSeek V4 checkpoint for the DeepSeek V4 CUDA provider") + return bridge + + def _configure_provider(self, max_seq_length: int) -> None: + from megatron.bridge.models.deepseek.deepseek_v4_bridge import ( + set_deepseek_v4_pipeline_model_parallel_layout, + ) + + provider = self.provider + router_dtype = provider.moe_router_dtype + super()._configure_provider(max_seq_length) + provider.moe_router_dtype = router_dtype + # Match the Hopper-compatible no-MTP recipe and keep the native hybrid + # W/CSA/HCA + MoE layout. MTP is not part of Libra's GRPO objective. + provider.transformer_impl = "transformer_engine" + provider.attention_backend = None + # V4's native CP implementation requires contiguous THD and cuDNN CSA. + provider.dsa_kernel_backend = "cudnn" if self.train_cp_size > 1 else "none" + if self.train_cp_size > 1: + provider.attention_cp_layout = "contiguous" + # HybridStack uses the linear layout at its PP boundaries and MoE + # blocks. Keep it consistent with the packed V4 attention layout. + provider.linear_cp_layout = "contiguous" + _configure_flash_mla_for_cp() + provider.use_fused_mhc = False + provider.mhc_norm_eps_inside_sqrt = True + provider.apply_rope_fusion = True + provider.dsa_indexer_loss_coeff = 0.0 + provider.dsa_indexer_use_sparse_loss = False + provider.moe_aux_loss_coeff = 0.0 + provider.moe_router_force_load_balancing = False + provider.moe_router_bias_update_rate = 0.0 + provider.recompute_granularity = "selective" + provider.recompute_modules = ["moe_act", "mhc"] + provider.recompute_method = None + provider.recompute_num_layers = None + provider.cuda_graph_impl = "none" + provider.mtp_num_layers = None + provider.mtp_loss_scaling_factor = 0.0 + provider.mtp_hybrid_override_pattern = None + if provider.csa_compress_ratios is not None: + provider.csa_compress_ratios = list(provider.csa_compress_ratios[:provider.num_layers]) + set_deepseek_v4_pipeline_model_parallel_layout(provider) + + def get_data_parallel_world_size(self): + return self._parallel_state().get_data_parallel_world_size(with_context_parallel=False) + + def get_data_parallel_rank(self): + return self._parallel_state().get_data_parallel_rank(with_context_parallel=False) + + def is_batch_source(self): + return super().is_batch_source() and ( + self.train_cp_size == 1 or self._parallel_state().get_context_parallel_rank() == 0 + ) + + def distribute_trajectories(self, trajectories): + if not dist.is_initialized(): + return trajectories or [] + parallel_state = self._parallel_state() + payload = [trajectories if self.is_batch_source() else None] + if self.train_cp_size > 1 and parallel_state.is_pipeline_first_stage(): + cp_group = parallel_state.get_context_parallel_group() + dist.broadcast_object_list(payload, src=dist.get_global_rank(cp_group, 0), group=cp_group) + dist.broadcast_object_list( + payload, + src=parallel_state.get_pipeline_model_parallel_first_rank(), + group=parallel_state.get_pipeline_model_parallel_group(), + ) + return payload[0] or [] + + def _forward_context_shard(self, batch, model, cp_group, *, forward_only): + from megatron.core.packed_seq_params import PackedSeqParams + + ids = batch["input_ids"] + samples, width = ids.shape + local_tokens = ids.numel() // cp_group.size() + first_token = local_tokens * cp_group.rank() + shard = slice(first_token, first_token + local_tokens) + positions = torch.arange(first_token, first_token + local_tokens, device=ids.device) + cu_seqlens = torch.arange(0, (samples + 1) * width, width, dtype=torch.int32, device=ids.device) + packed = PackedSeqParams(qkv_format="thd", cu_seqlens_q=cu_seqlens, + cu_seqlens_kv=cu_seqlens, max_seqlen_q=width, max_seqlen_kv=width) + output = model(input_ids=ids.flatten()[shard].unsqueeze(0), + position_ids=(positions % width).unsqueeze(0), + attention_mask=None, labels=None, packed_seq_params=packed) + + def loss_func(logits): + if logits.shape[:2] != (1, local_tokens): + raise RuntimeError("Unexpected DeepSeek V4 packed CP logits layout") + + def scores(active, target_positions): + selected = F.log_softmax(logits[0, active].float(), dim=-1) + return selected.gather(-1, ids.flatten()[target_positions].unsqueeze(-1)).squeeze(-1) + + if forward_only: + local = logits.new_zeros(local_tokens, dtype=torch.float32) + active = (positions % width < batch["length"] - 1).nonzero(as_tuple=True)[0] + for indices in active.split(_LOGPROB_CHUNK_SIZE): + local[indices] = scores(indices, positions[indices] + 1) + gathered = torch.empty_like(ids, dtype=local.dtype).view(-1) + dist.all_gather_into_tensor(gathered, local, group=cp_group) + return logits.new_zeros(()), gathered.view_as(ids)[:, :batch["length"] - 1] + + # Shift in global document order before slicing. The last query on a + # shard can predict the first token on the next rank, never the next document. + candidates = (positions % width < width - 1).nonzero(as_tuple=True)[0] + candidate_targets = positions[candidates] + 1 + mask = batch["loss_mask"] + selected = mask.flatten()[candidate_targets].nonzero(as_tuple=True)[0] + active = candidates[selected] + target_positions = candidate_targets[selected] + action_rows = target_positions // width + anchor = batch["old_logprobs"].flatten()[target_positions] + weights = mask.flatten()[target_positions] + if "behavior_logprobs" in batch: + behavior = batch["behavior_logprobs"].flatten()[target_positions] + weights = torch.exp(anchor - behavior) + loss, stats = self._loss_from_actions( + scores(active, target_positions), anchor, batch["advantages"][action_rows], + weights, mask[:, 1:].sum(-1).clamp_min(1.0)[action_rows], batch["rewards"], + ) + # Megatron's two-value loss callback scales by CP before the DP×CP + # gradient average. Do not scale the local contribution a second time. + return loss, stats + + return output, loss_func + + def _pipeline(self, trajectories, *, forward_only: bool): + from megatron.core.distributed import finalize_model_grads + from megatron.core.pipeline_parallel import get_forward_backward_func + from megatron.core.utils import get_model_config + + micro_batch_size = self.recompute_micro_batch_size if forward_only else self.micro_batch_size + # 1F1B uses one activation shape for the entire schedule. + if not trajectories or len(trajectories) % micro_batch_size: + raise ValueError("DeepSeek V4 pipeline requires nonempty, complete microbatches") + cp_group = None + width = self.max_seq_length + if self.train_cp_size > 1: + cp_group = self._parallel_state().get_context_parallel_group() + compression = max(1, *self.provider.csa_compress_ratios) + boundary = max(self.provider.csa_window_size, compression) + alignment = lcm(cp_group.size(), compression) + width = max(width, boundary * cp_group.size()) + width = ((width + alignment - 1) // alignment) * alignment + + def make_batches(): + for start in range(0, len(trajectories), micro_batch_size): + rows = trajectories[start:start + micro_batch_size] + batch = self._pad_micro_batch(rows, require_anchor=not forward_only) + batch["length"] = batch["input_ids"].shape[1] + if batch["length"] > self.max_seq_length: + raise ValueError("DeepSeek V4 trajectory exceeds the configured sequence length") + padding = width - batch["length"] + for key in ("input_ids", "loss_mask", "old_logprobs", "behavior_logprobs"): + if key in batch: + value = self.tokenizer.pad_token_id if key == "input_ids" else 0 + batch[key] = F.pad(batch[key], (0, padding), value=value) + yield batch + + def forward_step(iterator, model): + batch = next(iterator) + if cp_group is not None: + return self._forward_context_shard( + batch, model, cp_group, forward_only=forward_only, + ) + ids = batch["input_ids"] + positions = torch.arange(ids.shape[1], device=ids.device).expand_as(ids) + output = model(input_ids=ids, position_ids=positions, attention_mask=None, labels=None) + + def loss_func(logits): + if logits.shape[:2] != ids.shape: + raise RuntimeError("Unexpected DeepSeek V4 pipeline logits layout") + if forward_only: + length = batch["length"] + logprobs = self._action_log_probs(logits[:, :length], ids[:, :length]) + return logits.new_zeros(()), logprobs + return self._loss(batch, logits) + + return output, loss_func + + config = get_model_config(self.model[0]) + if not forward_only: + config.grad_scale_func = self.optimizer.scale_loss + config.finalize_model_grads_func = finalize_model_grads + return get_forward_backward_func()( + forward_step_func=forward_step, + data_iterator=make_batches(), + model=self.model, + num_microbatches=len(trajectories) // micro_batch_size, + seq_length=width if cp_group is None else width * micro_batch_size, + micro_batch_size=micro_batch_size if cp_group is None else 1, + forward_only=forward_only, + ) + + def recompute_logprobs(self, trajectories): + parallel_state = self._parallel_state() + self._set_train_mode(False) + try: + with torch.no_grad(): + batches = self._pipeline(trajectories, forward_only=True) + logprobs = torch.zeros( + (len(trajectories), self.max_seq_length), dtype=torch.float32, device=self._device() + ) + if parallel_state.is_pipeline_last_stage(): + offset = 0 + for batch in batches: + count, width = batch.shape + logprobs[offset:offset + count, 1:width + 1] = batch + offset += count + dist.broadcast( + logprobs, + src=parallel_state.get_pipeline_model_parallel_last_rank(), + group=parallel_state.get_pipeline_model_parallel_group(), + ) + for row, trajectory in zip(logprobs.cpu(), trajectories): + length = trajectory["input_ids"].shape[-1] + trajectory["logprobs"] = row[:length].unsqueeze(0).clone() + finally: + self._set_train_mode(True) + + def grpo_update(self, trajectories, ppo_epochs=1): + parallel_state = self._parallel_state() + epoch_stats = [] + for _ in range(ppo_epochs): + self._zero_grad() + self._set_train_mode(True) + stats = self._pipeline(trajectories, forward_only=False) + # The schedule calls finalize_model_grads before returning. + # Both Apex and TE 2.20 hit illegal accesses calculating V4's + # DSA split norm on H20. Preserve Megatron's reductions and clipping. + with _pytorch_gradient_clipping(): + successful, grad_norm, _ = self.optimizer.step() + if not successful: + raise FloatingPointError("DeepSeek V4 optimizer rejected the update") + self.optimizer_revision += 1 + result = None + if parallel_state.is_pipeline_last_stage(): + result = self._merge_stats(stats) + result["grad_norm"] = float(grad_norm) if grad_norm is not None else 0.0 + if self.train_cp_size > 1: + keys = ("loss", "pg_loss", "kl") + values = torch.tensor([result[key] for key in keys], device=self._device()) + dist.all_reduce(values, group=parallel_state.get_context_parallel_group()) + result.update(zip(keys, values.tolist())) + result = self._reduce_stats(result, with_context_parallel=False) + else: + result = self._reduce_stats(result) + payload = [result] + dist.broadcast_object_list( + payload, + src=parallel_state.get_pipeline_model_parallel_last_rank(), + group=parallel_state.get_pipeline_model_parallel_group(), + ) + epoch_stats.append(payload[0]) + result = self._merge_stats(epoch_stats) + result["version"] = self.current_version + return result diff --git a/engine/megatron_core_train_engine.py b/engine/megatron_core_train_engine.py index 6379a85..92f10e3 100644 --- a/engine/megatron_core_train_engine.py +++ b/engine/megatron_core_train_engine.py @@ -35,6 +35,9 @@ class MegatronCoreTrainEngine: """MCore TP/EP/DDP backend with streaming HF interoperability.""" + supports_pipeline_parallelism = False + dependency_guide = "requirements-megatron.txt" + def __init__( self, *, @@ -171,7 +174,7 @@ def init_phase(name: str) -> None: raise ValueError( "optimizer_offload_fraction requires optimizer_cpu_offload=True" ) - if self.train_pp_size != 1: + if self.train_pp_size != 1 and not self.supports_pipeline_parallelism: raise ValueError( "MegatronCoreTrainEngine currently supports PP=1; use TP/EP/DP " "for Qwen3-30B-A3B" @@ -184,17 +187,19 @@ def init_phase(name: str) -> None: from megatron.bridge import AutoBridge from megatron.core.distributed import DistributedDataParallelConfig from megatron.core.optimizer import OptimizerConfig, get_megatron_optimizer - from RL_Framework.engine.megatron_core_attention import ( - apply_megatron_core_014_compatibility, - torch_sdpa_layer_spec, - ) + if not self.supports_pipeline_parallelism: + from RL_Framework.engine.megatron_core_attention import ( + apply_megatron_core_014_compatibility, + ) + if not self.use_transformer_engine: + from RL_Framework.engine.megatron_core_attention import torch_sdpa_layer_spec except ImportError as exc: raise RuntimeError( - "Megatron-Core dependencies are unavailable. Install the pinned " - "packages from requirements-megatron.txt." + f"Megatron-Core dependencies are unavailable. See {self.dependency_guide}." ) from exc init_phase("imports_complete") - apply_megatron_core_014_compatibility() + if not self.supports_pipeline_parallelism: + apply_megatron_core_014_compatibility() init_phase("tokenizer_load_start") self.tokenizer = AutoTokenizer.from_pretrained( @@ -206,10 +211,7 @@ def init_phase(name: str) -> None: init_phase("tokenizer_load_complete") init_phase("bridge_load_start") - self.bridge = AutoBridge.from_hf_pretrained( - self.model_path, - trust_remote_code=True, - ) + self.bridge = self._load_bridge(AutoBridge) init_phase("bridge_load_complete") init_phase("provider_build_start") self.provider = self.bridge.to_megatron_provider(load_weights=True) @@ -307,6 +309,9 @@ def init_phase(name: str) -> None: flush=True, ) + def _load_bridge(self, auto_bridge): + return auto_bridge.from_hf_pretrained(self.model_path, trust_remote_code=True) + def _configure_provider(self, max_seq_length: int) -> None: provider = self.provider provider.tensor_model_parallel_size = self.train_tp_size @@ -1246,17 +1251,22 @@ def _loss( weights = torch.exp(anchor - behavior) else: weights = loss_mask[action_positions] + return self._loss_from_actions( + current, anchor, advantages, weights, action_counts, micro_batch["rewards"], + ) + + def _loss_from_actions(self, current, anchor, advantages, weights, action_counts, rewards): log_ratio = current - anchor ratio = torch.exp(log_ratio.clamp(min=-20.0, max=20.0)) clipped = ratio.clamp(1.0 - self.clip_epsilon, 1.0 + self.clip_epsilon) weights_per_trajectory = weights / action_counts - sample_count = loss_mask.shape[0] + sample_count = rewards.numel() pg_per_action = torch.maximum(-advantages * ratio, -advantages * clipped) kl_per_action = (ratio - 1.0) - log_ratio pg = (weights_per_trajectory * pg_per_action).sum() / sample_count kl = (weights_per_trajectory * kl_per_action).sum() / sample_count loss = pg + self.kl_coef * kl - if decoupled: + if is_decoupled(self): checks = torch.stack((torch.isfinite(current).all() & (current <= 1e-6).all(), torch.isfinite(weights).all() & (weights > 0).all(), torch.isfinite(loss))) # One combined host read before backward; no diagnostic reductions. @@ -1267,10 +1277,10 @@ def _loss( if not valid: raise FloatingPointError(message) return loss, dict(loss=loss.detach(), pg_loss=pg.detach(), kl=kl.detach(), - reward_sum=micro_batch["rewards"].sum().detach(), - n_samples=float(micro_batch["rewards"].numel()), n_updates=1.0) + reward_sum=rewards.sum().detach(), + n_samples=float(sample_count), n_updates=1.0) - def _reduce_stats(self, stats: dict[str, float]) -> dict[str, float]: + def _reduce_stats(self, stats: dict[str, float], *, with_context_parallel=True) -> dict[str, float]: updates = float(stats["n_updates"]) samples = float(stats["n_samples"]) values = torch.tensor( @@ -1289,7 +1299,7 @@ def _reduce_stats(self, stats: dict[str, float]) -> dict[str, float]: device=self._device(), ) group = self._parallel_state().get_data_parallel_group( - with_context_parallel=True + with_context_parallel=with_context_parallel ) dist.all_reduce(values, op=dist.ReduceOp.SUM, group=group) global_updates = values[5].clamp(min=1.0) diff --git a/engine/train_factory.py b/engine/train_factory.py index 1359a3e..395cd82 100644 --- a/engine/train_factory.py +++ b/engine/train_factory.py @@ -40,7 +40,12 @@ def create_train_engine(config: AsyncRLConfig) -> TrainEngine: ) if backend == "megatron_core": - return MegatronCoreTrainEngine( + engine_type = MegatronCoreTrainEngine + if getattr(config, "megatron_model_family", "default") == "deepseek_v4": + from RL_Framework.engine.deepseek_v4_train_engine import DeepSeekV4TrainEngine + + engine_type = DeepSeekV4TrainEngine + return engine_type( model_path=config.model_path, grpo_objective=getattr(config, "grpo_objective", "legacy"), learning_rate=config.learning_rate, diff --git a/patches/mcore-defer-ddp-grad-allocation.patch b/patches/mcore-defer-ddp-grad-allocation.patch new file mode 100644 index 0000000..34f214f --- /dev/null +++ b/patches/mcore-defer-ddp-grad-allocation.patch @@ -0,0 +1,51 @@ +--- a/megatron/core/distributed/param_and_grad_buffer.py ++++ b/megatron/core/distributed/param_and_grad_buffer.py +@@ -1317,15 +1317,12 @@ + allocate_param_buffer() + if self.nccl_ub: + allocate_grad_buffer() +- # Without nccl_ub the pool (if any) backs only param_data; grads stay plain. +- if not self.nccl_ub: +- allocate_grad_buffer() + + self.grad_data_size = 0 + self.param_data_size = 0 + self.param_data_cpu = None + +- # Finally, map param.data and param.main_grad fields to buffers. ++ # Map parameter data, then allocate and map independent gradient storage. + def _create_bucket(bucket_id, bucket_params, bucket_params_with_extra_main_grads): + """ + Look up precomputed bucket indices and create a new bucket. +@@ -1357,12 +1354,8 @@ + bucket_params_with_extra_main_grads=bucket_params_with_extra_main_grads, + ) + +- bucket_params = [] +- bucket_params_with_extra_main_grads = [] +- cur_bucket_id = 0 +- for param, param_name in params_with_names[::-1]: +- # Get parameter indices computed in previous loop. +- param_start_index, param_end_index, bucket_id = self.param_index_map[param] ++ for param, _ in reversed(params_with_names): ++ param_start_index, _, _ = self.param_index_map[param] + nvfp4_packed_param_start_index = None + if self.has_nvfp4_params: + nvfp4_packed_param_start_index, _, _ = self.nvfp4_packed_param_index_map[param] +@@ -1493,6 +1486,16 @@ + if getattr(param, "needs_nccl_mem", False): + param.register_ub_pool(self.param_nccl_mem_pool or self.nccl_mem_pool) + ++ if not self.nccl_ub and not uses_shared_param_grad_buffer: ++ # Independent gradient storage can be allocated after the original ++ # parameter storage has been replaced by views into param_data. ++ allocate_grad_buffer() ++ ++ bucket_params = [] ++ bucket_params_with_extra_main_grads = [] ++ cur_bucket_id = 0 ++ for param, param_name in reversed(params_with_names): ++ param_start_index, _, bucket_id = self.param_index_map[param] + # Grad buffer always uses full-numel offsets from param_index_map. + param.main_grad = self._get( + param.data.shape, param_start_index, buffer_type=BufferType.GRAD diff --git a/scripts/deepseek_v4_spec_rollout.py b/scripts/deepseek_v4_spec_rollout.py new file mode 100644 index 0000000..d9fe120 --- /dev/null +++ b/scripts/deepseek_v4_spec_rollout.py @@ -0,0 +1,136 @@ +"""Serve or verify a fixed-checkpoint DeepSeek V4 speculative rollout.""" + +from __future__ import annotations + +import argparse +import asyncio +import json +import math +import os +from pathlib import Path +import sys +import time + + +def speculative_config(model: Path, method: str) -> dict: + config = json.loads((model / "config.json").read_text()) + if config.get("model_type") != "deepseek_v4": + raise ValueError("Expected a DeepSeek V4 checkpoint") + block_size = config.get("dspark_block_size") + if method == "dspark": + if type(block_size) is not int or block_size < 2: + raise ValueError("DSpark requires a DeepSeek V4 checkpoint with a DSpark draft") + return {"method": method, "num_speculative_tokens": max(7, block_size), + "draft_sample_method": "greedy"} + if block_size or not config.get("num_nextn_predict_layers"): + raise ValueError("MTP requires the DeepSeek V4 checkpoint with a classic MTP draft") + return {"method": "mtp", "num_speculative_tokens": 1} + + +def serve(args: argparse.Namespace) -> None: + model = args.model.resolve(strict=True) + spec = speculative_config(model, args.method) + index = json.loads((model / "model.safetensors.index.json").read_text()) + missing = sorted({name for name in index["weight_map"].values() if not (model / name).is_file()}) + if missing: + raise ValueError(f"Incomplete DeepSeek V4 checkpoint, missing shards {missing}") + command = [ + sys.executable, "-m", "vllm.entrypoints.cli.main", "serve", str(model), + "--served-model-name", args.model_name, "--host", args.host, "--port", str(args.port), + "--distributed-executor-backend", "mp", + "--tensor-parallel-size", str(args.tensor_parallel_size), "--enable-expert-parallel", + "--kv-cache-dtype", "fp8", "--block-size", "256", "--tokenizer-mode", "deepseek_v4", + "--max-model-len", str(args.max_model_len), "--max-num-seqs", str(args.max_num_seqs), + "--gpu-memory-utilization", str(args.gpu_memory_utilization), + "--generation-config", "vllm", "--speculative-config", json.dumps(spec), + ] + if args.enforce_eager: + command.append("--enforce-eager") + print(json.dumps({"checkpoint": str(model), "speculative_config": spec, + "tensor_parallel_size": args.tensor_parallel_size}), flush=True) + os.execv(sys.executable, command) + + +async def speculative_counters(client, url: str) -> dict[str, float]: + response = await client.get(f"{url}/metrics") + response.raise_for_status() + prefix = "vllm:spec_decode_num_" + counters = dict.fromkeys(("drafts", "draft_tokens", "accepted_tokens"), 0.0) + for line in response.text.splitlines(): + if not line.startswith(prefix): + continue + metric, value, *_ = line.split() + name = metric.split("{", 1)[0].removeprefix(prefix).removesuffix("_total") + if name in counters: + counters[name] += float(value) + return counters + + +async def verify(args: argparse.Namespace) -> dict: + import httpx + from RL_Framework.engine.rollout_engine import VLLMRolloutEngine + + engine = VLLMRolloutEngine(host=args.host, port=args.port, model_path=args.model_name) + prompts = ( + "Continue the sequence with the next thirty integers separated by commas. 1, 2, 3, 4,", + "Continue this Python program with a docstring and the rest of the implementation.\n" + "def fibonacci(n: int) -> list[int]:\n", + "The days of the week in order are Monday, Tuesday,", + ) + async with httpx.AsyncClient(timeout=10) as client: + before = await speculative_counters(client, engine.base_url) + started = time.monotonic() + try: + rows = await asyncio.gather(*(engine.generate( + prompt, max_new_tokens=64, temperature=0.7, top_p=0.95, + seed=seed, ignore_eos=True, + ) for seed, prompt in enumerate(prompts))) + finally: + await engine.close() + elapsed = time.monotonic() - started + for row in rows: + if (not row["text"].strip() or len(row["tokens"]) != 64 or len(row["logprobs"]) != 64 + or not all(isinstance(lp, (float, int)) and math.isfinite(lp) and lp <= 0 + for lp in row["logprobs"])): + raise RuntimeError("Rollout did not return 64 tokens with finite logprobs") + + # Prometheus may collect engine counters after the HTTP reply is sent. + for _ in range(15): + after = await speculative_counters(client, engine.base_url) + delta = {name: after[name] - before[name] for name in before} + if 0 < delta["accepted_tokens"] <= delta["draft_tokens"] and delta["drafts"] > 0: + break + await asyncio.sleep(1) + else: + raise RuntimeError(f"No accepted speculative tokens recorded by {engine.base_url}: {delta}") + + return {"endpoint": engine.base_url, "model": args.model_name, "requests": len(rows), + "output_tokens": sum(len(row["tokens"]) for row in rows), "elapsed_seconds": elapsed, + **delta} + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + server = commands.add_parser("serve") + server.add_argument("--method", choices=("mtp", "dspark"), required=True) + server.add_argument("--model", type=Path, required=True) + server.add_argument("--tensor-parallel-size", type=int, default=8) + server.add_argument("--max-model-len", type=int, default=4096) + server.add_argument("--max-num-seqs", type=int, default=16) + server.add_argument("--gpu-memory-utilization", type=float, default=0.72) + server.add_argument("--enforce-eager", action="store_true") + probe = commands.add_parser("verify") + for command in (server, probe): + command.add_argument("--host", default="127.0.0.1") + command.add_argument("--port", type=int, default=8018) + command.add_argument("--model-name", required=True) + args = parser.parse_args() + if args.command == "serve": + serve(args) + else: + print(json.dumps(asyncio.run(verify(args)), allow_nan=False)) + + +if __name__ == "__main__": + main() diff --git a/scripts/validate_deepseek_v4_cuda.py b/scripts/validate_deepseek_v4_cuda.py new file mode 100644 index 0000000..8a47434 --- /dev/null +++ b/scripts/validate_deepseek_v4_cuda.py @@ -0,0 +1,111 @@ +"""Verify an actual full-weight Libra GRPO update on the CUDA V4 path.""" + +from __future__ import annotations + +import argparse +from dataclasses import replace +import hashlib +import json +import math +import os +from pathlib import Path + +import torch +import torch.distributed as dist + +from RL_Framework.config import load_config +from RL_Framework.engine.train_factory import create_train_engine + + +def run_gate(args: argparse.Namespace) -> None: + config = load_config(args.config) + model_path = Path(args.model).resolve(strict=True) + topology = ( + {"train_cp_size": args.cp_size, "train_dp_size": 0} + if args.cp_size is not None else {} + ) + config = replace(config, model_path=str(model_path), tokenizer_path=str(model_path), **topology) + if int(os.environ.get("WORLD_SIZE", "1")) != config.train_gpus: + raise ValueError(f"Launch with torchrun on {config.train_gpus} training ranks") + + engine = create_train_engine(config) + try: + engine.initialize(max_seq_length=config.max_seq_length) + local_batch = engine.get_local_batch_size(config.batch_size) + generator = torch.Generator().manual_seed(42 + engine.get_data_parallel_rank()) + vocab_size = engine.provider.vocab_size + trajectories = [] + for index in range(local_batch): + ids = torch.randint(0, vocab_size, (1, config.max_seq_length), generator=generator) + loss_mask = torch.zeros_like(ids) + loss_mask[:, -32:] = 1 + value = torch.tensor([1.0 if index % 2 == 0 else -1.0]) + trajectories.append({ + "input_ids": ids, + "attention_mask": torch.ones_like(ids), + "loss_mask": loss_mask, + "rewards": value, + "advantages": value, + }) + + engine.recompute_logprobs(trajectories) + if any(not torch.isfinite(row["logprobs"]).all() for row in trajectories): + raise FloatingPointError("Nonfinite recomputed logprobs") + logprobs = torch.cat([row["logprobs"] for row in trajectories]) + digest = hashlib.sha256(logprobs.contiguous().numpy().tobytes()).hexdigest() + parallel_state = engine._parallel_state() + if config.train_cp_size > 1: + digests = [None] * config.train_cp_size + dist.all_gather_object(digests, digest, group=parallel_state.get_context_parallel_group()) + if len(set(digests)) != 1: + raise RuntimeError("Context ranks disagree on the reconstructed logprobs") + probes = [] + for parameter in engine.model[0].parameters(): + if parameter.requires_grad and parameter.is_contiguous() and parameter.numel(): + view = parameter.detach().view(-1) + sample = view[::max(1, view.numel() // 64)][:64] + probes.append((sample, sample.clone())) + metrics = engine.grpo_update(trajectories) + if not all(math.isfinite(float(value)) for value in metrics.values()): + raise FloatingPointError("Nonfinite training metrics") + if metrics["n_samples"] != config.batch_size: + raise RuntimeError("Each global trajectory must be counted once") + if engine.optimizer_revision != 1: + raise RuntimeError("Expected exactly one optimizer update") + changed = torch.zeros((), dtype=torch.int32, device=engine._device()) + for current, before in probes: + changed.add_((current != before).any()) + dist.all_reduce(changed, op=dist.ReduceOp.SUM) + if changed.item() == 0: + raise RuntimeError("No sampled parameter changed after the optimizer step") + + output = Path(args.output) + output.mkdir(parents=True, exist_ok=True) + receipt = { + "rank": dist.get_rank(), + "cp_size": config.train_cp_size, + "cp_rank": parallel_state.get_context_parallel_rank(), + "dp_rank": engine.get_data_parallel_rank(), + "logprobs_sha256": digest, + "optimizer_revision": engine.optimizer_revision, + "changed_parameter_probes": changed.item(), + "peak_allocated_bytes": torch.cuda.max_memory_allocated(), + "peak_reserved_bytes": torch.cuda.max_memory_reserved(), + "metrics": metrics, + } + (output / f"rank_{dist.get_rank():04d}.json").write_text(json.dumps(receipt) + "\n") + dist.barrier() + if engine.is_main_process: + print(f"LIBRA_DEEPSEEK_V4_CUDA_GATE_PASSED ranks={dist.get_world_size()}", flush=True) + finally: + if dist.is_initialized(): + dist.destroy_process_group() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", required=True) + parser.add_argument("--cp-size", type=int, help="Override CP and derive DP from the training allocation") + parser.add_argument("--model", required=True, help="Local Hugging Face checkpoint directory") + parser.add_argument("--output", required=True, help="Run-specific shared receipt directory") + run_gate(parser.parse_args()) diff --git a/tests/test_deepseek_v4_cuda.py b/tests/test_deepseek_v4_cuda.py new file mode 100644 index 0000000..2c0924a --- /dev/null +++ b/tests/test_deepseek_v4_cuda.py @@ -0,0 +1,171 @@ +"""CPU regression checks for Libra's V4 pipeline adapter.""" + +from dataclasses import replace +from pathlib import Path +import sys +from types import ModuleType, SimpleNamespace + +import pytest +import torch + +from RL_Framework.config import load_config +from RL_Framework.engine.train_factory import create_train_engine + + +def test_h20_gate_config_selects_v4_pipeline(): + path = Path(__file__).resolve().parents[1] / "configs/deepseek_v4_flash_h20_32_train_gate.yaml" + config = load_config(str(path)) + assert (config.train_tp_size, config.train_pp_size, config.train_ep_size, config.train_dp_size) == (1, 4, 8, 8) + assert create_train_engine(config).supports_pipeline_parallelism + with pytest.raises(ValueError, match="requires train_pp_size=1"): + replace(config, megatron_model_family="default") + with pytest.raises(ValueError, match="complete GRPO groups"): + replace(config, batch_size=24) + + +@pytest.mark.parametrize("cp_size", [1, 2, 3, 4, 6, 12]) +def test_v4_config_derives_logical_dp_for_48_training_gpus(cp_size): + path = Path(__file__).resolve().parents[1] / "configs/deepseek_v4_flash_h20_32_train_gate.yaml" + config = replace(load_config(str(path)), train_gpus=48, train_pp_size=4, + train_ep_size=4, train_cp_size=cp_size, train_dp_size=0, batch_size=24) + assert config.train_dp_size == 12 // cp_size + assert create_train_engine(config).train_cp_size == cp_size + with pytest.raises(ValueError, match="must divide DP"): + replace(config, train_ep_size=8) + + +@pytest.mark.parametrize("cp_size", [2, 3, 4]) +def test_v4_cp_shards_preserve_action_logprobs_and_gradient(monkeypatch, cp_size): + from RL_Framework.engine import deepseek_v4_train_engine as module + + path = Path(__file__).resolve().parents[1] / "configs/deepseek_v4_flash_h20_32_train_gate.yaml" + config = replace(load_config(str(path)), train_gpus=48, train_ep_size=4, + train_cp_size=cp_size, train_dp_size=0, batch_size=24) + engine = create_train_engine(config) + packed_module = ModuleType("megatron.core.packed_seq_params") + packed_module.PackedSeqParams = SimpleNamespace + monkeypatch.setitem(sys.modules, packed_module.__name__, packed_module) + + generator = torch.Generator().manual_seed(19) + ids = torch.randint(0, 7, (2, 12), generator=generator) + # CP4 rank zero has no actions. CP3 rank zero owns the query for target 8. + mask = torch.tensor([[0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0], + [0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0]], dtype=torch.float32) + full_logits = torch.randn(2, 12, 7, generator=generator, requires_grad=True) + batch = dict(input_ids=ids, loss_mask=mask, length=10, + old_logprobs=torch.full((2, 12), -2.0), + advantages=torch.tensor([1., -1.]), rewards=torch.tensor([1., 2.])) + reference = engine._action_log_probs(full_logits, ids) + expected_loss, expected_stats = engine._loss(batch, full_logits) + expected_grad = torch.autograd.grad(expected_loss, full_logits)[0] + aligned = torch.nn.functional.pad(reference[:, :9].detach(), (0, 3)).flatten() + width = ids.numel() // cp_size + total_loss = 0 + for rank in range(cp_size): + start = rank * width + stop = start + width + group = SimpleNamespace(size=lambda: cp_size, rank=lambda: rank) + + def model(*, input_ids, position_ids, packed_seq_params, **kwargs): + assert packed_seq_params.qkv_format == "thd" + assert packed_seq_params.cu_seqlens_q.tolist() == [0, 12, 24] + torch.testing.assert_close(input_ids[0], ids.flatten()[start:stop]) + torch.testing.assert_close(position_ids[0], torch.arange(start, stop) % 12) + return full_logits.reshape(1, 24, 7)[:, start:stop] + + def gather(output, local, *, group): + torch.testing.assert_close(local, aligned[start:stop]) + output.copy_(aligned) + + monkeypatch.setattr(module.dist, "all_gather_into_tensor", gather) + with torch.no_grad(): + logits, objective = engine._forward_context_shard( + batch, model, group, forward_only=True, + ) + torch.testing.assert_close(objective(logits)[1], reference[:, :9]) + logits, objective = engine._forward_context_shard( + batch, model, group, forward_only=False, + ) + loss, stats = objective(logits) + assert stats["n_samples"] == expected_stats["n_samples"] + total_loss += loss + torch.testing.assert_close(total_loss, expected_loss) + torch.testing.assert_close(torch.autograd.grad(total_loss, full_logits)[0], expected_grad) + + +def test_v4_schedule_preserves_actions_when_padding_variable_lengths(monkeypatch): + path = Path(__file__).resolve().parents[1] / "configs/deepseek_v4_flash_h20_32_train_gate.yaml" + engine = create_train_engine(load_config(str(path))) + engine._device = lambda: torch.device("cpu") + engine.tokenizer = SimpleNamespace(pad_token_id=0) + engine.max_seq_length = 8 + engine.optimizer = SimpleNamespace(scale_loss=lambda loss: loss) + model_config = SimpleNamespace() + + class TinyPolicy(torch.nn.Module): + def __init__(self): + super().__init__() + self.embedding = torch.nn.Embedding(8, 8) + + def forward(self, *, input_ids, position_ids, attention_mask, labels): + assert input_ids.shape == (1, 8) + return self.embedding(input_ids) + + model = TinyPolicy() + engine.model = [model] + + def schedule(*, forward_step_func, data_iterator, model, num_microbatches, + seq_length, micro_batch_size, forward_only): + assert seq_length == 8 and micro_batch_size == 1 + stats = [] + for _ in range(num_microbatches): + logits, objective = forward_step_func(data_iterator, model[0]) + loss, item = objective(logits) + if not forward_only: + (model_config.grad_scale_func(loss) / num_microbatches).backward() + stats.append(item) + return stats + + symbols = { + "megatron.core.distributed": {"finalize_model_grads": lambda model: None}, + "megatron.core.pipeline_parallel": {"get_forward_backward_func": lambda: schedule}, + "megatron.core.utils": {"get_model_config": lambda model: model_config}, + } + for name, attrs in symbols.items(): + module = ModuleType(name) + vars(module).update(attrs) + monkeypatch.setitem(sys.modules, name, module) + + trajectories = [ + { + "input_ids": torch.arange(length).unsqueeze(0), + "loss_mask": torch.tensor([[0] + [1] * (length - 1)]), + "rewards": torch.tensor([1.0]), + } + for length in (3, 5) + ] + logprobs = engine._pipeline(trajectories, forward_only=True) + for row, actual in zip(trajectories, logprobs): + ids = row["input_ids"] + expected = model.embedding(ids)[:, :-1].log_softmax(dim=-1) + expected = expected.gather(-1, ids[:, 1:].unsqueeze(-1)).squeeze(-1) + torch.testing.assert_close(actual, expected) + row["logprobs"] = torch.cat((torch.zeros(1, 1), actual.detach()), dim=1) + stats = engine._pipeline(trajectories, forward_only=False) + assert sum(item["n_samples"] for item in stats) == 2 + assert all(torch.isfinite(item["loss"]) for item in stats) + assert model.embedding.weight.grad is not None + assert model.embedding.weight.grad[5:].count_nonzero() == 0 + + +def test_v4_gradient_clipping_supports_mixed_precision(): + from RL_Framework.engine.deepseek_v4_train_engine import _gradient_norms, _scale_gradients + + grads = [torch.tensor([3., 4.], dtype=torch.bfloat16), + torch.tensor([0., 12.], dtype=torch.float32)] + total, norms = _gradient_norms(None, None, [grads], per_tensor=True) + torch.testing.assert_close(norms, torch.tensor([5., 12.])) + torch.testing.assert_close(total, torch.tensor([13.])) + _scale_gradients(None, None, [grads, grads], torch.tensor([0.5])) + torch.testing.assert_close(grads[0].float(), torch.tensor([1.5, 2.])) + torch.testing.assert_close(grads[1], torch.tensor([0., 6.])) diff --git a/tests/test_deepseek_v4_spec_rollout.py b/tests/test_deepseek_v4_spec_rollout.py new file mode 100644 index 0000000..c16dbed --- /dev/null +++ b/tests/test_deepseek_v4_spec_rollout.py @@ -0,0 +1,40 @@ +import asyncio +import json +from types import SimpleNamespace + +import pytest + +from RL_Framework.scripts.deepseek_v4_spec_rollout import speculative_config, speculative_counters + + +@pytest.mark.parametrize(("method", "block_size", "expected"), [ + ("mtp", None, {"method": "mtp", "num_speculative_tokens": 1}), + ("dspark", 5, {"method": "dspark", "num_speculative_tokens": 7, + "draft_sample_method": "greedy"}), +]) +def test_selects_compatible_v4_draft(tmp_path, method, block_size, expected): + config = {"model_type": "deepseek_v4", "num_nextn_predict_layers": 1} + if block_size is not None: + config["dspark_block_size"] = block_size + (tmp_path / "config.json").write_text(json.dumps(config)) + assert speculative_config(tmp_path, method) == expected + with pytest.raises(ValueError, match="requires"): + speculative_config(tmp_path, "mtp" if method == "dspark" else "dspark") + + +def test_speculative_counters_aggregate_only_total_metrics(): + class Client: + async def get(self, url): + assert url == "http://rollout/metrics" + return SimpleNamespace(raise_for_status=lambda: None, text=( + '# TYPE vllm:spec_decode_num_drafts_total counter\n' + 'vllm:spec_decode_num_drafts_total{engine="0"} 4\n' + 'vllm:spec_decode_num_drafts_total{engine="1"} 6\n' + 'vllm:spec_decode_num_draft_tokens_total{engine="0"} 20\n' + 'vllm:spec_decode_num_accepted_tokens_total{engine="0"} 12\n' + 'vllm:spec_decode_num_accepted_tokens_per_pos_total{position="0"} 8\n' + )) + + assert asyncio.run(speculative_counters(Client(), "http://rollout")) == { + "drafts": 10, "draft_tokens": 20, "accepted_tokens": 12, + }