From aaa4fbe10977d1a30c926ff312f0a96f9d8df675 Mon Sep 17 00:00:00 2001 From: Lemon-412 Date: Thu, 26 Nov 2026 23:49:22 +0800 Subject: [PATCH 1/9] feat(qwen38): add full-length 32K MoK MXFP8 Muon SFT Initialize native MoK MXFP8 weights through Bridge and route mixed QSA through the DoSA boundary selector. Enable grouped FlashQLA on Blackwell and keep the standard BF16 vocabulary projection. --- .../patch/megatron/20260915-4a4de8657.patch | 73 +++++ .../scripts/run-qwen38-32k-mok-muon.sh | 280 ++++++++++++++++++ relax/backends/megatron/model_provider.py | 4 + .../qwen3_8/ops/qsa_mixed_ops/selector.py | 17 +- relax/models/qwen3_8/precision.py | 5 + 5 files changed, 377 insertions(+), 2 deletions(-) create mode 100755 examples/models/qwen3.8-flash-next/scripts/run-qwen38-32k-mok-muon.sh diff --git a/docker/patch/megatron/20260915-4a4de8657.patch b/docker/patch/megatron/20260915-4a4de8657.patch index b49bbfda42..34bb5a38a2 100644 --- a/docker/patch/megatron/20260915-4a4de8657.patch +++ b/docker/patch/megatron/20260915-4a4de8657.patch @@ -10611,4 +10611,77 @@ diff --git a/megatron/core/transformer/moe/moe_utils.py b/megatron/core/transfor return get_fp8_align_size(config.fp8_recipe) if config.fp4: return get_fp4_align_size(config.fp4_recipe) +diff --git a/megatron/core/ssm/gated_delta_net/common.py b/megatron/core/ssm/gated_delta_net/common.py +--- a/megatron/core/ssm/gated_delta_net/common.py ++++ b/megatron/core/ssm/gated_delta_net/common.py +@@ -422,6 +422,7 @@ + seq_len: int, + *gate_feats: tuple[torch.Tensor], + cp_size_headwise: int | None = None, ++ grouped_qk: bool = False, + ) -> dict[str, torch.Tensor]: + """ + Prepare all gated delta rule kernel inputs. +@@ -447,7 +448,7 @@ + value = value.reshape(batch, seq_len, -1, self.value_head_dim) + + # Apply L2 norm to query and key +- if self.use_qk_l2norm: ++ if self.use_qk_l2norm and not grouped_qk: + query_key = l2norm(query_key.contiguous()) + + # Split query and key +@@ -456,7 +457,7 @@ + + # Expand query and key if needed (grouped query attention) + repeat_factor = self.num_value_heads // self.num_key_heads +- if repeat_factor > 1: ++ if repeat_factor > 1 and not grouped_qk: + query = query.repeat_interleave(repeat_factor, dim=2) + key = key.repeat_interleave(repeat_factor, dim=2) + +diff --git a/megatron/core/ssm/gated_delta_net/gdn.py b/megatron/core/ssm/gated_delta_net/gdn.py +--- a/megatron/core/ssm/gated_delta_net/gdn.py ++++ b/megatron/core/ssm/gated_delta_net/gdn.py +@@ -5,6 +5,7 @@ + # This source code is licensed under the Apache license found in the + # LICENSE file in the root directory of this source tree. + ++import os + from functools import partial + from typing import Optional + +@@ -60,7 +61,14 @@ + self.dt_bias_dim = self.num_v_heads_local_tp + self.a_log_dim = self.num_v_heads_local_tp + +- if self.config.deterministic_mode: ++ self.use_flashqla_grouped = os.environ.get("RELAX_CP4_FLASH_QLA") == "1" ++ if self.use_flashqla_grouped: ++ if self.config.linear_cp_mode != "headwise" or self.gdn_pre_gated_delta_rule_fusion or self.config.deterministic_mode: ++ raise ValueError("Grouped FlashQLA requires headwise CP and the standard GDN input preparation") ++ from flash_qla import chunk_gated_delta_rule as flashqla_rule ++ ++ self.gated_delta_rule = flashqla_rule ++ elif self.config.deterministic_mode: + self.gated_delta_rule = torch_chunk_gated_delta_rule + else: + self.gated_delta_rule = chunk_gated_delta_rule +@@ -401,7 +409,7 @@ + **kernel_inputs, + initial_state=None, + output_final_state=False, +- use_qk_l2norm_in_kernel=False, ++ use_qk_l2norm_in_kernel=self.use_flashqla_grouped and self.use_qk_l2norm, + cu_seqlens=cu_seqlens_q, + cp_context=chunkwise_cp_context, + ) +@@ -586,6 +594,7 @@ + beta, + alpha, + cp_size_headwise=cp_size_headwise, ++ grouped_qk=self.use_flashqla_grouped, + ) + nvtx_range_pop(suffix="prepare_input_for_gated_delta_rule") + # END blackwell diff --git a/examples/models/qwen3.8-flash-next/scripts/run-qwen38-32k-mok-muon.sh b/examples/models/qwen3.8-flash-next/scripts/run-qwen38-32k-mok-muon.sh new file mode 100755 index 0000000000..0308c30fe8 --- /dev/null +++ b/examples/models/qwen3.8-flash-next/scripts/run-qwen38-32k-mok-muon.sh @@ -0,0 +1,280 @@ +#!/usr/bin/env bash +# Copyright (c) 2026 Relax Authors. All Rights Reserved. +# Full-length 32K text SFT on 4 x 8 Blackwell GPUs, TP1/PP1/CP1/EP8. +# Export MODEL_DIR, DATA_DIR, SAVE_DIR, MEGATRON and RAY_JOBS_ADDRESS. +# Use the Blackwell Megatron runtime with grouped FlashQLA support. +set -eo pipefail + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +RELAX_ROOT="$(cd -- "${SCRIPT_DIR}/../../../.." && pwd)" +export RELAX="${RELAX_ROOT}" +source "${RELAX_ROOT}/scripts/models/qwen38-flash-next.sh" +: "${MODEL_DIR:?Set MODEL_DIR to the HF model directory}" +: "${DATA_DIR:?Set DATA_DIR to the prompt-data directory or file}" +: "${SAVE_DIR:?Set SAVE_DIR to a persistent checkpoint root}" +: "${MEGATRON:?Set MEGATRON to the compatible Megatron-LM checkout}" +# Use the unified image's installed Bridge, Python dependencies and HybridEP. +# Do not prepend the pre-refactor /opt/qwen38-flash-next runtime. +: "${RELAX_HYBRID_EP_COMMIT:?Use the unified Blackwell image with HybridEP installed}" +export RAY_NO_WAIT="${RAY_NO_WAIT:-1}" +export RELAX_SKIP_CLUSTER_CLEANUP="${RELAX_SKIP_CLUSTER_CLEANUP:-1}" +export EXP_NAME="${EXP_NAME:-qwen38-32k-mok-muon}" # gitleaks:allow -- stable experiment/checkpoint identity +export PROJECT_NAME="${PROJECT_NAME:-Relax/sft/qwen38-qsa}" +# Preserve this recipe's setting when ray-job.sh resets the generic variable. +export QWEN38_CUDA_DEVICE_MAX_CONNECTIONS="${QWEN38_CUDA_DEVICE_MAX_CONNECTIONS:-32}" +now=$(date "+%Y%m%d-%H%M%S") +export SUBMISSION_ID="${SUBMISSION_ID:-${EXP_NAME}-${now}-$$}" + +# Use an exclusive Ray cluster; the operator must prevent concurrent training. +if [[ "${DRY_RUN:-0}" != 1 && -z "${RELAX_ENTRYPOINT_MODE:-}" ]]; then + exec bash "${RELAX}/scripts/entrypoint/ray-job.sh" "${BASH_SOURCE[0]}" "$@" +fi + +# Explicit driver/actor settings override entrypoint defaults (notably connections=1). +export QWEN38_DOSA_INTERVAL_CONFIG=${QWEN38_DOSA_INTERVAL_CONFIG:-'{"boundary_bins":1024}'} +ENV_ARGS=( + "NVTE_CUTEDSL_FUSED_GROUPED_MLP=${NVTE_CUTEDSL_FUSED_GROUPED_MLP:-0}" + "RELAX_CP4_FLASH_QLA=${RELAX_CP4_FLASH_QLA:-1}" + "RELAX_SKIP_NONFINITE_GRAD=${RELAX_SKIP_NONFINITE_GRAD:-0}" + MCORE_QSA_SPARSE_BACKEND=id_sparse + TORCHINDUCTOR_COMPILE_THREADS=1 + QWEN38_PLE_CPU_OFFLOAD=1 + "QWEN38_PLE_INPUT_HALO_CP=1" + "QWEN38_PLE_INPUT_HALO_TRANSPORT=${QWEN38_PLE_INPUT_HALO_TRANSPORT:-adaptive}" + "RELAX_HYBRID_EP_COMMIT=${RELAX_HYBRID_EP_COMMIT}" + "LD_LIBRARY_PATH=${LD_LIBRARY_PATH:-}" + RELAX_PROPAGATE_ENV_VARS=QWEN38_WORKSPACE,SAVE_DIR,RELAX_PROFILE_DIR,TENSORBOARD_DIR,CLEARML_CACHE_DIR,CLEARML_OFFLINE_MODE,PYTHONDONTWRITEBYTECODE,RELAX_HYBRID_EP_COMMIT,LD_LIBRARY_PATH,NVLINK_DOMAIN_SIZE,USE_MNNVL,CUDA_DEVICE_MAX_CONNECTIONS,QWEN38_RUN_DIR,RELAX_SKIP_NONFINITE_GRAD + NCCL_NVLS_ENABLE=0 + "PYTHONPATH=${RELAX}:${MEGATRON}" + "MEGATRON=${MEGATRON}" + "RELAX=${RELAX}" + PYTHONNOUSERSITE=1 + "CUDA_DEVICE_MAX_CONNECTIONS=${QWEN38_CUDA_DEVICE_MAX_CONNECTIONS}" + "NVTE_USE_CUTLASS_GROUPED_GEMM=${NVTE_USE_CUTLASS_GROUPED_GEMM:-0}" + PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True,garbage_collection_threshold:0.8 + TOKENIZERS_PARALLELISM=false + RELAX_QWEN38_QSA_FUSED_ATTENTION=0 + RELAX_QWEN38_RETAIN_QSA_ATTENTION=0 + RELAX_QWEN38_QSA_FIXED_POOL=0 + RELAX_QWEN38_QSA_SPARSE_BLOCKMASK=1 + "RELAX_QWEN38_RECORD_FUNCTION_TAGS=${RELAX_QWEN38_RECORD_FUNCTION_TAGS:-0}" + RELAX_QWEN38_QSA_LOCAL_QUERY=1 + RELAX_QWEN38_ROUTER_SORTED_REPLAY=1 + RELAX_QWEN38_QSA_ROUTED_QKV=1 + RELAX_QWEN38_QSA_RECOMPUTE_REPLAY=1 + RELAX_QWEN38_QSA_CPU_LAYOUT=0 + RELAX_QWEN38_PLE_STREAMED=0 + RELAX_QWEN38_GDN_OUTPUT_SAFE_CONFIG=1 + RELAX_QWEN38_FLA_CONV_CACHE_REUSE=1 + RELAX_QWEN38_QSA_COMMUNITY_BACKEND=mixed + "RELAX_QWEN38_QSA_MIXED_LONG_BACKEND=${RELAX_QWEN38_QSA_MIXED_LONG_BACKEND:-cute}" + "RELAX_QWEN38_QSA_MIXED_FLASH_MAX_LEN=${RELAX_QWEN38_QSA_MIXED_FLASH_MAX_LEN:--1}" + "RELAX_QWEN38_QSA_NV_MAX_PACK_TOKENS=${RELAX_QWEN38_QSA_NV_MAX_PACK_TOKENS:-0}" + "QWEN38_WORKSPACE=${RELAX}" + "SAVE_DIR=${SAVE_DIR}" + RELAX_SFT_RESIDENT_PARAM_OVERLAP=0 + RAY_OVERRIDE_JOB_RUNTIME_ENV=1 + "TENSORBOARD_DIR=${SAVE_DIR}/tensorboard" + "CLEARML_CACHE_DIR=${SAVE_DIR}/clearml" + CLEARML_OFFLINE_MODE=0 + "RELAX_PROFILE_DIR=${SAVE_DIR}/traces" + PYTHONDONTWRITEBYTECODE=1 + RELAX_PROFILE_RANKS=0,8,16,24 + RELAX_PROFILE_GZIP_LEVEL=1 + FLA_CACHE_RESULTS=1 + TRITON_CACHE_AUTOTUNING=1 + TORCHINDUCTOR_FX_GRAPH_CACHE=1 + TORCHINDUCTOR_AUTOTUNE_LOCAL_CACHE=1 + "RELAX_AUTOTUNE_LOG_DIR=${RELAX_AUTOTUNE_LOG_DIR-${SAVE_DIR}/autotune}" + RELAX_QWEN38_HC_FUSED_MIX=1 + RELAX_SFT_SELECTIVE_LOGITS=1 + RELAX_QWEN38_QSA_TP_SELECTOR=1 + RELAX_QWEN38_QSA_FUSED_SELECTOR=0 + RELAX_QWEN38_QSA_GROUPED_BACKWARD_WARPS=4 + RELAX_QWEN38_QSA_FLEX_SPARSE_MASK=1 + NVLINK_DOMAIN_SIZE=8 + USE_MNNVL=0 + RELAX_QWEN38_HC_FUSED_COMBINE=1 + RELAX_QWEN38_PLE_FUSED_CONV=1 + RELAX_SFT_FUSED_LINEAR_CE=1 + "RELAX_LOGPROB_CE_IMPL=native" + "QWEN38_RUN_DIR=${SAVE_DIR}" + RELAX_QWEN38_QSA_MIXED_FLEX_MAX_LEN=0 + RELAX_QWEN38_QSA_GROUPED_BACKWARD_STAGES=3 + RELAX_SFT_MTP_ACCEPTANCE_METRICS=0 + RELAX_QWEN38_QSA_GROUPED_BACKWARD_BLOCK_K=32 + RELAX_QWEN38_QSA_SELECTOR_COMPILE=1 + "RELAX_QWEN38_QSA_SELECTOR_BACKEND=${RELAX_QWEN38_QSA_SELECTOR_BACKEND:-dosa}" + "QWEN38_DOSA_VARIANT=${QWEN38_DOSA_VARIANT:-boundary}" + "QWEN38_DOSA_INTERVAL_CONFIG=${QWEN38_DOSA_INTERVAL_CONFIG}" + "RELAX_QWEN38_QSA_CP=${RELAX_QWEN38_QSA_CP:-1}" + "RELAX_QWEN38_GDN_CP_PREBUILD_ROUTE=${RELAX_QWEN38_GDN_CP_PREBUILD_ROUTE:-0}" + "RELAX_QWEN38_PLE_CP_FUSED_CONV=${RELAX_QWEN38_PLE_CP_FUSED_CONV:-0}" + "RELAX_QWEN38_QSA_CP_TP_SELECTOR=${RELAX_QWEN38_QSA_CP_TP_SELECTOR:-0}" +) +unset NUM_OF_HYBRID_EP_RANKS_PER_NVLINK_DOMAIN +export "${ENV_ARGS[@]}" +TRAIN_ENV_JSON=$(python3 - "${ENV_ARGS[@]}" <<'PYENV' +import json +import sys +print(json.dumps(dict(item.split("=", 1) for item in sys.argv[1:]))) +PYENV +) +BASE_RUNTIME_ENV_JSON="${RUNTIME_ENV_JSON:-}" +if [[ -z "${BASE_RUNTIME_ENV_JSON}" ]]; then BASE_RUNTIME_ENV_JSON='{}'; fi +RUNTIME_ENV_JSON=$(python3 - "${BASE_RUNTIME_ENV_JSON}" "${TRAIN_ENV_JSON}" <<'PYRUNTIME' +import json +import sys +runtime = json.loads(sys.argv[1]) +runtime.setdefault("env_vars", {}).pop("NUM_OF_HYBRID_EP_RANKS_PER_NVLINK_DOMAIN", None) +runtime["env_vars"].update(json.loads(sys.argv[2])) +print(json.dumps(runtime)) +PYRUNTIME +) + +PARALLEL_ARGS=( + --tensor-model-parallel-size 1 + --pipeline-model-parallel-size 1 + --context-parallel-size 1 + --expert-model-parallel-size 8 + --expert-tensor-parallel-size 1 + --pipeline-model-parallel-layout 'Et*48L' + --linear-cp-mode headwise + --moe-token-dispatcher-type alltoall + --cuda-graph-impl none + --moe-megakernel-backend mok + --moe-megakernel-backend-config "{\"shared_expert_mode\":\"native\",\"fixed_num_local_tokens\":32768}" + --moe-grouped-gemm + --colocate + --no-rope-fusion + --sft-chunked-logits + --sft-logits-chunk-size 2048 + --recompute-granularity full + --recompute-method uniform + --recompute-num-layers 2 + --no-offload-train + --empty-unused-memory-level 0 +) + +CKPT_ARGS=( + --hf-checkpoint "${MODEL_DIR}" + --ref-load "${MODEL_DIR}" + --megatron-to-hf-mode bridge + --num-rollout "${NUM_STEPS:-50}" + --load "${SAVE_DIR}/${EXP_NAME}" + --max-actor-ckpt-to-keep 2 +) + +SFT_ARGS=( + --loss-type sft + --prompt-data "${DATA_DIR}" + --custom-dataset-class examples.retool.sft_dataset.AuthorMaskedSFTDataset + --mtp-num-layers 0 + --input-key messages + --tool-key tools + --apply-chat-template + --apply-chat-template-kwargs '{"add_generation_prompt":false,"preserve_thinking":true}' + --sft-invalid-multimodal-strategy skip + --sft-oversize-strategy skip + --calculate-per-token-loss + --rollout-max-context-len 32768 + --global-batch-size "${GBS:-128}" + --rollout-batch-size "${GBS:-128}" + --n-samples-per-prompt 1 + --micro-batch-size 1 + --seq-length 32768 + --use-dynamic-batch-size + --max-tokens-per-gpu 32768 + --data-pad-size-multiplier 16384 + --per-rank-fetch + --sft-prefetch-num-workers 16 + --sft-train-data-prefetch + --freeze-vision-model + --freeze-vision-projection + --freeze-params-name-list '(^|\.)per_layer_embedding\.|self_attention\.indexer\.' +) +OPTIMIZER_ARGS=( + --optimizer muon + --muon-momentum 0.95 + --muon-nesterov + --muon-coefficient-type polar_express + --muon-num-ns-steps 8 + --muon-scale-mode spectral + --muon-extra-scale-factor 0.2 + --muon-tp-mode duplicated + --lr 2e-5 + --lr-decay-style cosine + --lr-decay-iters "${LR_DECAY_ITERS:-2023}" + --min-lr 2e-6 + --lr-warmup-fraction 0.05 + --lr-warmup-init 0 + --weight-decay 0.1 + --adam-beta1 0.9 + --adam-beta2 0.98 + --clip-grad 1.0 + --use-distributed-optimizer + --no-use-precision-aware-optimizer + --moe-aux-loss-coeff 0 +) + +MISC_ARGS=( + --seed 1234 + --bf16 + --fp8-format e4m3 + --fp8-recipe mxfp8 + --fp8-param-gather + --reuse-grad-buf-for-mxfp8-param-ag + --attention-dropout 0.0 + --hidden-dropout 0.0 + --attention-softmax-in-fp32 + --attention-backend flash + --accumulate-allreduce-grads-in-fp32 + --train-env-vars "${TRAIN_ENV_JSON}" + # Keep identical logical packing for both comparison arms. + --overlap-grad-reduce + --overlap-param-gather +) +if [[ "${QWEN38_SFT_HEALTH_CHECK:-1}" == 1 ]]; then + MISC_ARGS+=(--use-health-check) +fi + +METRICS_ARGS=( + --use-clearml + --use-metrics-service + --tb-project-name "${PROJECT_NAME}" + --tb-experiment-name "${EXP_NAME}-${now}" +) + +TRAIN_ARGS=( + --resource '{"sft":[1,0],"actor":[1,32]}' + --actor-num-nodes 4 + --actor-num-gpus-per-node 8 + --sft-max-in-flight-steps 4 + --num-data-storage-units 2 + "${MODEL_ARGS[@]}" + "${CKPT_ARGS[@]}" + "${SFT_ARGS[@]}" + "${PARALLEL_ARGS[@]}" + "${OPTIMIZER_ARGS[@]}" + "${MISC_ARGS[@]}" + "${METRICS_ARGS[@]}" + "$@" +) + +if [[ "${DRY_RUN:-0}" == 1 ]]; then + python3 - "${RUNTIME_ENV_JSON}" python3 -m relax.entrypoints.train "${TRAIN_ARGS[@]}" <<'PYDRY' +import json +import sys +print(json.dumps({"runtime_env": json.loads(sys.argv[1]), "argv": sys.argv[2:]}, indent=2)) +PYDRY + exit 0 +fi + +cd "${RELAX}" +mkdir -p "${SAVE_DIR}/logs" +ray job submit ${RAY_NO_WAIT:+--no-wait} \ + --submission-id "${SUBMISSION_ID}" \ + ${WORKING_DIR:+--working-dir "${WORKING_DIR}"} \ + --runtime-env-json="${RUNTIME_ENV_JSON}" \ + -- python3 -m relax.entrypoints.train "${TRAIN_ARGS[@]}" \ + 2>&1 | tee "${SAVE_DIR}/logs/${EXP_NAME}-${now}.log" diff --git a/relax/backends/megatron/model_provider.py b/relax/backends/megatron/model_provider.py index be8cfaefec..3115b0cc24 100644 --- a/relax/backends/megatron/model_provider.py +++ b/relax/backends/megatron/model_provider.py @@ -515,6 +515,10 @@ def wrapped_model_provider( if getattr(provider, "vision_dp_when_cp", False): _install_bridge_vision_cp_all_gather_compat() + # MoK constructs its MXFP8 weights before DDP from the provider config. + if getattr(args, "moe_megakernel_backend", None) == "mok" and getattr(args, "fp8_recipe", None) == "mxfp8": + provider.fp8_param = bool(args.fp8_param_gather) + # Handle name-mismatched attributes that require explicit mapping if getattr(args, "decoder_first_pipeline_num_layers", None) is not None: provider.num_layers_in_first_pipeline_stage = args.decoder_first_pipeline_num_layers diff --git a/relax/models/qwen3_8/ops/qsa_mixed_ops/selector.py b/relax/models/qwen3_8/ops/qsa_mixed_ops/selector.py index 48126d5761..a3db141011 100644 --- a/relax/models/qwen3_8/ops/qsa_mixed_ops/selector.py +++ b/relax/models/qwen3_8/ops/qsa_mixed_ops/selector.py @@ -102,8 +102,8 @@ def forward( ): raise NotImplementedError("TP selector supports CP1 frozen Stage-1 selected IDs") selector_backend = os.environ.get("RELAX_QWEN38_QSA_SELECTOR_BACKEND", "torch") - if selector_backend not in ("torch", "radix"): - raise ValueError("QSA selector backend must be torch or radix") + if selector_backend not in ("torch", "radix", "dosa"): + raise ValueError("QSA selector backend must be torch, radix or dosa") if not self.config.layernorm_zero_centered_gamma: raise NotImplementedError("Gemma RMSNorm requires zero-centered gamma weights") if ( @@ -186,6 +186,19 @@ def forward( pooled = _apply_rotary_pos_emb_bshd( pooled[:, None, None, :], key_freqs, rotary_interleaved=self.config.rotary_interleaved )[:, 0, 0] + if selector_backend == "dosa": + from relax.models.qwen3_8.ops.qsa_cute.selector import select_ids + + # CuTe constructs canonical block metadata from the selected set. + # Other attention consumers retain the ordered-ID contract. + boundary = ( + os.environ.get("QWEN38_DOSA_VARIANT") == "boundary" + and os.environ.get("RELAX_QWEN38_QSA_MIXED_LONG_BACKEND") == "cute" + ) + selected[first - first_query : last - first_query] = select_ids( + q[first:last], pooled, positions[first:last], topk, impl="dosa-set" if boundary else "dosa" + ) + continue for a in range(first - start, last - start, 512): b = min(a + 512, last - start) local_positions = torch.arange(a, b, device=hidden.device) diff --git a/relax/models/qwen3_8/precision.py b/relax/models/qwen3_8/precision.py index 973602ead1..eff91af264 100644 --- a/relax/models/qwen3_8/precision.py +++ b/relax/models/qwen3_8/precision.py @@ -126,6 +126,11 @@ def configure_fp8(model: torch.nn.Module, args: Namespace) -> dict[str, str]: raise ValueError( "Qwen3.8 FP8 parameters require MXFP8, --use-distributed-optimizer and --reuse-grad-buf-for-mxfp8-param-ag" ) + if primary_fp8 and recipe == "mxfp8" and getattr(args, "moe_megakernel_backend", None) == "mok": + # MoK owns routed expert weights. Native TE projections inherit the global + # recipe and the standard (non-TE) vocabulary head stays in BF16. + logger.info("Qwen3.8 MoK uses native MXFP8 parameter initialization and global TE precision") + return {} if primary_fp8 and getattr(args, "overlap_param_gather", False): raise ValueError("Qwen3.8 FP8 parameter storage currently requires synchronous parameter gather") alignment = {"mxfp8": 32, "blockwise": 128, "tensorwise": 16}.get(recipe) From 7c20557ac7a3d4c324e7e11aadb0da01bc5127b0 Mon Sep 17 00:00:00 2001 From: Lemon-412 Date: Fri, 27 Nov 2026 00:02:48 +0800 Subject: [PATCH 2/9] fix(qwen38): recognize layer-wise distributed Muon for MoK Megatron normalizes the distributed optimizer flag for Muon before the model is constructed. Validate that normalized mode for native MXFP8 weights and cover the startup failure with a regression test. --- relax/backends/megatron/model_provider.py | 7 +++++- relax/models/qwen3_8/precision.py | 22 ++++++++++++------- .../megatron/test_qwen38_fp8_hf_import.py | 22 +++++++++++++++++++ 3 files changed, 42 insertions(+), 9 deletions(-) diff --git a/relax/backends/megatron/model_provider.py b/relax/backends/megatron/model_provider.py index 3115b0cc24..f1b79449a7 100644 --- a/relax/backends/megatron/model_provider.py +++ b/relax/backends/megatron/model_provider.py @@ -516,7 +516,12 @@ def wrapped_model_provider( _install_bridge_vision_cp_all_gather_compat() # MoK constructs its MXFP8 weights before DDP from the provider config. - if getattr(args, "moe_megakernel_backend", None) == "mok" and getattr(args, "fp8_recipe", None) == "mxfp8": + if ( + getattr(args, "moe_megakernel_backend", None) == "mok" + and getattr(args, "fp8_recipe", None) == "mxfp8" + and getattr(args, "optimizer", None) == "muon" + and getattr(args, "use_layer_wise_distributed_optimizer", False) + ): provider.fp8_param = bool(args.fp8_param_gather) # Handle name-mismatched attributes that require explicit mapping diff --git a/relax/models/qwen3_8/precision.py b/relax/models/qwen3_8/precision.py index eff91af264..66b0e9baf3 100644 --- a/relax/models/qwen3_8/precision.py +++ b/relax/models/qwen3_8/precision.py @@ -113,23 +113,26 @@ def configure_fp8(model: torch.nn.Module, args: Namespace) -> dict[str, str]: if getattr(args, "te_precision_config_file", None): raise ValueError("Qwen3.8 MoE FP8 cannot be combined with a separate TE precision config") - from megatron.core.quantization.quant_config import MatchContext, QuantizationConfig - from transformer_engine import pytorch as te - recipe = getattr(args.fp8_recipe, "value", args.fp8_recipe) primary_fp8 = getattr(args, "fp8_param_gather", False) + mok_muon = ( + primary_fp8 + and recipe == "mxfp8" + and getattr(args, "moe_megakernel_backend", None) == "mok" + and getattr(args, "optimizer", None) == "muon" + and getattr(args, "use_layer_wise_distributed_optimizer", False) + ) if primary_fp8 and ( recipe != "mxfp8" - or not getattr(args, "use_distributed_optimizer", False) + or not (mok_muon or getattr(args, "use_distributed_optimizer", False)) or not getattr(args, "reuse_grad_buf_for_mxfp8_param_ag", False) ): raise ValueError( "Qwen3.8 FP8 parameters require MXFP8, --use-distributed-optimizer and --reuse-grad-buf-for-mxfp8-param-ag" ) - if primary_fp8 and recipe == "mxfp8" and getattr(args, "moe_megakernel_backend", None) == "mok": - # MoK owns routed expert weights. Native TE projections inherit the global - # recipe and the standard (non-TE) vocabulary head stays in BF16. - logger.info("Qwen3.8 MoK uses native MXFP8 parameter initialization and global TE precision") + if mok_muon: + # Native TE projections inherit global MXFP8 and MoK owns its expert weights. + logger.info("Qwen3.8 MoK uses native MXFP8 weights with layer-wise distributed Muon") return {} if primary_fp8 and getattr(args, "overlap_param_gather", False): raise ValueError("Qwen3.8 FP8 parameter storage currently requires synchronous parameter gather") @@ -137,6 +140,9 @@ def configure_fp8(model: torch.nn.Module, args: Namespace) -> dict[str, str]: if alignment is None: raise ValueError(f"Qwen3.8 MoE FP8 does not support recipe {recipe!r}") + from megatron.core.quantization.quant_config import MatchContext, QuantizationConfig + from transformer_engine import pytorch as te + plan: dict[str, str] = {} pending = [] for name, module in model.named_modules(): diff --git a/tests/cpu/backends/megatron/test_qwen38_fp8_hf_import.py b/tests/cpu/backends/megatron/test_qwen38_fp8_hf_import.py index 6f764ef949..b0786ff3d4 100644 --- a/tests/cpu/backends/megatron/test_qwen38_fp8_hf_import.py +++ b/tests/cpu/backends/megatron/test_qwen38_fp8_hf_import.py @@ -460,6 +460,28 @@ def precision(): return precision +def test_mok_primary_weights_support_layer_wise_muon(precision): + args = SimpleNamespace( + fp8="e4m3", + bf16=True, + fp8_recipe="mxfp8", + fp8_param_gather=True, + moe_megakernel_backend="mok", + optimizer="muon", + use_layer_wise_distributed_optimizer=True, + use_distributed_optimizer=False, + reuse_grad_buf_for_mxfp8_param_ag=True, + overlap_param_gather=True, + ) + model = torch.nn.Linear(32, 32, dtype=torch.bfloat16) + weight = model.weight + assert precision.configure_fp8(model, args) == {} + assert model.weight is weight + args.use_layer_wise_distributed_optimizer = False + with pytest.raises(ValueError, match="use-distributed-optimizer"): + precision.configure_fp8(model, args) + + @pytest.mark.parametrize("source", ["bf16", "other_model", "fp8_patched", "fp8_unpatched", "fp8_nested_unpatched"]) def test_fp8_source_guard_requires_scale_aware_bridge(precision, source): config = SimpleNamespace( From 8d43b845ee1eede21435526e7fbec93b264b8cef Mon Sep 17 00:00:00 2001 From: Lemon-412 Date: Fri, 27 Nov 2026 14:07:44 +0800 Subject: [PATCH 3/9] fix(qwen38): preserve Ray submission and grouped GDN fallback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Wait for Ray's terminal status by default, honor the Jobs address, keep the launcher library paths for the driver and actors, and save to the resume directory. The MoK path has no HybridEP installation dependency. Let FLA select the grouped GDN backend. For two Q/K heads and six V heads the indices are [0, 0, 0, 1, 1, 1], matching repeat_interleave. With normalization enabled the FlashQLA wrapper applies l2norm_fwd before grouped GDN. Keep the Qwen3.5 preprocessing contract intact. 20-step comparison on 7c20557a used identical logical packing, model, seed, data and LR. Max absolute loss delta was 0.01440. Steps 3–19 averaged 5463.25 vs 5568.06 tokens/s/GPU. This measurement predates the FLA dispatch change. --- .../patch/megatron/20260915-4a4de8657.patch | 24 +++++++-------- .../scripts/run-qwen38-32k-mok-muon.sh | 29 ++++++++++--------- .../megatron/test_qwen38_fp8_hf_import.py | 2 +- 3 files changed, 28 insertions(+), 27 deletions(-) diff --git a/docker/patch/megatron/20260915-4a4de8657.patch b/docker/patch/megatron/20260915-4a4de8657.patch index 34bb5a38a2..78dc523028 100644 --- a/docker/patch/megatron/20260915-4a4de8657.patch +++ b/docker/patch/megatron/20260915-4a4de8657.patch @@ -10651,28 +10651,26 @@ diff --git a/megatron/core/ssm/gated_delta_net/gdn.py b/megatron/core/ssm/gated_ from functools import partial from typing import Optional -@@ -60,7 +61,14 @@ +@@ -60,6 +61,13 @@ self.dt_bias_dim = self.num_v_heads_local_tp self.a_log_dim = self.num_v_heads_local_tp -- if self.config.deterministic_mode: -+ self.use_flashqla_grouped = os.environ.get("RELAX_CP4_FLASH_QLA") == "1" -+ if self.use_flashqla_grouped: -+ if self.config.linear_cp_mode != "headwise" or self.gdn_pre_gated_delta_rule_fusion or self.config.deterministic_mode: -+ raise ValueError("Grouped FlashQLA requires headwise CP and the standard GDN input preparation") -+ from flash_qla import chunk_gated_delta_rule as flashqla_rule -+ -+ self.gated_delta_rule = flashqla_rule -+ elif self.config.deterministic_mode: ++ self.grouped_qk = ( ++ os.environ.get("RELAX_CP4_FLASH_QLA") == "1" ++ and self.config.linear_cp_mode == "headwise" ++ and not self.gdn_pre_gated_delta_rule_fusion ++ and not self.config.deterministic_mode ++ and not getattr(self.config, "_relax_qwen35_optimized", False) ++ ) + if self.config.deterministic_mode: self.gated_delta_rule = torch_chunk_gated_delta_rule else: - self.gated_delta_rule = chunk_gated_delta_rule @@ -401,7 +409,7 @@ **kernel_inputs, initial_state=None, output_final_state=False, - use_qk_l2norm_in_kernel=False, -+ use_qk_l2norm_in_kernel=self.use_flashqla_grouped and self.use_qk_l2norm, ++ use_qk_l2norm_in_kernel=self.grouped_qk and self.use_qk_l2norm, cu_seqlens=cu_seqlens_q, cp_context=chunkwise_cp_context, ) @@ -10680,7 +10678,7 @@ diff --git a/megatron/core/ssm/gated_delta_net/gdn.py b/megatron/core/ssm/gated_ beta, alpha, cp_size_headwise=cp_size_headwise, -+ grouped_qk=self.use_flashqla_grouped, ++ grouped_qk=self.grouped_qk, ) nvtx_range_pop(suffix="prepare_input_for_gated_delta_rule") diff --git a/examples/models/qwen3.8-flash-next/scripts/run-qwen38-32k-mok-muon.sh b/examples/models/qwen3.8-flash-next/scripts/run-qwen38-32k-mok-muon.sh index 0308c30fe8..fc7a0ad591 100755 --- a/examples/models/qwen3.8-flash-next/scripts/run-qwen38-32k-mok-muon.sh +++ b/examples/models/qwen3.8-flash-next/scripts/run-qwen38-32k-mok-muon.sh @@ -13,10 +13,6 @@ source "${RELAX_ROOT}/scripts/models/qwen38-flash-next.sh" : "${DATA_DIR:?Set DATA_DIR to the prompt-data directory or file}" : "${SAVE_DIR:?Set SAVE_DIR to a persistent checkpoint root}" : "${MEGATRON:?Set MEGATRON to the compatible Megatron-LM checkout}" -# Use the unified image's installed Bridge, Python dependencies and HybridEP. -# Do not prepend the pre-refactor /opt/qwen38-flash-next runtime. -: "${RELAX_HYBRID_EP_COMMIT:?Use the unified Blackwell image with HybridEP installed}" -export RAY_NO_WAIT="${RAY_NO_WAIT:-1}" export RELAX_SKIP_CLUSTER_CLEANUP="${RELAX_SKIP_CLUSTER_CLEANUP:-1}" export EXP_NAME="${EXP_NAME:-qwen38-32k-mok-muon}" # gitleaks:allow -- stable experiment/checkpoint identity export PROJECT_NAME="${PROJECT_NAME:-Relax/sft/qwen38-qsa}" @@ -25,6 +21,10 @@ export QWEN38_CUDA_DEVICE_MAX_CONNECTIONS="${QWEN38_CUDA_DEVICE_MAX_CONNECTIONS: now=$(date "+%Y%m%d-%H%M%S") export SUBMISSION_ID="${SUBMISSION_ID:-${EXP_NAME}-${now}-$$}" +if [[ "${DRY_RUN:-0}" != 1 ]]; then + : "${RAY_JOBS_ADDRESS:?Set RAY_JOBS_ADDRESS to the Ray Jobs endpoint}" +fi + # Use an exclusive Ray cluster; the operator must prevent concurrent training. if [[ "${DRY_RUN:-0}" != 1 && -z "${RELAX_ENTRYPOINT_MODE:-}" ]]; then exec bash "${RELAX}/scripts/entrypoint/ray-job.sh" "${BASH_SOURCE[0]}" "$@" @@ -41,9 +41,8 @@ ENV_ARGS=( QWEN38_PLE_CPU_OFFLOAD=1 "QWEN38_PLE_INPUT_HALO_CP=1" "QWEN38_PLE_INPUT_HALO_TRANSPORT=${QWEN38_PLE_INPUT_HALO_TRANSPORT:-adaptive}" - "RELAX_HYBRID_EP_COMMIT=${RELAX_HYBRID_EP_COMMIT}" "LD_LIBRARY_PATH=${LD_LIBRARY_PATH:-}" - RELAX_PROPAGATE_ENV_VARS=QWEN38_WORKSPACE,SAVE_DIR,RELAX_PROFILE_DIR,TENSORBOARD_DIR,CLEARML_CACHE_DIR,CLEARML_OFFLINE_MODE,PYTHONDONTWRITEBYTECODE,RELAX_HYBRID_EP_COMMIT,LD_LIBRARY_PATH,NVLINK_DOMAIN_SIZE,USE_MNNVL,CUDA_DEVICE_MAX_CONNECTIONS,QWEN38_RUN_DIR,RELAX_SKIP_NONFINITE_GRAD + RELAX_PROPAGATE_ENV_VARS=QWEN38_WORKSPACE,SAVE_DIR,RELAX_PROFILE_DIR,TENSORBOARD_DIR,CLEARML_CACHE_DIR,CLEARML_OFFLINE_MODE,PYTHONDONTWRITEBYTECODE,LD_LIBRARY_PATH,NVLINK_DOMAIN_SIZE,USE_MNNVL,CUDA_DEVICE_MAX_CONNECTIONS,QWEN38_RUN_DIR,RELAX_SKIP_NONFINITE_GRAD NCCL_NVLS_ENABLE=0 "PYTHONPATH=${RELAX}:${MEGATRON}" "MEGATRON=${MEGATRON}" @@ -112,12 +111,14 @@ ENV_ARGS=( "RELAX_QWEN38_PLE_CP_FUSED_CONV=${RELAX_QWEN38_PLE_CP_FUSED_CONV:-0}" "RELAX_QWEN38_QSA_CP_TP_SELECTOR=${RELAX_QWEN38_QSA_CP_TP_SELECTOR:-0}" ) -unset NUM_OF_HYBRID_EP_RANKS_PER_NVLINK_DOMAIN export "${ENV_ARGS[@]}" -TRAIN_ENV_JSON=$(python3 - "${ENV_ARGS[@]}" <<'PYENV' +TRAIN_ENV_JSON=$(python3 - "${RUNTIME_ENV_JSON:-}" "${ENV_ARGS[@]}" <<'PYENV' import json import sys -print(json.dumps(dict(item.split("=", 1) for item in sys.argv[1:]))) +env = dict(item.split("=", 1) for item in sys.argv[2:]) +base = json.loads(sys.argv[1] or "{}").get("env_vars", {}) +env["LD_LIBRARY_PATH"] = base.get("LD_LIBRARY_PATH", env["LD_LIBRARY_PATH"]) +print(json.dumps(env)) PYENV ) BASE_RUNTIME_ENV_JSON="${RUNTIME_ENV_JSON:-}" @@ -126,8 +127,7 @@ RUNTIME_ENV_JSON=$(python3 - "${BASE_RUNTIME_ENV_JSON}" "${TRAIN_ENV_JSON}" <<'P import json import sys runtime = json.loads(sys.argv[1]) -runtime.setdefault("env_vars", {}).pop("NUM_OF_HYBRID_EP_RANKS_PER_NVLINK_DOMAIN", None) -runtime["env_vars"].update(json.loads(sys.argv[2])) +runtime.setdefault("env_vars", {}).update(json.loads(sys.argv[2])) print(json.dumps(runtime)) PYRUNTIME ) @@ -162,6 +162,8 @@ CKPT_ARGS=( --megatron-to-hf-mode bridge --num-rollout "${NUM_STEPS:-50}" --load "${SAVE_DIR}/${EXP_NAME}" + --save "${SAVE_DIR}/${EXP_NAME}" + --save-interval "${SAVE_INTERVAL:-50}" --max-actor-ckpt-to-keep 2 ) @@ -230,7 +232,6 @@ MISC_ARGS=( --attention-backend flash --accumulate-allreduce-grads-in-fp32 --train-env-vars "${TRAIN_ENV_JSON}" - # Keep identical logical packing for both comparison arms. --overlap-grad-reduce --overlap-param-gather ) @@ -272,7 +273,9 @@ fi cd "${RELAX}" mkdir -p "${SAVE_DIR}/logs" -ray job submit ${RAY_NO_WAIT:+--no-wait} \ +RAY_SUBMIT_ARGS=(--address="${RAY_JOBS_ADDRESS}") +if [[ "${RAY_NO_WAIT:-0}" == 1 ]]; then RAY_SUBMIT_ARGS+=(--no-wait); fi +ray job submit "${RAY_SUBMIT_ARGS[@]}" \ --submission-id "${SUBMISSION_ID}" \ ${WORKING_DIR:+--working-dir "${WORKING_DIR}"} \ --runtime-env-json="${RUNTIME_ENV_JSON}" \ diff --git a/tests/cpu/backends/megatron/test_qwen38_fp8_hf_import.py b/tests/cpu/backends/megatron/test_qwen38_fp8_hf_import.py index b0786ff3d4..615f899f5a 100644 --- a/tests/cpu/backends/megatron/test_qwen38_fp8_hf_import.py +++ b/tests/cpu/backends/megatron/test_qwen38_fp8_hf_import.py @@ -475,7 +475,7 @@ def test_mok_primary_weights_support_layer_wise_muon(precision): ) model = torch.nn.Linear(32, 32, dtype=torch.bfloat16) weight = model.weight - assert precision.configure_fp8(model, args) == {} + precision.configure_fp8(model, args) assert model.weight is weight args.use_layer_wise_distributed_optimizer = False with pytest.raises(ValueError, match="use-distributed-optimizer"): From c2b405fb34d8611b965a5ecbbf5e800d026bd534 Mon Sep 17 00:00:00 2001 From: Lemon-412 Date: Fri, 27 Nov 2026 15:02:41 +0800 Subject: [PATCH 4/9] fix(qwen38): use the Jobs endpoint for Ray node discovery --- docker/patch/megatron/20260915-4a4de8657.patch | 2 +- .../qwen3.8-flash-next/scripts/run-qwen38-32k-mok-muon.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docker/patch/megatron/20260915-4a4de8657.patch b/docker/patch/megatron/20260915-4a4de8657.patch index 78dc523028..6de5bf816e 100644 --- a/docker/patch/megatron/20260915-4a4de8657.patch +++ b/docker/patch/megatron/20260915-4a4de8657.patch @@ -10660,7 +10660,7 @@ diff --git a/megatron/core/ssm/gated_delta_net/gdn.py b/megatron/core/ssm/gated_ + and self.config.linear_cp_mode == "headwise" + and not self.gdn_pre_gated_delta_rule_fusion + and not self.config.deterministic_mode -+ and not getattr(self.config, "_relax_qwen35_optimized", False) ++ and not self.config._relax_qwen35_optimized + ) if self.config.deterministic_mode: self.gated_delta_rule = torch_chunk_gated_delta_rule diff --git a/examples/models/qwen3.8-flash-next/scripts/run-qwen38-32k-mok-muon.sh b/examples/models/qwen3.8-flash-next/scripts/run-qwen38-32k-mok-muon.sh index fc7a0ad591..28177f32d4 100755 --- a/examples/models/qwen3.8-flash-next/scripts/run-qwen38-32k-mok-muon.sh +++ b/examples/models/qwen3.8-flash-next/scripts/run-qwen38-32k-mok-muon.sh @@ -22,7 +22,7 @@ now=$(date "+%Y%m%d-%H%M%S") export SUBMISSION_ID="${SUBMISSION_ID:-${EXP_NAME}-${now}-$$}" if [[ "${DRY_RUN:-0}" != 1 ]]; then - : "${RAY_JOBS_ADDRESS:?Set RAY_JOBS_ADDRESS to the Ray Jobs endpoint}" + export RAY_API_SERVER_ADDRESS="${RAY_JOBS_ADDRESS:?Set RAY_JOBS_ADDRESS to the Ray Jobs endpoint}" fi # Use an exclusive Ray cluster; the operator must prevent concurrent training. From 436215606ba1c7227a606b79db343476c978d9ad Mon Sep 17 00:00:00 2001 From: Lemon-412 Date: Fri, 27 Nov 2026 16:26:15 +0800 Subject: [PATCH 5/9] fix(ray): verify the cleanup cluster before touching workers --- scripts/entrypoint/ray-job.sh | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/scripts/entrypoint/ray-job.sh b/scripts/entrypoint/ray-job.sh index 5bbcb836d3..94414b38e1 100755 --- a/scripts/entrypoint/ray-job.sh +++ b/scripts/entrypoint/ray-job.sh @@ -69,6 +69,28 @@ source "${DIR}/kernel-cache.sh" # script is structurally incapable of hitting a ray daemon, so it is safe to run clusterwide. # Fresh/dedicated clusters can preserve all existing jobs and placements. if [[ "${RELAX_SKIP_CLUSTER_CLEANUP:-0}" != 1 ]]; then +if [[ -n "${RAY_JOBS_ADDRESS:-}" ]]; then + export RAY_API_SERVER_ADDRESS="$RAY_JOBS_ADDRESS" + export RAY_DASHBOARD_ADDRESS="$RAY_JOBS_ADDRESS" + # The cleanup helpers connect via Ray Core; Jobs and Serve use the dashboard. + if ! timeout 30 python - <<'PYRAY' +import os + +import ray +from ray.util.state import get_node + +if os.environ.get("RAY_ADDRESS") == "local": + raise SystemExit("RAY_ADDRESS=local creates a new cluster") +ray.init(address="auto", log_to_driver=False) +node = get_node(ray.get_runtime_context().get_node_id(), timeout=10) +if node is None or node.state != "ALIVE": + raise SystemExit("The Jobs endpoint does not report the connected Ray Core node as alive") +PYRAY + then + echo "Cleanup aborted: could not verify that Ray Core and RAY_JOBS_ADDRESS target the same cluster." >&2 + exit 1 + fi +fi echo "=== Cleaning up residual Relax/SGLang worker processes ===" python ${DIR}/../tools/run_on_each_ray_node.py ${DIR}/../tools/kill_for_ray.sh || echo "failed" From e1ea8b4cf5d27a73933041eca9081f8e67faa3ef Mon Sep 17 00:00:00 2001 From: Lemon-412 Date: Fri, 27 Nov 2026 18:18:30 +0800 Subject: [PATCH 6/9] fix(ray): share the resolved dashboard URL across cleanup clients --- scripts/entrypoint/ray-job.sh | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/scripts/entrypoint/ray-job.sh b/scripts/entrypoint/ray-job.sh index 94414b38e1..3d4bcf1309 100755 --- a/scripts/entrypoint/ray-job.sh +++ b/scripts/entrypoint/ray-job.sh @@ -70,26 +70,36 @@ source "${DIR}/kernel-cache.sh" # Fresh/dedicated clusters can preserve all existing jobs and placements. if [[ "${RELAX_SKIP_CLUSTER_CLEANUP:-0}" != 1 ]]; then if [[ -n "${RAY_JOBS_ADDRESS:-}" ]]; then - export RAY_API_SERVER_ADDRESS="$RAY_JOBS_ADDRESS" - export RAY_DASHBOARD_ADDRESS="$RAY_JOBS_ADDRESS" + export RAY_API_SERVER_ADDRESS="${RAY_API_SERVER_ADDRESS:-$RAY_JOBS_ADDRESS}" # The cleanup helpers connect via Ray Core; Jobs and Serve use the dashboard. - if ! timeout 30 python - <<'PYRAY' + if ! _cleanup_dashboard=$(timeout 30 python - <<'PYRAY' import os +from urllib.parse import urlsplit import ray +from ray.dashboard.utils import get_address_for_submission_client from ray.util.state import get_node if os.environ.get("RAY_ADDRESS") == "local": raise SystemExit("RAY_ADDRESS=local creates a new cluster") +dashboard = get_address_for_submission_client(None) +url = urlsplit(dashboard) +if url.scheme not in ("http", "https") or not url.hostname: + raise SystemExit("Ray Serve cleanup requires an HTTP(S) dashboard URL") +os.environ["RAY_API_SERVER_ADDRESS"] = dashboard ray.init(address="auto", log_to_driver=False) node = get_node(ray.get_runtime_context().get_node_id(), timeout=10) if node is None or node.state != "ALIVE": raise SystemExit("The Jobs endpoint does not report the connected Ray Core node as alive") +print(dashboard) PYRAY - then + ); then echo "Cleanup aborted: could not verify that Ray Core and RAY_JOBS_ADDRESS target the same cluster." >&2 exit 1 fi + export RAY_API_SERVER_ADDRESS="$_cleanup_dashboard" + export RAY_JOBS_ADDRESS="$_cleanup_dashboard" + export RAY_DASHBOARD_ADDRESS="$_cleanup_dashboard" fi echo "=== Cleaning up residual Relax/SGLang worker processes ===" python ${DIR}/../tools/run_on_each_ray_node.py ${DIR}/../tools/kill_for_ray.sh || echo "failed" From 21b76d7a6b94ff0b2d64d57b0c02614370309e9c Mon Sep 17 00:00:00 2001 From: Lemon-412 Date: Fri, 27 Nov 2026 21:24:12 +0800 Subject: [PATCH 7/9] fix(qwen38): validate recipe environment and bound CP1 DoSA fallback --- .../scripts/run-qwen38-32k-mok-muon.sh | 6 ++--- relax/models/qwen3_8/ops/qsa_cute/selector.py | 22 ++++++++++++++---- .../qwen3_8/ops/qsa_mixed_ops/selector.py | 7 +++++- relax/utils/env.py | 5 ++++ tests/backends/megatron/test_qsa_mixed.py | 23 +++++++++++++++++++ tests/cpu/examples/test_qwen38_mok_sft.py | 17 ++++++++++++-- 6 files changed, 69 insertions(+), 11 deletions(-) diff --git a/examples/models/qwen3.8-flash-next/scripts/run-qwen38-32k-mok-muon.sh b/examples/models/qwen3.8-flash-next/scripts/run-qwen38-32k-mok-muon.sh index 28177f32d4..e01815fa15 100755 --- a/examples/models/qwen3.8-flash-next/scripts/run-qwen38-32k-mok-muon.sh +++ b/examples/models/qwen3.8-flash-next/scripts/run-qwen38-32k-mok-muon.sh @@ -3,6 +3,7 @@ # Full-length 32K text SFT on 4 x 8 Blackwell GPUs, TP1/PP1/CP1/EP8. # Export MODEL_DIR, DATA_DIR, SAVE_DIR, MEGATRON and RAY_JOBS_ADDRESS. # Use the Blackwell Megatron runtime with grouped FlashQLA support. +# The DoSA boundary fast path is validated on SM103. Unsupported inputs use exact radix selection. set -eo pipefail SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" @@ -42,7 +43,7 @@ ENV_ARGS=( "QWEN38_PLE_INPUT_HALO_CP=1" "QWEN38_PLE_INPUT_HALO_TRANSPORT=${QWEN38_PLE_INPUT_HALO_TRANSPORT:-adaptive}" "LD_LIBRARY_PATH=${LD_LIBRARY_PATH:-}" - RELAX_PROPAGATE_ENV_VARS=QWEN38_WORKSPACE,SAVE_DIR,RELAX_PROFILE_DIR,TENSORBOARD_DIR,CLEARML_CACHE_DIR,CLEARML_OFFLINE_MODE,PYTHONDONTWRITEBYTECODE,LD_LIBRARY_PATH,NVLINK_DOMAIN_SIZE,USE_MNNVL,CUDA_DEVICE_MAX_CONNECTIONS,QWEN38_RUN_DIR,RELAX_SKIP_NONFINITE_GRAD + RELAX_PROPAGATE_ENV_VARS=SAVE_DIR,TENSORBOARD_DIR,CLEARML_CACHE_DIR,CLEARML_OFFLINE_MODE,PYTHONDONTWRITEBYTECODE,LD_LIBRARY_PATH,NVLINK_DOMAIN_SIZE,USE_MNNVL,CUDA_DEVICE_MAX_CONNECTIONS,RELAX_SKIP_NONFINITE_GRAD NCCL_NVLS_ENABLE=0 "PYTHONPATH=${RELAX}:${MEGATRON}" "MEGATRON=${MEGATRON}" @@ -69,14 +70,12 @@ ENV_ARGS=( "RELAX_QWEN38_QSA_MIXED_LONG_BACKEND=${RELAX_QWEN38_QSA_MIXED_LONG_BACKEND:-cute}" "RELAX_QWEN38_QSA_MIXED_FLASH_MAX_LEN=${RELAX_QWEN38_QSA_MIXED_FLASH_MAX_LEN:--1}" "RELAX_QWEN38_QSA_NV_MAX_PACK_TOKENS=${RELAX_QWEN38_QSA_NV_MAX_PACK_TOKENS:-0}" - "QWEN38_WORKSPACE=${RELAX}" "SAVE_DIR=${SAVE_DIR}" RELAX_SFT_RESIDENT_PARAM_OVERLAP=0 RAY_OVERRIDE_JOB_RUNTIME_ENV=1 "TENSORBOARD_DIR=${SAVE_DIR}/tensorboard" "CLEARML_CACHE_DIR=${SAVE_DIR}/clearml" CLEARML_OFFLINE_MODE=0 - "RELAX_PROFILE_DIR=${SAVE_DIR}/traces" PYTHONDONTWRITEBYTECODE=1 RELAX_PROFILE_RANKS=0,8,16,24 RELAX_PROFILE_GZIP_LEVEL=1 @@ -97,7 +96,6 @@ ENV_ARGS=( RELAX_QWEN38_PLE_FUSED_CONV=1 RELAX_SFT_FUSED_LINEAR_CE=1 "RELAX_LOGPROB_CE_IMPL=native" - "QWEN38_RUN_DIR=${SAVE_DIR}" RELAX_QWEN38_QSA_MIXED_FLEX_MAX_LEN=0 RELAX_QWEN38_QSA_GROUPED_BACKWARD_STAGES=3 RELAX_SFT_MTP_ACCEPTANCE_METRICS=0 diff --git a/relax/models/qwen3_8/ops/qsa_cute/selector.py b/relax/models/qwen3_8/ops/qsa_cute/selector.py index 332f7aa140..13060de033 100644 --- a/relax/models/qwen3_8/ops/qsa_cute/selector.py +++ b/relax/models/qwen3_8/ops/qsa_cute/selector.py @@ -19,12 +19,20 @@ def _interval_config(): return IntervalConfig(**json.loads(os.environ.get("QWEN38_DOSA_INTERVAL_CONFIG", "{}"))) -def select_ids(query: Tensor, keys: Tensor, positions: Tensor, budget: int, impl: str = "auto") -> Tensor: +def select_ids( + query: Tensor, + keys: Tensor, + positions: Tensor, + budget: int, + impl: str = "auto", + *, + chunk_dosa_fallback: bool = False, +) -> Tensor: """Select complete causal blocks. Radix, DoSA and CPU ties use ascending block ID; torch keeps its original GEMM and topk tie behavior. ``dosa-set`` preserves radix membership and may reorder the valid IDs. It - is only used by the CuTe CP set consumer. + is used by the CuTe set consumer. CP1 bounds the radix workspace if DoSA declines the input. The CPU implementation is also useful for small numerical oracles. It uses the same FP32 scoring contract; it is not a fallback for unsupported GPUs. @@ -41,6 +49,7 @@ def select_ids(query: Tensor, keys: Tensor, positions: Tensor, budget: int, impl return torch.full((rows, budget), -1, dtype=torch.int32, device=query.device) count = min(budget, blocks) visible = ((positions + 1) // 4).clamp(min=0, max=blocks) + radix_rows = rows if query.is_cuda and impl in ("dosa", "dosa-set"): boundary_only = impl == "dosa-set" variant = os.environ.get("QWEN38_DOSA_VARIANT") @@ -58,6 +67,8 @@ def select_ids(query: Tensor, keys: Tensor, positions: Tensor, budget: int, impl if selected is not None: return selected impl = "triton" if boundary_only else "auto" + if chunk_dosa_fallback: + radix_rows = 512 output = torch.full((rows, budget), -1, dtype=torch.int32, device=query.device) if query.is_cuda and impl == "torch": from relax.models.qwen3_8.ops.qsa_mixed_ops.selector import index_scores @@ -73,9 +84,12 @@ def select_ids(query: Tensor, keys: Tensor, positions: Tensor, budget: int, impl elif query.is_cuda: from relax.models.qwen3_8.ops.qsa_cute.triton_qsa_select import ID_BITS, qsa_select_topk_keys - encoded = qsa_select_topk_keys(query.contiguous(), keys.contiguous(), visible, count, impl=impl) + keys = keys.contiguous() mask = (1 << ID_BITS) - 1 - output[:, :count] = torch.where(encoded > 0, mask - (encoded & mask), -1).int() + for start in range(0, rows, radix_rows): + chunk = slice(start, start + radix_rows) + encoded = qsa_select_topk_keys(query[chunk].contiguous(), keys, visible[chunk], count, impl=impl) + output[chunk, :count] = torch.where(encoded > 0, mask - (encoded & mask), -1).int() else: scores = torch.zeros(rows, blocks, dtype=torch.float32, device=query.device) for head in range(heads): diff --git a/relax/models/qwen3_8/ops/qsa_mixed_ops/selector.py b/relax/models/qwen3_8/ops/qsa_mixed_ops/selector.py index a3db141011..8972eaec77 100644 --- a/relax/models/qwen3_8/ops/qsa_mixed_ops/selector.py +++ b/relax/models/qwen3_8/ops/qsa_mixed_ops/selector.py @@ -196,7 +196,12 @@ def forward( and os.environ.get("RELAX_QWEN38_QSA_MIXED_LONG_BACKEND") == "cute" ) selected[first - first_query : last - first_query] = select_ids( - q[first:last], pooled, positions[first:last], topk, impl="dosa-set" if boundary else "dosa" + q[first:last], + pooled, + positions[first:last], + topk, + impl="dosa-set" if boundary else "dosa", + chunk_dosa_fallback=True, ) continue for a in range(first - start, last - start, 512): diff --git a/relax/utils/env.py b/relax/utils/env.py index c828d2efae..45bb4baa18 100644 --- a/relax/utils/env.py +++ b/relax/utils/env.py @@ -228,6 +228,7 @@ class Envs(metaclass=_EnvsMeta): # Qwen model compatibility and optional training kernels. RELAX_LOGPROB_FAST_PATH = EnvProperty("RELAX_LOGPROB_FAST_PATH", bool, False) RELAX_SFT_RESIDENT_PARAM_OVERLAP = EnvProperty("RELAX_SFT_RESIDENT_PARAM_OVERLAP", bool, False) + RELAX_AUTOTUNE_LOG_DIR = EnvProperty("RELAX_AUTOTUNE_LOG_DIR", str, None) RELAX_PROFILE_RANKS = EnvProperty("RELAX_PROFILE_RANKS", str, None) RELAX_PROFILE_GZIP_LEVEL = EnvProperty("RELAX_PROFILE_GZIP_LEVEL", int, None) RELAX_QWEN38_HC_FUSED_MIX = EnvProperty("RELAX_QWEN38_HC_FUSED_MIX", bool, True) @@ -235,6 +236,8 @@ class Envs(metaclass=_EnvsMeta): RELAX_QWEN38_PLE_COMPACT_GRAD = EnvProperty("RELAX_QWEN38_PLE_COMPACT_GRAD", bool, False) RELAX_QWEN38_PLE_FUSED_CONV = EnvProperty("RELAX_QWEN38_PLE_FUSED_CONV", bool, False) RELAX_QWEN38_PLE_CP_FUSED_CONV = EnvProperty("RELAX_QWEN38_PLE_CP_FUSED_CONV", bool, False) + RELAX_CP4_FLASH_QLA = EnvProperty("RELAX_CP4_FLASH_QLA", bool, False) + RELAX_QWEN38_RECORD_FUNCTION_TAGS = EnvProperty("RELAX_QWEN38_RECORD_FUNCTION_TAGS", bool, False) RELAX_QWEN38_QSA_CP_TP_SELECTOR = EnvProperty("RELAX_QWEN38_QSA_CP_TP_SELECTOR", bool, False) RELAX_SFT_FUSED_LINEAR_CE = EnvProperty("RELAX_SFT_FUSED_LINEAR_CE", bool, False) # Independent opt-ins for K3 training operator benchmarks and deployment. @@ -259,10 +262,12 @@ class Envs(metaclass=_EnvsMeta): RELAX_QWEN38_PLE_STREAMED = EnvProperty("RELAX_QWEN38_PLE_STREAMED", bool, False) RELAX_QWEN38_QSA_FUSED_ATTENTION = _QSAFusedAttentionProperty("RELAX_QWEN38_QSA_FUSED_ATTENTION", bool, False) RELAX_QWEN38_QSA_COMMUNITY_BACKEND = EnvProperty("RELAX_QWEN38_QSA_COMMUNITY_BACKEND", str, "") + RELAX_QWEN38_QSA_FLEX_SPARSE_MASK = EnvProperty("RELAX_QWEN38_QSA_FLEX_SPARSE_MASK", bool, True) RELAX_QWEN38_QSA_MIXED_FLEX_MAX_LEN = EnvProperty("RELAX_QWEN38_QSA_MIXED_FLEX_MAX_LEN", int, 16384) RELAX_QWEN38_QSA_MIXED_LONG_BACKEND = EnvProperty("RELAX_QWEN38_QSA_MIXED_LONG_BACKEND", str, "grouped") RELAX_QWEN38_QSA_MIXED_FLASH_MAX_LEN = EnvProperty("RELAX_QWEN38_QSA_MIXED_FLASH_MAX_LEN", int, -1) RELAX_QWEN38_QSA_NV_MAX_PACK_TOKENS = EnvProperty("RELAX_QWEN38_QSA_NV_MAX_PACK_TOKENS", int, 0) + RELAX_QWEN38_QSA_GROUPED_BACKWARD_WARPS = EnvProperty("RELAX_QWEN38_QSA_GROUPED_BACKWARD_WARPS", int, 4) RELAX_QWEN38_QSA_GROUPED_BACKWARD_STAGES = EnvProperty("RELAX_QWEN38_QSA_GROUPED_BACKWARD_STAGES", int, 1) RELAX_QWEN38_QSA_GROUPED_BACKWARD_BLOCK_K = EnvProperty("RELAX_QWEN38_QSA_GROUPED_BACKWARD_BLOCK_K", int, 64) RELAX_QWEN38_QSA_SELECTOR_COMPILE = EnvProperty("RELAX_QWEN38_QSA_SELECTOR_COMPILE", bool, False) diff --git a/tests/backends/megatron/test_qsa_mixed.py b/tests/backends/megatron/test_qsa_mixed.py index 63f6c0aea2..30d99bd28f 100644 --- a/tests/backends/megatron/test_qsa_mixed.py +++ b/tests/backends/megatron/test_qsa_mixed.py @@ -248,3 +248,26 @@ def check_qsa_mixed_parallel_geometry(geometry, lengths): @pytest.mark.parametrize("lengths", [(2052,), (16385,)]) def check_qsa_mixed_production_sparse_budget(geometry, lengths): _run_case(lengths, 512, geometry) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CP1 radix fallback requires CUDA") +def test_cp1_dosa_fallback_bounds_radix_queries(monkeypatch): + from relax.models.qwen3_8.ops.qsa_cute import triton_qsa_select + from relax.models.qwen3_8.ops.qsa_cute.selector import select_ids + + # 128 blocks fall below DoSA's interval-selector threshold on every device. + query = torch.zeros(1025, 4, 128, dtype=torch.bfloat16, device="cuda") + keys = torch.zeros(128, 128, dtype=query.dtype, device=query.device) + positions = torch.arange(len(query), dtype=torch.int32, device=query.device) + expected = select_ids(query, keys, positions, 32, impl="triton") + radix = triton_qsa_select.qsa_select_topk_keys + chunks = [] + + def record(q, *args, **kwargs): + chunks.append(len(q)) + return radix(q, *args, **kwargs) + + monkeypatch.setattr(triton_qsa_select, "qsa_select_topk_keys", record) + actual = select_ids(query, keys, positions, 32, impl="dosa-set", chunk_dosa_fallback=True) + torch.testing.assert_close(actual, expected, atol=0, rtol=0) + assert chunks == [512, 512, 1] diff --git a/tests/cpu/examples/test_qwen38_mok_sft.py b/tests/cpu/examples/test_qwen38_mok_sft.py index 88b9a7a39a..9a90e25805 100644 --- a/tests/cpu/examples/test_qwen38_mok_sft.py +++ b/tests/cpu/examples/test_qwen38_mok_sft.py @@ -15,7 +15,7 @@ LAUNCHER = ROOT / "examples/models/qwen3.8-flash-next/scripts/run-qwen38-qsa-sft-openr1mm-32xgpu-blackwell.sh" -def _dry_run(checkpoint: Path, **extra: str) -> dict: +def _dry_run(checkpoint: Path, launcher: Path = LAUNCHER, **extra: str) -> dict: env = {key: os.environ[key] for key in ("PATH", "HOME", "LANG", "TMPDIR") if key in os.environ} env.update( DRY_RUN="1", @@ -26,7 +26,7 @@ def _dry_run(checkpoint: Path, **extra: str) -> dict: MEGATRON="/image/megatron", ) env.update(extra) - result = subprocess.run(["bash", str(LAUNCHER)], env=env, capture_output=True, text=True, timeout=10) + result = subprocess.run(["bash", str(launcher)], env=env, capture_output=True, text=True, timeout=10) assert result.returncode == 0, result.stderr return json.loads(result.stdout) @@ -35,6 +35,19 @@ def _value(argv: list[str], flag: str) -> str: return argv[len(argv) - 1 - argv[::-1].index(flag) + 1] +def test_32k_muon_recipe_env_passes_strict_validation(tmp_path, monkeypatch): + from relax.utils.env import validate_env + + launcher = LAUNCHER.with_name("run-qwen38-32k-mok-muon.sh") + config = _dry_run(tmp_path / "checkpoints", launcher=launcher) + for name in list(os.environ): + if name.startswith("RELAX_"): + monkeypatch.delenv(name) + monkeypatch.setenv("RELAX_STRICT_ENV", "1") + validate_env(config["runtime_env"]["env_vars"]) + validate_env(json.loads(_value(config["argv"], "--train-env-vars"))) + + @pytest.mark.parametrize("backend", ["hybridep", "mok"]) def test_backend_selection_and_worker_dependencies(tmp_path: Path, backend: str) -> None: config = _dry_run( From 20acec33e755257c1a605a93e9000d1bda6558be Mon Sep 17 00:00:00 2001 From: Lemon-412 Date: Fri, 27 Nov 2026 21:43:50 +0800 Subject: [PATCH 8/9] fix(qwen38): align boolean kernel flags with environment validation --- docker/patch/megatron/20260915-4a4de8657.patch | 2 +- relax/models/qwen3_8/ops/qsa_cute/profiling.py | 5 +++-- relax/models/qwen3_8/ops/qsa_mixed_ops/flex.py | 6 +++--- relax/models/qwen3_8/ops/qsa_mixed_ops/grouped.py | 4 +++- relax/utils/autotune_logging.py | 4 +++- relax/utils/record_function_tags.py | 5 +++-- .../backends/megatron/test_qsa_cute_contracts.py | 14 ++++++++++++++ 7 files changed, 30 insertions(+), 10 deletions(-) diff --git a/docker/patch/megatron/20260915-4a4de8657.patch b/docker/patch/megatron/20260915-4a4de8657.patch index 6de5bf816e..8e7964caa4 100644 --- a/docker/patch/megatron/20260915-4a4de8657.patch +++ b/docker/patch/megatron/20260915-4a4de8657.patch @@ -10656,7 +10656,7 @@ diff --git a/megatron/core/ssm/gated_delta_net/gdn.py b/megatron/core/ssm/gated_ self.a_log_dim = self.num_v_heads_local_tp + self.grouped_qk = ( -+ os.environ.get("RELAX_CP4_FLASH_QLA") == "1" ++ os.getenv("RELAX_CP4_FLASH_QLA", "").strip().lower() in {"1", "t", "true", "y", "yes", "on"} + and self.config.linear_cp_mode == "headwise" + and not self.gdn_pre_gated_delta_rule_fusion + and not self.config.deterministic_mode diff --git a/relax/models/qwen3_8/ops/qsa_cute/profiling.py b/relax/models/qwen3_8/ops/qsa_cute/profiling.py index 522ab84e78..19d1047ca1 100644 --- a/relax/models/qwen3_8/ops/qsa_cute/profiling.py +++ b/relax/models/qwen3_8/ops/qsa_cute/profiling.py @@ -3,12 +3,13 @@ """Optional CPU launch ranges; GPU durations come from profiler correlations.""" -import os from contextlib import AbstractContextManager, nullcontext +from relax.utils.env import Envs + def profile_range(name: str) -> AbstractContextManager: - if os.environ.get("RELAX_QWEN38_RECORD_FUNCTION_TAGS", "0") != "1": + if not Envs.RELAX_QWEN38_RECORD_FUNCTION_TAGS: return nullcontext() import torch diff --git a/relax/models/qwen3_8/ops/qsa_mixed_ops/flex.py b/relax/models/qwen3_8/ops/qsa_mixed_ops/flex.py index 089240d96b..9986100d83 100644 --- a/relax/models/qwen3_8/ops/qsa_mixed_ops/flex.py +++ b/relax/models/qwen3_8/ops/qsa_mixed_ops/flex.py @@ -6,13 +6,13 @@ """Flex sparse GQA with selected-block and causal-tail masks.""" -import os - import torch import triton import triton.language as tl from torch.nn.attention.flex_attention import create_block_mask, flex_attention +from relax.utils.env import Envs + _compiled_attention = torch.compile(flex_attention, dynamic=True) @@ -90,7 +90,7 @@ def mask(batch, head, qi, ki): & (((key_block < complete) & selected) | (key_block == complete)) ) - if os.environ.get("RELAX_QWEN38_QSA_FLEX_SPARSE_MASK", "1") == "1": + if Envs.RELAX_QWEN38_QSA_FLEX_SPARSE_MASK: from relax.models.qwen3_8.ops.qsa_mixed_ops.block_mask import create block_mask = create(bits, starts, mask) diff --git a/relax/models/qwen3_8/ops/qsa_mixed_ops/grouped.py b/relax/models/qwen3_8/ops/qsa_mixed_ops/grouped.py index 30e6db6a33..4e885ea8b0 100644 --- a/relax/models/qwen3_8/ops/qsa_mixed_ops/grouped.py +++ b/relax/models/qwen3_8/ops/qsa_mixed_ops/grouped.py @@ -12,6 +12,8 @@ import triton import triton.language as tl +from relax.utils.env import Envs + @triton.jit def _forward( @@ -150,7 +152,7 @@ def forward(ctx, q, k, v, indices, scale, bf16_products=False, block_k=32, gradi raise ValueError("Unsupported Grouped QSA backward block size") ctx.params = dict(params, BK=backward_block_k) if bf16_products else params ctx.launch = launch - backward_warps = int(os.environ.get("RELAX_QWEN38_QSA_GROUPED_BACKWARD_WARPS", "4")) + backward_warps = Envs.RELAX_QWEN38_QSA_GROUPED_BACKWARD_WARPS assert backward_warps in (4, 8, 16) backward_stages = int(os.environ.get("RELAX_QWEN38_QSA_GROUPED_BACKWARD_STAGES", "1")) if backward_stages not in (1, 2, 3): diff --git a/relax/utils/autotune_logging.py b/relax/utils/autotune_logging.py index 78e10f8377..f9c4f31b17 100644 --- a/relax/utils/autotune_logging.py +++ b/relax/utils/autotune_logging.py @@ -14,6 +14,8 @@ from pathlib import Path from typing import Any +from relax.utils.env import Envs + def install_autotune_logging(process_group: Any) -> None: """Record cache-miss benchmark calls on each training rank. @@ -22,7 +24,7 @@ def install_autotune_logging(process_group: Any) -> None: returned to the tuners are unchanged. JSONL intervals use wall-clock time; profiler ranges identify overlap with the local capture window directly. """ - output_dir = os.environ.get("RELAX_AUTOTUNE_LOG_DIR") + output_dir = Envs.RELAX_AUTOTUNE_LOG_DIR if not output_dir: return diff --git a/relax/utils/record_function_tags.py b/relax/utils/record_function_tags.py index d89359e202..b9bcaaaf6c 100644 --- a/relax/utils/record_function_tags.py +++ b/relax/utils/record_function_tags.py @@ -10,7 +10,6 @@ import inspect import json -import os import threading from collections import deque from contextlib import ExitStack @@ -20,6 +19,8 @@ import torch +from relax.utils.env import Envs + _phase: ContextVar[str] = ContextVar("rcd_phase", default="fwd") _checkpoint_layers: ContextVar[list[str] | None] = ContextVar("rcd_checkpoint_layers", default=None) @@ -349,7 +350,7 @@ def _instrument_chunks(chunks: Any, rank_suffix: str) -> list[dict[str, Any]]: def install_record_function_tags(args: Any, model_chunks: Any) -> list[dict[str, Any]]: """Install only on enabled, selected profiler ranks after model setup.""" - if os.environ.get("RELAX_QWEN38_RECORD_FUNCTION_TAGS", "0") != "1" or not args.use_pytorch_profiler: + if not Envs.RELAX_QWEN38_RECORD_FUNCTION_TAGS or not args.use_pytorch_profiler: return [] from relax.utils.logging_utils import get_logger from relax.utils.profile_utils import _should_profile_train_rank diff --git a/tests/cpu/backends/megatron/test_qsa_cute_contracts.py b/tests/cpu/backends/megatron/test_qsa_cute_contracts.py index ea6e5d2a95..174a603a85 100644 --- a/tests/cpu/backends/megatron/test_qsa_cute_contracts.py +++ b/tests/cpu/backends/megatron/test_qsa_cute_contracts.py @@ -326,3 +326,17 @@ class PackedFixture: assert result.cp_partition_mode == "zigzag" if bound_layout: assert valid_physical_layout(result) == valid_physical_layout(original) + + +@pytest.mark.parametrize("value,expected", [(None, False), (" TrUe ", True), ("off", False)]) +def test_qsa_profile_range_uses_registered_boolean(monkeypatch, value, expected): + from relax.models.qwen3_8.ops.qsa_cute.profiling import profile_range + + if value is None: + monkeypatch.delenv("RELAX_QWEN38_RECORD_FUNCTION_TAGS", raising=False) + else: + monkeypatch.setenv("RELAX_QWEN38_RECORD_FUNCTION_TAGS", value) + with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU]) as profile: + with profile_range("boolean-regression"): + torch.zeros(1) + assert ("QSA/boolean-regression" in {event.key for event in profile.key_averages()}) == expected From 8e5b76ec9582a6db17f45a2476b51b0412f17979 Mon Sep 17 00:00:00 2001 From: Lemon-412 Date: Fri, 27 Nov 2026 22:02:26 +0800 Subject: [PATCH 9/9] test(qwen38): cover bounded DoSA fallback through the CP1 selector --- tests/backends/megatron/test_qsa_mixed.py | 50 +++++++++++++++++++---- 1 file changed, 41 insertions(+), 9 deletions(-) diff --git a/tests/backends/megatron/test_qsa_mixed.py b/tests/backends/megatron/test_qsa_mixed.py index 30d99bd28f..12f48bb829 100644 --- a/tests/backends/megatron/test_qsa_mixed.py +++ b/tests/backends/megatron/test_qsa_mixed.py @@ -253,13 +253,40 @@ def check_qsa_mixed_production_sparse_budget(geometry, lengths): @pytest.mark.skipif(not torch.cuda.is_available(), reason="CP1 radix fallback requires CUDA") def test_cp1_dosa_fallback_bounds_radix_queries(monkeypatch): from relax.models.qwen3_8.ops.qsa_cute import triton_qsa_select - from relax.models.qwen3_8.ops.qsa_cute.selector import select_ids - - # 128 blocks fall below DoSA's interval-selector threshold on every device. - query = torch.zeros(1025, 4, 128, dtype=torch.bfloat16, device="cuda") - keys = torch.zeros(128, 128, dtype=query.dtype, device=query.device) - positions = torch.arange(len(query), dtype=torch.int32, device=query.device) - expected = select_ids(query, keys, positions, 32, impl="triton") + from relax.models.qwen3_8.ops.qsa_mixed_ops import selector + + monkeypatch.setenv("RELAX_QWEN38_QSA_SELECTOR_BACKEND", "dosa") + monkeypatch.setenv("QWEN38_DOSA_VARIANT", "boundary") + monkeypatch.setenv("RELAX_QWEN38_QSA_MIXED_LONG_BACKEND", "cute") + monkeypatch.setattr(selector.dist, "get_world_size", lambda group: 1) + monkeypatch.setattr(selector.dist, "get_rank", lambda group: 0) + + # One document with 256 complete blocks naturally takes the DoSA fallback. + rows, topk = 1025, 32 + hidden = torch.zeros(rows, 1, 640, dtype=torch.bfloat16, device="cuda") + freqs = torch.zeros(rows, 1, 1, 128, device=hidden.device) + norm = SimpleNamespace(weight=hidden.new_zeros(128)) + indexer = SimpleNamespace( + config=SimpleNamespace( + context_parallel_size=1, + qsa_indexer_loss_coeff=0, + layernorm_zero_centered_gamma=True, + sequence_parallel=False, + rotary_interleaved=False, + layernorm_epsilon=1e-6, + ), + pg_collection=SimpleNamespace(tp=object(), cp=object()), + parameters=lambda: (), + n_heads=4, + kv_heads=1, + head_dim=128, + compress_ratio=4, + token_budget=topk * 4, + block_topk=topk, + index_qk_proj=lambda x: (x, None), + q_layernorm=norm, + k_layernorm=norm, + ) radix = triton_qsa_select.qsa_select_topk_keys chunks = [] @@ -268,6 +295,11 @@ def record(q, *args, **kwargs): return radix(q, *args, **kwargs) monkeypatch.setattr(triton_qsa_select, "qsa_select_topk_keys", record) - actual = select_ids(query, keys, positions, 32, impl="dosa-set", chunk_dosa_fallback=True) + actual = selector.forward(indexer, hidden, freqs, output_format="ids").selected_ids + assert sum(chunks) == rows + assert all(0 < chunk <= 512 for chunk in chunks) + # Every score ties. The expected IDs are the first complete causal blocks. + ids = torch.arange(topk, dtype=torch.int32, device=hidden.device) + visible = (torch.arange(rows, device=hidden.device) + 1) // 4 + expected = torch.where(ids < visible[:, None], ids, -1) torch.testing.assert_close(actual, expected, atol=0, rtol=0) - assert chunks == [512, 512, 1]