-
Notifications
You must be signed in to change notification settings - Fork 974
[FSDP] Add Masked importance sampling #1122
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
51954ed
support token/seq level MIS for FSDP
zijiexia 471420b
Add masked importance sampling for FSDP backend (#1063).
GuanxingLu 227b679
Merge branch 'zijie_dev_branch' into feature/fsdp-mis
zijiexia 8c8a782
Merge pull request #1 from GuanxingLu/feature/fsdp-mis
zijiexia d44e8d0
avoid getattr, remove mis test for FSDP
zijiexia 1105f26
remove further getattr
zijiexia 464e8ec
remove unnecessary funcs, cleanup actor.py
zijiexia 4e633d3
fix
zijiexia File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| from typing import Any | ||
|
|
||
| import torch | ||
|
|
||
| from .mis import compute_mis_weights | ||
|
|
||
|
|
||
| def compute_mis_weights_fsdp( | ||
| args, | ||
| *, | ||
| pg_loss: torch.Tensor, | ||
| train_log_probs: list[torch.Tensor], | ||
| rollout_log_probs: list[torch.Tensor], | ||
| loss_masks: list[torch.Tensor], | ||
| **kwargs: Any, | ||
| ) -> tuple[torch.Tensor, list[torch.Tensor], dict[str, torch.Tensor]]: | ||
| """Compute masked importance sampling weights for FSDP. No context parallelism. | ||
|
|
||
| Args: | ||
| args: Arguments containing MIS settings (use_tis, tis_mode, etc.) | ||
| pg_loss: Policy gradient loss, flattened tensor [total_tokens] | ||
| train_log_probs: Training log probs, list of 1D tensors per sequence | ||
| rollout_log_probs: Rollout log probs, list of 1D tensors per sequence | ||
| loss_masks: Loss masks, list of 1D tensors per sequence | ||
| **kwargs: Additional arguments (cp_rank, cp_size, etc.) for compatibility | ||
|
|
||
| Returns: | ||
| pg_loss: Policy gradient loss with IS weights applied | ||
| modified_masks: Modified loss masks after rejection sampling | ||
| mis_metrics: Metrics dict with flattened tensors | ||
| """ | ||
| is_weights, modified_masks, is_metrics = compute_mis_weights( | ||
| args=args, | ||
| train_log_probs=train_log_probs, | ||
| rollout_log_probs=rollout_log_probs, | ||
| loss_masks=loss_masks, | ||
| ) | ||
|
|
||
| result_metrics = {} | ||
| if is_weights is not None: | ||
| is_weights_flat = torch.cat(is_weights, dim=0) | ||
| pg_loss = pg_loss * is_weights_flat | ||
|
|
||
| for key, values in is_metrics.items(): | ||
| result_metrics[f"mis_{key}"] = torch.cat(values, dim=0) | ||
|
|
||
| return pg_loss, modified_masks, result_metrics |
148 changes: 148 additions & 0 deletions
148
examples/train_infer_mismatch_helper/run-qwen3-4b-fsdp-mis.sh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,148 @@ | ||
| #!/bin/bash | ||
|
|
||
| # for rerun the task | ||
| pkill -9 sglang | ||
| sleep 3 | ||
| ray stop --force | ||
| pkill -9 ray | ||
| pkill -9 python | ||
| sleep 3 | ||
| pkill -9 ray | ||
| pkill -9 python | ||
|
|
||
|
|
||
|
|
||
|
|
||
| set -ex | ||
|
|
||
| # will prevent ray from buffering stdout/stderr | ||
| export PYTHONBUFFERED=16 | ||
| export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 | ||
| NVLINK_COUNT=$(nvidia-smi | grep -o "NVLink" | wc -l) | ||
| if [ "$NVLINK_COUNT" -gt 0 ]; then | ||
| HAS_NVLINK=1 | ||
| else | ||
| HAS_NVLINK=0 | ||
| fi | ||
| echo "HAS_NVLINK: $HAS_NVLINK (detected $NVLINK_COUNT NVLink references)" | ||
|
|
||
|
|
||
|
|
||
| SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)" | ||
|
|
||
| RUN_ID=${RUN_ID:-"run_$(date +%Y%m%d_%H%M%S)"} | ||
| LOAD_SAVE_PATH="/root/shared_data/${RUN_ID}/checkpoints" | ||
|
|
||
| CKPT_ARGS=( | ||
| --hf-checkpoint /root/Qwen3-4B | ||
| --load /root/Qwen3-4B | ||
| --ref-load /root/Qwen3-4B | ||
| ) | ||
|
|
||
| ROLLOUT_ARGS=( | ||
| --prompt-data /root/dapo-math-17k/dapo-math-17k.jsonl | ||
| --input-key prompt | ||
| --label-key label | ||
| --apply-chat-template | ||
| --rollout-shuffle | ||
| --balance-data | ||
| --rm-type deepscaler | ||
| --num-rollout 100 | ||
| --rollout-batch-size 8 | ||
| --n-samples-per-prompt 8 | ||
| --rollout-max-response-len 4096 | ||
| --rollout-temperature 0.8 | ||
| --global-batch-size 64 | ||
| ) | ||
|
|
||
| GRPO_ARGS=( | ||
| --use-kl-loss | ||
| --advantage-estimator grpo | ||
| --kl-loss-coef 0.00 | ||
| --kl-loss-type low_var_kl | ||
| --kl-coef 0.00 | ||
| --entropy-coef 0.00 | ||
| --eps-clip 0.2 | ||
| --eps-clip-high 0.28 | ||
| --use-tis | ||
| ) | ||
|
|
||
| OPTIMIZER_ARGS=( | ||
| --optimizer adam | ||
| --lr 1e-6 | ||
| --lr-decay-style constant | ||
| --weight-decay 0.1 | ||
| --adam-beta1 0.9 | ||
| --adam-beta2 0.98 | ||
| ) | ||
|
|
||
| WANDB_ARGS=( | ||
| --use-wandb | ||
| --wandb-project slime-dev-mcore-fsdp | ||
| --wandb-group qwen3-4B-fsdp-1130-ref | ||
| --wandb-key ${WANDB_API_KEY} | ||
| ) | ||
|
|
||
| SGLANG_ARGS=( | ||
| --rollout-num-gpus-per-engine 1 | ||
| --sglang-mem-fraction-static 0.75 | ||
| --sglang-decode-log-interval 1000 | ||
| --sglang-chunked-prefill-size 4096 | ||
| --sglang-attention-backend fa3 | ||
| ) | ||
|
|
||
| TRAIN_BACKEND_ARGS=( | ||
| --train-backend fsdp | ||
| --update-weight-buffer-size 536870912 | ||
| --gradient-checkpointing | ||
| --attn-implementation flash_attention_3 | ||
| --train-env-vars '{"PYTORCH_CUDA_ALLOC_CONF":"expandable_segments:True"}' | ||
| ) | ||
|
|
||
| PERF_ARGS=( | ||
| --use-dynamic-batch-size | ||
| --max-tokens-per-gpu 9216 | ||
| ) | ||
|
|
||
| MISC_ARGS=( | ||
| --actor-num-nodes 1 | ||
| --actor-num-gpus-per-node 8 | ||
| --colocate | ||
| --use-fault-tolerance | ||
| --dump-details /root/shared_data/qwen3-4B-fsdp-1116-noref/dump_details | ||
| # --fsdp-cpu-offload | ||
| ) | ||
|
|
||
| CUSTOM_ARGS=( | ||
| --custom-config-path examples/train_infer_mismatch_helper/mis.yaml | ||
| --custom-tis-function-path examples.train_infer_mismatch_helper.mis_fsdp.compute_mis_weights_fsdp | ||
| ) | ||
|
|
||
| # launch the master node of ray in container - 8 GPUs for training | ||
| export MASTER_ADDR=${MASTER_ADDR:-"127.0.0.1"} | ||
| ray start --head --node-ip-address ${MASTER_ADDR} --num-gpus 8 --disable-usage-stats | ||
|
|
||
|
|
||
| RUNTIME_ENV_JSON="{ | ||
| \"env_vars\": { | ||
| \"PYTHONPATH\": \"/root/Megatron-LM/:${SCRIPT_DIR}\", | ||
| \"CUDA_DEVICE_MAX_CONNECTIONS\": \"1\" | ||
| } | ||
| }" | ||
|
|
||
|
|
||
| ray job submit --address="http://127.0.0.1:8265" \ | ||
| --runtime-env-json="${RUNTIME_ENV_JSON}" \ | ||
| -- python3 train.py \ | ||
| ${CKPT_ARGS[@]} \ | ||
| ${ROLLOUT_ARGS[@]} \ | ||
| ${OPTIMIZER_ARGS[@]} \ | ||
| ${GRPO_ARGS[@]} \ | ||
| ${WANDB_ARGS[@]} \ | ||
| ${SGLANG_ARGS[@]} \ | ||
| ${TRAIN_BACKEND_ARGS[@]} \ | ||
| ${PERF_ARGS[@]} \ | ||
| ${MISC_ARGS[@]} \ | ||
| ${CUSTOM_ARGS[@]} | ||
|
|
||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.