Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ __pycache__/
.mypy_cache/
.ruff_cache/
.venv/
.venv-*/
*.egg-info/
/.coverage
/htmlcov/

# macOS metadata
.DS_Store
Expand Down Expand Up @@ -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/
Expand Down
44 changes: 40 additions & 4 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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'"
Expand Down Expand Up @@ -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"
)
Expand All @@ -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:
Expand Down
32 changes: 32 additions & 0 deletions configs/deepseek_v4_flash_h20_32_train_gate.yaml
Original file line number Diff line number Diff line change
@@ -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
17 changes: 17 additions & 0 deletions configs/model_arch_config/deepseek-v4-flash.yaml
Original file line number Diff line number Diff line change
@@ -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
155 changes: 155 additions & 0 deletions docs/deepseek_v4_cuda.md
Original file line number Diff line number Diff line change
@@ -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.
Loading
Loading