Files
Model-Optimizer/tests/examples/speculative_decoding/test_eagle.py
T
h-guo18 3036a9ea9f Feat: Context Parallel for Eagle3 Training (#745)
## What does this PR do?

**Type of change:** New Feature <!-- Use one of the following: Bug fix,
new feature, new example, new tests, documentation. -->

**Overview:** 

- Supported Context Parallel by patching torch ring attention;
- Require following libirary version for stable cp: 
  - torch2.8.0
  - transformers5.0.0
  - accelrate1.12.0 
 - Move to FSDP2 
- Removed unused arguments in training script (`--multi_gpu`,
`fsdp_wrap_layer`)
 - Bump CI container to `nvcr.io/nvidia/pytorch:25.08-py3`

## Usage
<!-- You can potentially add a usage example below. -->

```bash
./launch_train.sh --model $MODEL \
            --output_dir $OUTPUT_DIR \  
            --data $DATA \
            --num_epochs 0.1 \
            --train_bs 1 \
            --eagle_config eagle_config.json \
            --training_seq_len 1024 \
            --cp_size 2   #newly added
```

## Testing
- SDPA level correctness: tested TTT attention with/without CP, diff <
1%
```
=== Compare context-parallel (CP) outputs and grads with non-CP ===
Forward output comparison (CP vs Non-CP):
  Absolute diff (adiff) cp_out vs out: 0.001953125
  Relative diff (rdiff) cp_out vs out: 0.00182342529296875
WQ (query proj) grad comparison (CP vs Non-CP):
  Absolute diff (adiff) cp_wq_grad vs wq_grad: 0.0078125
  Relative diff (rdiff) cp_wq_grad vs wq_grad: 0.00347900390625
WK (key proj) grad comparison (CP vs Non-CP):
  Absolute diff (adiff) cp_wk_grad vs wk_grad: 0.0078125
  Relative diff (rdiff) cp_wk_grad vs wk_grad: 0.002471923828125
WV (value proj) grad comparison (CP vs Non-CP):
  Absolute diff (adiff) cp_wv_grad vs wv_grad: 0.25
  Relative diff (rdiff) cp_wv_grad vs wv_grad: 0.0069580078125
==============================================================
```

- E2E Training Acc
  (Llama3.1-8B, Unsynthesized magpie)
<img width="911" height="630" alt="image"
src="https://github.com/user-attachments/assets/1ecacc7f-c720-494c-9c1b-b60e7ced7baa"
/>

- Peak Mem Reserved
   (llama3.1-8B, 8xH100, train_length=4k)

    | cp_size | max_memory_allocated(MB) |max_memory_reserved (MB) |
    |----|--------------------------|--------------------------|
    | 1  |         65040.20              |79018.00
    | 2  |           50409.17             |73098.00
    | 4  |              45120.92            |72052.00
    | 8  |              38882.12            |66484.00

- Max Training Length test
  (llama3.1-8B, H100)

  | cp_size               | 6k  | 12k | 24k  | 48k  |
  |--------------------|-----|-----|-----|-----|
  | 1         | ✅ | OOM | OOM | OOM  |
  |2      | ✅  | ✅ | OOM | OOM |
  | 4         | ✅ | ✅ | ✅  | OOM  |
  | 8         | ✅ | ✅ | ✅  | ✅  |

## Before your PR is "*Ready for review*"
<!-- If you haven't finished some of the above items you can still open
`Draft` PR. -->

- **Make sure you read and follow [Contributor
guidelines](https://github.com/NVIDIA/Model-Optimizer/blob/main/CONTRIBUTING.md)**
and your commits are signed.
- **Is this change backward compatible?**: Yes/No <!--- If No, explain
why. -->
- **Did you write any new necessary tests?**: Yes/No
- **Did you add or update any necessary documentation?**: Yes/No
- **Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?**:
Yes/No <!--- Only for new features, API changes, critical bug fixes or
bw breaking changes. -->

## Additional Information
<!-- E.g. related issue. -->


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **New Features**
* Added context parallelism (CP) and data parallelism shard size
configuration parameters to training arguments.

* **Enhancements**
* Improved TTT attention masking support for speculative decoding
workflows.
* Enhanced training launch script with improved parallelism
configuration handling.

* **Chores**
* Updated core dependencies: torch, transformers, accelerate, and wandb.
  * Added FSDP configuration file for distributed training setup.

<sub>✏️ Tip: You can customize this high-level summary in your review
settings.</sub>

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: h-guo18 <67671475+h-guo18@users.noreply.github.com>
2026-01-24 02:45:50 +00:00

132 lines
4.9 KiB
Python

# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import pytest
import safetensors.torch
import torch
from _test_utils.examples.run_command import run_example_command
from packaging.version import Version
from modelopt.torch.export.plugins.hf_spec_export import LLAMA_EAGLE_SINGLE_LAYER
@pytest.fixture(scope="module")
def eagle_output_dir(tmp_path_factory):
"""Eagle output directory shared in this module."""
return tmp_path_factory.mktemp("eagle_output_dir")
# fmt: off
@pytest.mark.parametrize("cp_size", [1, 2])
def test_llama_eagle3(tiny_llama_path, tiny_daring_anteater_path, tmp_path, eagle_output_dir, cp_size):
"""Test Eagle3 training with a tiny llama model, using different cp_size values."""
available_gpus = torch.cuda.device_count() if torch.cuda.is_available() else 0
if cp_size == 2 and available_gpus < 2:
pytest.skip("cp_size=2 requires at least 2 GPUs, but only {} found.".format(available_gpus))
if cp_size == 2 and not (
Version(torch.__version__) > Version("2.7.0")
and Version(torch.__version__) < Version("2.9.0")
):
pytest.skip("cp_size=2 requires torch 2.8.0")
# Create an ultra-tiny EAGLE config for testing to reduce memory usage
tiny_eagle_config = {
"max_position_embeddings": 128,
"num_hidden_layers": 1,
"intermediate_size": 64,
"num_attention_heads": 2,
"num_key_value_heads": 2,
"head_dim": 64,
}
# Write the tiny config to a temporary file
config_file = tmp_path / f"tiny_eagle_config_cp{cp_size}.json"
with open(config_file, "w") as f:
json.dump(tiny_eagle_config, f)
run_example_command(
[
"./launch_train.sh",
"--model", tiny_llama_path,
"--data", tiny_daring_anteater_path,
"--num_epochs", "1",
"--lr", "1e-5",
"--mode", "eagle3",
"--eagle_config", str(config_file),
"--output_dir", eagle_output_dir / f"eagle-tinyllama-cp{cp_size}",
"--training_seq_len", "128", # Match max_position_embeddings
"--cp_size", str(cp_size),
],
"speculative_decoding",
)
def test_ar_validate(eagle_output_dir):
"""Test in-framework AR evaluation."""
run_example_command(
[
"python", "./scripts/ar_validate.py",
"--model_path", eagle_output_dir / "eagle-tinyllama-cp1",
"--osl", "20",
"--num_samples", "10",
"--steps", "3"
],
"speculative_decoding",
)
def test_export_hf_checkpoint(eagle_output_dir):
"""Test export of Eagle3 checkpoint."""
run_example_command(
[
"python", "./scripts/export_hf_checkpoint.py",
"--model_path", eagle_output_dir / "eagle-tinyllama-cp1",
"--export_path", eagle_output_dir / "eagle-tinyllama-export",
],
"speculative_decoding",
)
# Check the exported checkpoints have required keys
state_dict = safetensors.torch.load_file(eagle_output_dir / "eagle-tinyllama-export" / "model.safetensors")
for required_key in LLAMA_EAGLE_SINGLE_LAYER["required"]:
assert required_key in state_dict, f"Missing key '{required_key}' in state_dict"
def test_convert_to_vllm_ckpt(tiny_llama_path, eagle_output_dir):
"""Test conversion of Eagle3 checkpoint to VLLM one-model checkpoint."""
run_example_command(
[
"python", "./scripts/convert_to_vllm_ckpt.py",
"--input", eagle_output_dir / "eagle-tinyllama-export",
"--verifier", tiny_llama_path,
"--output", eagle_output_dir / "eagle-tinyllama-export-vllm-one-ckpt",
],
"speculative_decoding",
)
@pytest.mark.skip(reason="Needs dataset conversion to role-content format; consolidate data loading first.")
def test_calibrate_draft_vocab(tiny_llama_path, tiny_daring_anteater_path,tmp_path):
"""Test calibration of draft vocabulary."""
run_example_command(
[
"python", "./scripts/calibrate_draft_vocab.py",
"--model", tiny_llama_path,
"--data", tiny_daring_anteater_path,
"--draft_vocab_size", "100",
"--save_dir", tmp_path / "draft_vocab_cache",
],
"speculative_decoding",
)