> ## Documentation Index
> Fetch the complete documentation index at: https://miles.radixark.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Qwen4

> RL recipe for Qwen4-35B-A3B, the GDN + QSA hybrid MoE with hyper-connections, a host-resident PLE table and FP4 round-tripped attention K/V, on a single 4-GPU node.

Qwen4-35B-A3B support lands in [`radixark/miles#5141`](https://github.com/radixark/miles/pull/5141).

## 1. Model Introduction

[Qwen4-35B-A3B](https://huggingface.co/Qwen/Qwen4-35B-A3B) (`Qwen4MoeForConditionalGeneration`,
`model_type` `qwen4_moe`) is the architecture that [Qwen3.8-Flash-Next](https://miles.radixark.com/docs/models/qwen/qwen3-8-flash-next.md)
previewed, at a smaller size. Miles trains it with the same plugin
(`miles_plugins/models/qwen3_8_next/`), bridge and Megatron → HF conversion; read that page
for how hyper-connections, QSA sparse attention and the PLE table are built. This page covers
what is specific to Qwen4.

**Key highlights:**

* **40 layers, hybrid**: 30 GDN linear-attention layers + 10 QSA full-attention layers
  (every 4th layer is full attention).
* **256-expert MoE at top-8**, `moe-ffn-hidden-size 512`, plus a gated shared expert.
* **Shape**: hidden 2048, 16 attention heads, 2 query groups, `kv-channels 256`,
  vocab 248320, `--rotary-base 10000000` at `--rotary-percent 0.25`.
* **Hyper-connections** at every block (4 residual streams), PLE n-gram embedding at layer 2,
  one MTP layer (not mapped for training).
* **FP4 round-tripped K/V.** The full-attention layers attend over K/V that went through an
  FP4 round trip (one E4M3 scale per 16 elements, after qk-norm and RoPE). SGLang does this
  for every Qwen4 checkpoint, and the trainer applies the same fake-quant (straight-through in
  backward) when the checkpoint's `model_type` is `qwen4_moe`.

On parameters: the checkpoint holds 57 B, of which 20.5 B is the PLE n-gram table (frozen,
host-resident, never trained or synced) and 0.45 B the vision tower; the trainer owns \~35 B,
\~3 B of them active per token.

## 2. Supported Variants

| Variant | `--model-name` | Layers | GPUs |
| - | - | - | - |
| Full | `Qwen4-35B-A3B` | 40 | 4 (1 × 4) |

The launcher is the Qwen3.8-Next one, `scripts/run_qwen3_8_next.py`; `--model-name` selects
`megatron_model_type` `qwen4-35B-A3B` (`scripts/models/qwen4-35B-A3B.py`) and asserts the
4-GPU shape.

## 3. Environment Setup

Start from [`radixark/miles:dev`](https://miles.radixark.com/docs/developer/ci/02-docker-build). The SGLang engine must serve
`Qwen4MoeForConditionalGeneration` and normalize Qwen4's chat requests (its `reasoning_effort`
levels and keeping `</think>` for the reasoning parser); that support is not on `sglang-miles`
yet, so check the engine before launching:

```bash theme={null}
python -m sglang.launch_server --model-path /root/models/Qwen4-35B-A3B --trust-remote-code \
  --tp 2 --linear-attn-prefill-backend flashinfer
```

The tokenizer and processor are remote code. Where `HF_HOME` is read-only, point
`HF_MODULES_CACHE` at a writable directory, or loading them fails with `OSError: Read-only file system`.

### 3.1 Download model + dataset

```bash theme={null}
hf download Qwen/Qwen4-35B-A3B --local-dir /root/models/Qwen4-35B-A3B
hf download --repo-type dataset zhuzilin/dapo-math-17k --local-dir /root/datasets/dapo-math-17k
```

### 3.2 HF → Megatron `torch_dist` conversion

`--ref-load` resolves to `<--ckpt-dir>/qwen4-35B-A3B_torch_dist`. The output re-shards at
load, so the conversion layout does not have to match training:

```bash theme={null}
cd /root/miles
MODEL_ARGS_LINE="$(python3 miles/utils/external_utils/model_args_utils.py qwen4-35B-A3B)" || exit 1
read -ra MODEL_ARGS <<< "${MODEL_ARGS_LINE}"
CUDA_DEVICE_MAX_CONNECTIONS=1 CONVERT_KEEP_PP1=1 PYTHONPATH=/root/Megatron-LM \
  torchrun --nproc-per-node 2 tools/convert_hf_to_torch_dist.py \
  "${MODEL_ARGS[@]}" \
  --hf-checkpoint /root/models/Qwen4-35B-A3B \
  --save          /root/ckpt/qwen4-35B-A3B_torch_dist \
  --tensor-model-parallel-size 2 \
  --pipeline-model-parallel-size 1
```

The result is \~66 GiB: the trainable weights only, without the PLE table, the vision tower
and MTP.

## 4. Launch

On one 4-GPU node the launcher starts Ray itself (leave `MILES_SCRIPT_EXTERNAL_RAY` unset):

```bash theme={null}
cd /root/miles
python scripts/run_qwen3_8_next.py \
  --model-name Qwen4-35B-A3B \
  --num-nodes 1 --num-gpus-per-node 4 \
  --num-rollout 100 --rollout-max-response-len 4096 \
  --extra-args "--rollout-batch-size 16"
```

## 5. Recipe Configuration

### 5.1 Parallelism

| Shape | TP | PP | CP | EP | ETP | Rollout engines |
| - | - | - | - | - | - | - |
| 1 × 4 | 1 | 1 | 1 | 4 | 1 | 2 × SGLang TP 2 / EP 2 |

Training is colocated with rollout and adds `--optimizer-cpu-offload --overlap-cpu-optimizer-d2h-h2d --use-precision-aware-optimizer`: the fp32 master weights
and Adam moments of \~35 B trainable parameters do not fit next to the bf16 weights on four
H200s. The rest of the recipe (GRPO on DAPO-Math-17k, Adam at `--lr 1e-6`, disk offload
during rollout, SGLang flags) is the [Qwen3.8-Flash-Next recipe](https://miles.radixark.com/docs/models/qwen/qwen3-8-flash-next.md#5-recipe-configuration).

### 5.2 What differs from Qwen3.8-Flash-Next

* **Rollout routing replay is always on** (`--use-rollout-routing-replay`). The 256-expert
  top-8 router picks different experts in rollout and in training on enough tokens to make
  the train/rollout gap more than twice as large without it (table below).
* **Thinking is switched on with `enable_thinking`**: `--apply-chat-template-kwargs
  '{"enable_thinking":true}'`. The Qwen4 tokenizer rejects `thinking_mode`.
* **Reasoning effort** for serving and evaluation takes `xhigh`, `high`, `low` or `off`.

## 6. Results

DAPO on DAPO-Math-17k, 4 × H200, 4k response cap, 16 prompts × 8 samples per step,
`--lr 1e-6`, about 3 minutes per step. Over the first 95 steps the raw reward rises from 0.48
to 0.7–0.8 (5-step means, peak 0.82 at step 80) and the share of truncated responses falls
from 28 % to 9 %, while the trainer-vs-rollout gap stays flat: per-token KL 0.0018–0.0028 and
mean |Δ log p| 0.014–0.024 nats.

![Raw reward and trainer-vs-rollout policy mismatch over 95 DAPO steps](https://mintcdn.com/radixark/1PhZQ7Fw9sWTn7X2/assets/images/qwen4-rl-training.png?fit=max\&auto=format\&n=1PhZQ7Fw9sWTn7X2\&q=85\&s=4f3a19836b4549c96dbf29c06f330764)

Where the train/rollout gap comes from, at step 0 with the same weights:

| Config | `train_rollout_logprob_abs_diff` | `train_rollout_kl` |
| - | - | - |
| no routing replay, FP4 K/V on both sides | 0.050 | 0.013 |
| routing replay, FP4 K/V on both sides (the recipe) | 0.022 | 0.0025 |
| routing replay, FP4 K/V off on both sides | 0.0076 | 3.8e-4 |

With the FP4 round trip off on both sides the model sits at the bf16 floor. The remaining gap
in the recipe is the round trip amplifying GEMM-level noise: a 1-ulp difference in a block's
maximum can move its E4M3 scale and, with it, all 16 FP4 values. It is flat over training.

## 7. Notable quirks

* **`--check-weight-update-skip-list visual. ple_embedding.`** as for Qwen3.8-Flash-Next:
  the vision tower and the PLE table are never pushed from the trainer.
* **Serving on H200 with MTP**: do not pass `--mamba-ssm-dtype bfloat16`. FlashInfer's GDN
  MTP verify kernel requires an fp32 recurrent state there and aborts during CUDA graph
  capture.

## 8. Pairs Well With

* [Qwen3.8-Flash-Next](https://miles.radixark.com/docs/models/qwen/qwen3-8-flash-next.md) — the same architecture at 176 B
* [Qwen3-Next](https://miles.radixark.com/docs/models/qwen/qwen3-next.md) — the earlier GDN generation
* [True On-Policy](https://miles.radixark.com/docs/examples/infra-features/true-on-policy.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.