diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/datasets.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/datasets.md new file mode 100644 index 0000000000000000000000000000000000000000..d80c0183375bcfd92780caf3923724344f88ab39 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/datasets.md @@ -0,0 +1,13 @@ + + +# datasets package + +```{include} ../../../megatron/core/datasets/readme.md +``` diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/dist_checkpointing.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/dist_checkpointing.md new file mode 100644 index 0000000000000000000000000000000000000000..ee0e5562ef3d00903a67139acf469ad4236ffffc --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/dist_checkpointing.md @@ -0,0 +1,133 @@ + + +# dist_checkpointing package + +A library for saving and loading the distributed checkpoints. +A *distributed checkpoint* in Megatron Core uses the ``torch_dist`` format, +a custom checkpointing mechanism built on top of PyTorch's native +checkpointing capabilities. + +A key property of distributed checkpoints is that a checkpoint saved under one +parallel configuration (tensor, pipeline, or data parallelism) can be loaded +under a different parallel configuration. This enables flexible scaling and +resharding of models across heterogeneous training setups. + +Using the library requires defining sharded state_dict dictionaries with functions from *mapping* and *optimizer* modules. +Those state dicts can be saved or loaded with a *serialization* module using strategies from *strategies* module. + +## Safe Checkpoint Loading + +Since **PyTorch 2.6**, the default behavior of `torch.load` is `weights_only=True`. +This ensures that only tensors and allow-listed classes are loaded, reducing the risk of arbitrary code execution. + +If you encounter an error such as: + +```bash +WeightsUnpickler error: Unsupported global: GLOBAL argparse.Namespace was not an allowed global by default. +``` + +you can fix it by explicitly allow-listing the missing class in your script: + +```python +import torch, argparse + +torch.serialization.add_safe_globals([argparse.Namespace]) +``` + +## Checkpointing Distributed Optimizer + +### Checkpoint Compatibility and Optimizer State Formats + +Beginning with **mcore v0.14**, the ``flattened_range`` attribute was removed from ``dist_checkpointing``. As a result: + +- Optimizer states saved with mcore versions <= 0.14 can no longer be loaded directly. Loading these legacy optimizer states is not supported because the required sharded metadata is no longer available. If you need to continue training from older checkpoints, refer to the workaround described below. +- Model weights from older checkpoints remain fully compatible. No extra steps are needed—model weights from checkpoints created by earlier versions load automatically; simply add the ``--no-load-optim`` flag. + +### Workaround: Loading legacy optimizer states with ToT MCore + +**Step 1: Convert the legacy checkpoint using mcore v0.15.0** + +Run a dummy training job with mcore v0.15.0 to re-save the checkpoint with new optimizer states format. + +```bash +MODEL_TRAIN_PARAMS=( + # Define model architecture and training parameters here +) +OLD_CKPT=/workspace/mcore_ckpt_old +CONVERTED_CKPT=/workspace/mcore_ckpt_0.15.0 + +torchrun --nproc_per_node=8 /opt/megatron-lm/pretrain_gpt.py \ + --save-interval 1 \ + --eval-interval 1 \ + --exit-interval 1 \ + --eval-iters 1 \ + --use-distributed-optimizer \ + --save ${CONVERTED_CKPT} \ + --load ${OLD_CKPT} \ + --ckpt-format torch_dist \ + "${MODEL_TRAIN_PARAMS[@]}" +``` + +**Step 2: Load the converted checkpoint with ToT MCore** + +Use the converted checkpoint as the input for continued training with ToT MCore. + +```bash +MODEL_TRAIN_PARAMS=( + # Define model architecture and training parameters here +) +NEW_CKPT=/workspace/mcore_ckpt_new +CONVERTED_CKPT=/workspace/mcore_ckpt_0.15.0 + +torchrun --nproc_per_node=8 /opt/megatron-lm/pretrain_gpt.py \ + --use-distributed-optimizer \ + --save ${NEW_CKPT} \ + --load ${CONVERTED_CKPT} \ + --ckpt-format torch_dist \ + "${MODEL_TRAIN_PARAMS[@]}" +``` + +After this step, training can proceed normally using ToT MCore with fully supported optimizer state loading. + +## Distributed Optimizer Checkpoint Formats + +The refactor of the Distributed Optimizer introduces **two checkpoint formats**: + +- dp_reshardable (Default) + - Fast save/load performance. + - Not reshardable — not possible to change model parallelism when using this format. + - Recommended for general training when model parallelism changes are not needed. +- fully_reshardable + - Fully reshardable — supports arbitrary changes in model parallelism. + - Slower than dp_reshardable. + - Enabled via the ``--dist-ckpt-optim-fully-reshardable`` flag. + +### Workflow for Changing Model Parallelism + +You can combine formats to optimize both flexibility and performance: + + 1. Train using ``dp_reshardable`` (default) for faster checkpointing. + 2. When you need to change model parallelism: + + - Stop training. + - Change model parallelism for train config. + - Resume training with ``--dist-ckpt-optim-fully-reshardable``. + + 3. Save at least one checkpoint under the new model parallel configuration. + 4. (Optional) To continue the training with updated model parallelism and better checkpointing performance, stop training and switch back to ``dp_reshardable`` format by removing ``--dist-ckpt-optim-fully-reshardable``. + +## Subpackages + +```{toctree} +:maxdepth: 4 + +dist_checkpointing.strategies +``` + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/dist_checkpointing.strategies.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/dist_checkpointing.strategies.md new file mode 100644 index 0000000000000000000000000000000000000000..22fe3517a545ee00e9d6232bb0233bb6e2b27eb1 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/dist_checkpointing.strategies.md @@ -0,0 +1,16 @@ + + +# dist_checkpointing.strategies package + +Package defining different checkpoint formats (backends) and saving/loading algorithms (strategies). + +Strategies can be used for implementing new checkpoint formats or implementing new (more optimal for a given use case) ways of saving/loading of existing formats. +Strategies are passed to `dist_checkpointing.load` and `dist_checkpointing.save` functions and control the actual saving/loading procedure. + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/distributed.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/distributed.md new file mode 100644 index 0000000000000000000000000000000000000000..13da4285ec5fc2ac692dff18c4d2225462873076 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/distributed.md @@ -0,0 +1,19 @@ + + +# distributed package + +This package contains various utilities to finalize model weight gradients +on each rank before the optimizer step. This includes a distributed data +parallelism wrapper to all-reduce or reduce-scatter the gradients across +data-parallel replicas, and a `finalize_model_grads` method to +synchronize gradients across different parallelism modes (e.g., 'tied' +layers on different pipeline stages, or gradients for experts in a MoE on +different ranks due to expert parallelism). + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/fusions.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/fusions.md new file mode 100644 index 0000000000000000000000000000000000000000..fdd358e813cbfcd7ab8415cee7f6ec6426725083 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/fusions.md @@ -0,0 +1,20 @@ + + +# fusions package + +This package provides modules that provide commonly fused +operations. Fusing operations improves compute efficiency by +increasing the amount of work done each time a tensor is read from +memory. To perform the fusion, modules in this either rely on PyTorch +functionality for doing just-in-time compilation +(i.e. `torch.jit.script` in older PyTorch versions of `torch.compile` +in recent versions), or call into custom kernels in external libraries +such as Apex or TransformerEngine. + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/index.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/index.md new file mode 100644 index 0000000000000000000000000000000000000000..0d39e46e7440d468ef59e350ab11b9c48a82dd8d --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/index.md @@ -0,0 +1,25 @@ + + +# Core APIs + +Low-level API reference for core Megatron components. + +```{toctree} +:maxdepth: 2 + +transformer +tensor_parallel +pipeline_parallel +fusions +distributed +datasets +dist_checkpointing +dist_checkpointing.strategies +``` diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/pipeline_parallel.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/pipeline_parallel.md new file mode 100644 index 0000000000000000000000000000000000000000..35f3c5b5cc2d9e5a50deb9f14a297dee22cb8f95 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/pipeline_parallel.md @@ -0,0 +1,16 @@ + + +# pipeline_parallel package + +This package contains implementations for two different pipeline parallelism +schedules (one without interleaving and one with interleaving, see [Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM](https://arxiv.org/abs/2104.04473) +for details), and a default no-pipelining schedule. It also contains methods +for the point-to-point communication that is needed between pipeline stages. + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/tensor_parallel.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/tensor_parallel.md new file mode 100644 index 0000000000000000000000000000000000000000..2d41c5f4467d59560fd4e6501dba2701deea0b8a --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/tensor_parallel.md @@ -0,0 +1,17 @@ + + +# tensor_parallel package + +This package contains an implementation for tensor parallelism in transformer +models (see [Megatron-LM: Training Multi-Billion Parameter Language Models +Using Model Parallelism](https://arxiv.org/abs/1909.08053) and [Reducing +Activation Recomputation in Large Transformer Models](https://arxiv.org/abs/2205.05198) +for details). + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/transformer.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/transformer.md new file mode 100644 index 0000000000000000000000000000000000000000..d35144fda4f35927dc75eea7b1e89564d9ba1ea1 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/transformer.md @@ -0,0 +1,19 @@ + + +# transformer package + +The `transformer` package provides a customizable and configurable +implementation of the transformer model architecture. Each component +of a transformer stack, from entire layers down to individual linear +layers, can be customized by swapping in different PyTorch modules +using the "spec" parameters. The +configuration of the transformer (hidden size, number of layers, +number of attention heads, etc.) is provided via a `TransformerConfig` +object. diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/index.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/index.md new file mode 100644 index 0000000000000000000000000000000000000000..7afa2450dd0ae08c4de7bbf9bc857caaff0c253b --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/index.md @@ -0,0 +1,20 @@ + + +# API Guide + +API reference documentation for Megatron Core components. + +```{toctree} +:maxdepth: 3 + +models/index +core/index +internal/index +``` diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/internal/index.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/internal/index.md new file mode 100644 index 0000000000000000000000000000000000000000..312081ce70b54275282d4934e61c87432c5a62c7 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/internal/index.md @@ -0,0 +1,19 @@ + + +# Internal Utilities + +Internal utility APIs. + +```{toctree} +:maxdepth: 2 + +num_microbatches_calculator +optimizer_param_scheduler +``` diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/internal/num_microbatches_calculator.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/internal/num_microbatches_calculator.md new file mode 100644 index 0000000000000000000000000000000000000000..0c223588ce5e191d9257272a54d96014f8a6941c --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/internal/num_microbatches_calculator.md @@ -0,0 +1,13 @@ + + +# Microbatches Calculator + +This api is used to calculate the number of microbatches required to fit a given model on a given batch size. + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/internal/optimizer_param_scheduler.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/internal/optimizer_param_scheduler.md new file mode 100644 index 0000000000000000000000000000000000000000..45e5e4b7da1d079b81e30761e73f9a353bd55bfe --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/internal/optimizer_param_scheduler.md @@ -0,0 +1,13 @@ + + +# Optimizer Parameters Scheduler + +This api is used to calculate the learning rate and weight decay for the optimizer. + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/index.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/index.md new file mode 100644 index 0000000000000000000000000000000000000000..e5bb531454b5df1fd653b1c2c5a0eaece8f65bd0 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/index.md @@ -0,0 +1,21 @@ + + +# Model APIs + +API reference for Megatron Core model implementations. + +```{toctree} +:maxdepth: 2 + +models +models.gpt +models.bert +models.t5 +``` diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.bert.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.bert.md new file mode 100644 index 0000000000000000000000000000000000000000..1543f4df8654be47b632be740df2ec00c23acc9f --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.bert.md @@ -0,0 +1,13 @@ + + +# models.bert package + +Useful package for training bert and bert like encoder only models. It optionally comes with a binary head that can be used for classification tasks . + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.gpt.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.gpt.md new file mode 100644 index 0000000000000000000000000000000000000000..1c3cbb5484c875385525db9571537ade6b6ec56a --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.gpt.md @@ -0,0 +1,13 @@ + + +# models.gpt package + +This is the implementation of the popular GPT model. It supports several features like model parallelization (Tensor Parallel, Pipeline Parallel, Data Parallel) , mixture of experts, FP8 , Distributed optimizer etc. We are constantly adding new features. So be on the lookout or raise an issue if you want to have something added. + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.md new file mode 100644 index 0000000000000000000000000000000000000000..a633546f0c924cc6254c1d7aed8e7147896d4883 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.md @@ -0,0 +1,23 @@ + + +# models package + +This package contains most of the popular LLMs . Currently we have support for GPT, Bert, and T5 . This is an ever growing list so keep an eye out. + +## Subpackages + +```{toctree} +:maxdepth: 4 + +models.gpt +models.t5 +models.bert +``` + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.t5.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.t5.md new file mode 100644 index 0000000000000000000000000000000000000000..4694b80113a038eafcd204a615cee48672f92dfa --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.t5.md @@ -0,0 +1,11 @@ + + +# models.t5 package + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/router_replay.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/router_replay.md new file mode 100644 index 0000000000000000000000000000000000000000..88476ea753739d86189b7773464ede79dd077956 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/router_replay.md @@ -0,0 +1,186 @@ + + +# Design Document: MoE Router Replay Feature + +## 1. Overview + +This document provides a detailed description of the "Router Replay" feature implemented within the Megatron-LM Core for Mixture-of-Experts (MoE) models. + +This feature is designed to enhance determinism and analyzability in MoE model training and inference. It enables the model to load routing decisions from a predefined file and enforce their use during the forward pass, thereby bypassing the real-time routing computation. + +## 2. Motivation + +* **Determinism & Reproducibility**: In distributed training, MoE routing decisions can exhibit minor variations due to factors like floating-point precision. By replaying a fixed routing table, the MoE computation path is guaranteed to be identical across runs, which facilitates debugging and reproducing experimental results. +* **Performance Profiling**: The router's own computation (e.g., logits calculation, top-k selection) incurs overhead. In replay mode, this part of the computation can be completely skipped, allowing for more precise isolation and profiling of performance bottlenecks within the Expert Layers themselves. +* **Debugging Aid**: When issues arise in the model, fixing the routing decisions helps to isolate variables, making it easier to determine whether the problem lies with the routing mechanism or the expert computations. + +## 3. Design and Architecture + +The design follows the principles of being non-intrusive and on-demand, with the core idea of activating the replay logic only when explicitly requested by the user. + +* **Core Components**: + * `RouterReplay` (located in `megatron/core/transformer/moe/router_replay.py`): A utility class for replaying MoE routing decisions. When enabled via the `moe_enable_routing_replay` flag, a separate instance of `RouterReplay` is created for each MoE layer's router. Each instance is responsible for loading routing data and providing the deterministic routing decisions for its corresponding layer during the forward pass. + * `moe_enable_routing_replay` (located in `megatron/core/transformer/transformer_config.py`): A boolean global configuration flag that serves as the sole entry point for enabling this feature. + +* **Workflow**: + The feature supports different modes, such as recording and replaying, controlled by a `RouterReplayAction`. + + 1. **Enabling the Feature**: The user sets `moe_enable_routing_replay` to `True` in the model configuration. + 2. **Initialization**: When `moe_enable_routing_replay` is true, each `TopKRouter` creates its own `RouterReplay` instance. + 3. **Mode Configuration**: The user must programmatically set the desired router replay action (e.g., `record`, `forward_replay`, `backward_replay`) on the `RouterReplay` instances. + 4. **Execution Flow (within a mini-batch)**: + * **Forward Pass**: + * For each micro-batch, the `topk_routing_with_score_function` checks the `router_replay_action`. + * **In `record` mode**: The dynamically computed `top-k` expert indices are captured and stored. + * **In `forward_replay` mode**: The function retrieves pre-loaded expert indices from `target_topk_idx`. These indices are used for the forward computation and are also appended to the `replay_backward_list` to prepare for the backward pass. + * **Backward Pass**: + * For each micro-batch (processed in reverse order in pipeline parallelism), the `router_replay_action` is checked again. + * **In `backward_replay` mode**: The function retrieves the expert indices for the corresponding micro-batch by popping them from the `replay_backward_list`. This mode is intended for training recomputation (e.g., activation checkpointing and pipeline recompute) so the same routing decisions are used during recompute/backward as in forward, ensuring determinism and correctness. + +## 4. Implementation Details + +The implementation cleanly separates the replay logic from the router's core computation. + +* **`megatron/core/transformer/transformer_config.py`**: + * Adds the configuration option `moe_enable_routing_replay: bool = False`. + +* **`megatron/core/transformer/moe/moe_utils.py`**: + * Introduces the `RouterReplay` class to manage the state for recording and replaying routing decisions for a single MoE layer. + * `target_topk_idx`: An attribute holding the expert indices for the current micro-batch during forward replay mode. + * `recorded_topk_idx`: An attribute for storing the computed expert indices when in record mode. + * `replay_backward_list`: A list that accumulates the `top-k` indices used during the forward passes of a mini-batch. This list is consumed in FIFO order during the backward pass to ensure correctness under pipeline parallelism. + * `set_target_indices()`: A method to load the replay indices into `target_topk_idx` for the forward pass. + * `record_indices()`: A method to save the computed indices. + * The `topk_routing_with_score_function` is modified to contain the core logic. It checks the `router_replay_action` on the `router_replay` instance and accordingly performs one of the following actions: computes and records indices, replays indices from `target_topk_idx` (for forward), replays indices from `replay_backward_list` (for backward), or falls through to the default dynamic routing. + +### Training recompute usage + +- During forward replay, `set_target_indices()` prepares `replay_backward_list` so each micro-batch’s indices are available for recomputation. +- During recompute/backward, set action to `REPLAY_BACKWARD` so indices are consumed in FIFO order to mirror the forward sequence. + +## 5. Usage Guide + +1. **Enable & Instantiate** + - Create one `RouterReplay` instance per MoE router layer when building the model. + - Optionally use the global helpers to set/clear actions across all layers. +2. **Record Routing Decisions** + - Set action: `RouterReplay.set_global_router_replay_action(RouterReplayAction.RECORD)`. + - Run the model; retrieve per-layer indices via `RouterReplay.get_recorded_data()` and persist. +3. **Forward Replay** + - Load indices and distribute: `RouterReplay.set_replay_data(list_of_tensors)`. + - Set action: `RouterReplay.set_global_router_replay_action(RouterReplayAction.REPLAY_FORWARD)`. + - Run the model; dynamic top‑k is bypassed and target indices are used. +4. **Backward Replay** + - For training recomputation (activation checkpointing or pipeline recompute), set action: `REPLAY_BACKWARD` during recomputation. + - Per micro‑batch indices are consumed from `replay_backward_list` in FIFO order. +5. **Cleanup** + - Use `RouterReplay.clear_global_indices()`, `RouterReplay.clear_global_router_replay_action()`, and `RouterReplay.clear_global_router_replay_instances()` to restore default behavior and prevent memory leaks. + +### Quick usage with `topk_routing_with_score_function` + +```python +import torch +from megatron.core.transformer.moe.router_replay import RouterReplay, RouterReplayAction +from megatron.core.transformer.moe.moe_utils import topk_routing_with_score_function + +rr = RouterReplay() + +# Record +RouterReplay.set_global_router_replay_action(RouterReplayAction.RECORD) +logits = torch.randn(8, 16) +probs_rec, routing_map_rec = topk_routing_with_score_function( + logits=logits, topk=2, use_pre_softmax=False, score_function="softmax", router_replay=rr, +) +recorded = rr.get_recorded_indices() +torch.save(recorded, "/tmp/replay.pt") + +# Forward replay +rr.clear_router_replay_action() +rr.set_router_replay_action(RouterReplayAction.REPLAY_FORWARD) +target = torch.load("/tmp/replay.pt") +rr.set_target_indices(target) +probs_rep, routing_map_rep = topk_routing_with_score_function( + logits=logits, topk=2, use_pre_softmax=False, score_function="softmax", router_replay=rr, +) + +RouterReplay.clear_global_router_replay_action() +RouterReplay.clear_global_indices() +RouterReplay.clear_global_router_replay_instances() +``` + +## 6. Minimal Demo + +Here is a minimal code example showing how to use RouterReplay for recording and replaying: + +```python +import torch +import torch.distributed as dist +from megatron.core.transformer.transformer_config import TransformerConfig +from megatron.core.transformer.moe.router import TopKRouter +from megatron.core.transformer.moe.router_replay import RouterReplay, RouterReplayAction + + +# Initialize distributed training +if not dist.is_initialized(): + dist.init_process_group(backend="nccl") + +# Create a transformer config with RouterReplay enabled +config = TransformerConfig( + num_experts=8, + expert_model_parallel_size=1, + num_top_k=2, + moe_enable_routing_replay=True +) + +# Create a TopKRouter instance +router = TopKRouter(config) + +# Generate sample input (batch_size, sequence_length, hidden_size) +logits = torch.randn(16, 32, 8).to(torch.cuda.current_device()) + +# ----------------- +# 1. Recording Mode +# ----------------- +print("=== Recording Mode ===") +# Set global router replay action to RECORD +RouterReplay.set_global_router_replay_action(RouterReplayAction.RECORD) + +# Perform routing +routing_output = router.forward(logits) +print(f"Recorded top-k indices shape: {routing_output.top_k_idx.shape}") + +# ----------------- +# 2. Forward Replay Mode +# ----------------- +print("\n=== Forward Replay Mode ===") +# Save recorded indices to a file +torch.save(routing_output.top_k_idx, "/tmp/replay.pt") + +# Load indices from file and set as target for replay +replay_indices = torch.load("/tmp/replay.pt") +for router_instance in RouterReplay.global_router_replay_instances: + router_instance.target_topk_idx = replay_indices + +# Set global router replay action to REPLAY_FORWARD +RouterReplay.set_global_router_replay_action(RouterReplayAction.REPLAY_FORWARD) + +# Perform routing again - this will use the replayed indices +replay_routing_output = router.forward(logits) +print(f"Replayed top-k indices shape: {replay_routing_output.top_k_idx.shape}") +print(f"Are indices the same? {torch.equal(routing_output.top_k_idx, replay_routing_output.top_k_idx)}") + + +# Clean up +RouterReplay.clear_global_router_replay_action() +RouterReplay.clear_global_indices() +RouterReplay.clear_global_router_replay_instances() +if dist.is_initialized(): + dist.destroy_process_group() +``` diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/install.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/install.md new file mode 100644 index 0000000000000000000000000000000000000000..5781d065fae509be055190ac20f1a9efe34c8263 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/install.md @@ -0,0 +1,123 @@ + + +# Installation + +## System Requirements + +### Hardware + +- **Recommended**: NVIDIA Turing architecture or later +- **FP8 Support**: Requires NVIDIA Hopper, Ada, or Blackwell GPUs + +### Software + +- **Python**: >= 3.10 (3.12 recommended) +- **PyTorch**: >= 2.6.0 +- **CUDA Toolkit**: Latest stable version + + +## Prerequisites + +Install [uv](https://docs.astral.sh/uv/), a fast Python package installer: + +```bash +curl -LsSf https://astral.sh/uv/install.sh | sh +``` + + +## Option A: Pip Install (Recommended) + +Install the latest stable release from PyPI: + +```bash +uv pip install megatron-core +``` + +To include optional training dependencies (Weights & Biases, SentencePiece, HF Transformers): + +```bash +uv pip install "megatron-core[training]" +``` + +For all extras including [Transformer Engine](https://github.com/NVIDIA/TransformerEngine): + +```bash +uv pip install --group build +uv pip install --no-build-isolation "megatron-core[training,dev]" +``` + +```{note} +`--no-build-isolation` requires build dependencies to be pre-installed in the environment. `torch` is needed because several `[dev]` packages (`mamba-ssm`, `nv-grouped-gemm`, `transformer-engine`) import it at build time to compile CUDA kernels. Expect this step to take **20+ minutes** depending on your hardware. If you prefer pre-built binaries, the [NGC Container](#option-c-ngc-container) ships with these pre-compiled. +``` + +```{warning} +Building from source can consume a large amount of memory. By default the build runs one compiler job per CPU core, which may cause out-of-memory failures on machines with many cores. To limit parallel compilation jobs, set the `MAX_JOBS` environment variable before installing (e.g. `MAX_JOBS=4`). +``` + +```{tip} +For a lighter set of development dependencies without Transformer Engine and ModelOpt, use `[lts]` instead of `[dev]`: `uv pip install --no-build-isolation "megatron-core[training,lts]"`. The `[lts]` and `[dev]` extras are mutually exclusive. +``` + +To clone the repository for examples: + +```bash +git clone https://github.com/NVIDIA/Megatron-LM.git +``` + + +## Option B: Install from Source + +For development or to run the latest unreleased code: + +```bash +git clone https://github.com/NVIDIA/Megatron-LM.git +cd Megatron-LM +uv pip install -e . +``` + +To install with all development dependencies (includes Transformer Engine, requires pre-installed build deps): + +```bash +uv pip install --group build +uv pip install --no-build-isolation -e ".[training,dev]" +``` + +```{tip} +If the build runs out of memory, limit parallel compilation jobs with `MAX_JOBS=4 uv pip install --no-build-isolation -e ".[training,dev]"`. +``` + + +## Option C: NGC Container + +For a pre-configured environment with all dependencies pre-installed (PyTorch, CUDA, cuDNN, NCCL, Transformer Engine), use the [PyTorch NGC Container](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/pytorch). + +We recommend using the **previous month's** NGC container rather than the latest one to ensure compatibility with the current Megatron Core release and testing matrix. + +```bash +docker run --gpus all -it --rm \ + -v /path/to/dataset:/workspace/dataset \ + -v /path/to/checkpoints:/workspace/checkpoints \ + -e PIP_CONSTRAINT= \ + nvcr.io/nvidia/pytorch:26.01-py3 +``` + +```{note} +The NGC PyTorch container constrains the Python environment globally via `PIP_CONSTRAINT`. The `-e PIP_CONSTRAINT=` flag above unsets this so that Megatron Core and its dependencies install correctly. +``` + +Then install Megatron Core inside the container (torch is already available in the NGC image): + +```bash +pip install uv +uv pip install --no-build-isolation "megatron-core[training,dev]" +``` + + +You are now ready to run training. See [Your First Training Run](quickstart.md) for next steps. diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/overview.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/overview.md new file mode 100644 index 0000000000000000000000000000000000000000..b7f84ee22e5ccc36ffc0b21e56531bd60d4ce0c7 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/overview.md @@ -0,0 +1,93 @@ + + +# Overview + +Megatron-Core and Megatron-LM are open-source tools that are typically used together to train LLMs at scale across GPUs. Megatron-Core expands the capability of Megatron-LM. Megatron Bridge connects Megatron-Core and Megatron-LM to other popular training models, such as Hugging Face. + +## Megatron Core + +NVIDIA Megatron Core is a library of essential building blocks for highly efficient large-scale generative AI training. It can be used to train models with unparalleled speed at scale across thousands of GPUs. It provides an extensive set of tools for multimodal and speech AI. It expands Megatron LM capabilities. + +Megatron-Core contains GPU-optimized techniques featuring advanced parallelism strategies, optimizations like FP8 training, and support for the latest LLM, MoE, and multimodal architectures. It abstracts these techniques into composable and modular APIs. + +Megatron-Core is compatible with all NVIDIA Tensor Core GPUs and popular LLM architectures such as GPT, BERT, T5, and RETRO. + + +**Composable library** with GPU-optimized building blocks for custom training frameworks. + +**Best for:** + +- **Framework developers** building on top of modular and optimized components +- **Research teams** needing custom training loops, optimizers, or data pipelines +- **ML engineers** requiring fault-tolerant training pipelines + +**What you get:** + +- Composable transformer building blocks (attention, MLP) +- Advanced parallelism strategies (TP, PP, DP, EP, CP) +- Pipeline schedules and distributed optimizers +- Mixed precision support (FP16, BF16, FP8) +- GPU-optimized kernels and memory management +- High-performance dataloaders and dataset utilities +- Model architectures (LLaMA, Qwen, GPT, Mixtral, Mamba) + +## Megatron-LM + +Megatron-LM is a reference implementation, with a lightweight large-scale LLM training framework. It offers a customizable native PyTorch training loop with fewer abstraction layers. It was designed for scaling transformer models to the multi-billion and trillion-parameter regimes under realistic memory and compute constraints. **It serves as a straightforward entry point for exploring Megatron-Core.** + +It uses advanced parallelization techniques including model parallelism (tensor and pipeline), to allow models with billions of parameters to fit and train across large GPU clusters. It enables breakthroughs in large-scale NLP tasks. It splits model computations across many GPUs, overcoming single-GPU memory limits for training huge models, like GPT-style transformers. + + +**Reference implementation** that includes Megatron Core plus everything needed to train models. + +**Best for:** + +- **Training state-of-the-art foundation models** at scale with cutting-edge performance on latest NVIDIA hardware +- **Research teams** exploring new architectures and training techniques +- **Learning distributed training** concepts and best practices +- **Quick experimentation** with proven model configurations + +**What you get:** + +- Pre-configured training scripts for GPT, LLaMA, DeepSeek, Qwen, and more. +- End-to-end examples from data prep to evaluation +- Research-focused tools and utilities + + + +## Megatron Bridge + +Megatron Bridge provides out-of-the-box bridges and training recipes for models built on top of base model architectures from Megatron Core. + +Megatron Bridge provides a robust, parallelism-aware pathway to convert models and checkpoints. This bidirectional converter performs on-the-fly, model-parallel-aware, per-parameter conversion, and full in-memory loading. + +After training or modifying a Megatron model, you can convert it again for deployment or sharing. + +[Megatron Bridge](https://github.com/NVIDIA-NeMo/Megatron-Bridge) + + + +## Ecosystem Libraries + +**Libraries used by Megatron Core:** + +- **[Megatron Energon](https://github.com/NVIDIA/Megatron-Energon)** - Multi-modal data loader (text, images, video, audio) with distributed loading and dataset blending +- **[Transformer Engine](https://github.com/NVIDIA/TransformerEngine)** - Optimized kernels and FP8 mixed precision support +- **[Resiliency Extension (NVRx)](https://github.com/NVIDIA/nvidia-resiliency-ext)** - Fault tolerant training with failure detection and recovery + +**Libraries using Megatron Core:** + +- **[Megatron Bridge](https://github.com/NVIDIA-NeMo/Megatron-Bridge)** - Training library with bidirectional Hugging Face ↔ Megatron checkpoint conversion, flexible training loops, and production-ready recipes +- **[NeMo RL](https://github.com/NVIDIA-NeMo/RL)** - Scalable toolkit for efficient reinforcement learning with RLHF, DPO, and other post-training methods +- **[NeMo Framework](https://docs.nvidia.com/nemo-framework/user-guide/latest/overview.html)** - Enterprise framework with cloud-native support and end-to-end examples +- **[Model Optimizer (ModelOpt)](https://github.com/NVIDIA/Model-Optimizer)** - Model optimization toolkit for quantization, pruning, distillation, speculative decoding, and more. Checkout end-to-end examples in [examples/post_training/modelopt](https://github.com/NVIDIA/Megatron-LM/tree/main/examples/post_training/modelopt). + +**Compatible with:** [Hugging Face Accelerate](https://github.com/huggingface/accelerate), [Colossal-AI](https://github.com/hpcaitech/ColossalAI), [DeepSpeed](https://github.com/microsoft/DeepSpeed) + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/quickstart.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/quickstart.md new file mode 100644 index 0000000000000000000000000000000000000000..c8797aeedd426df97fff81224d4c909d0be10342 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/quickstart.md @@ -0,0 +1,68 @@ + + +# Your First Training Run + +This guide walks you through running your first training jobs with Megatron Core. Make sure you have completed [installation](install.md) before proceeding. + +## Simple Training Example + +Run a minimal distributed training loop with mock data on 2 GPUs: + +```bash +torchrun --nproc_per_node=2 examples/run_simple_mcore_train_loop.py +``` + +## LLaMA-3 Training Example + +Train a LLaMA-3 8B model with FP8 precision on 8 GPUs using mock data: + +```bash +./examples/llama/train_llama3_8b_h100_fp8.sh +``` + +## Data Preparation + +To train on your own data, Megatron expects preprocessed binary files (`.bin` and `.idx`). + +### 1. Prepare a JSONL File + +Each line should contain a `text` field: + +```json +{"text": "Your training text here..."} +{"text": "Another training sample..."} +``` + +### 2. Preprocess the Data + +```bash +python tools/preprocess_data.py \ + --input data.jsonl \ + --output-prefix processed_data \ + --tokenizer-type HuggingFaceTokenizer \ + --tokenizer-model /path/to/tokenizer.model \ + --workers 8 \ + --append-eod +``` + +### Key Arguments + +- `--input`: Path to input JSON/JSONL file +- `--output-prefix`: Prefix for output binary files (.bin and .idx) +- `--tokenizer-type`: Tokenizer type (`HuggingFaceTokenizer`, `GPT2BPETokenizer`, etc.) +- `--tokenizer-model`: Path to tokenizer model file +- `--workers`: Number of parallel workers for processing +- `--append-eod`: Add end-of-document token + +## Next Steps + +- Explore [Parallelism Strategies](../user-guide/parallelism-guide.md) to scale your training +- Learn about [Data Preparation](../user-guide/data-preparation.md) best practices +- Check out [Advanced Features](../user-guide/features/index.md) for advanced capabilities diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/releasenotes.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/releasenotes.md new file mode 100644 index 0000000000000000000000000000000000000000..e624de19f15b6ca59a1414780743e0e57cb9e4fc --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/releasenotes.md @@ -0,0 +1,19 @@ + + +# Release Notes + + +## Roadmaps + +Stay up-to-date with our development roadmaps and planned features: + +- **[MoE Q3-Q4 2025 Roadmap](https://github.com/NVIDIA/Megatron-LM/issues/1729)** - Comprehensive MoE feature development including DeepSeek-V3, Qwen3, advanced parallelism, FP8 optimizations, and Blackwell enhancements +- **[GPT-OSS Implementation Tracker](https://github.com/NVIDIA/Megatron-LM/issues/1739)** - Advanced features including YaRN RoPE scaling, attention sinks, and custom activation functions + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/models/index.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/models/index.md new file mode 100644 index 0000000000000000000000000000000000000000..0ee379b01bdca56089f65d97dc096d97f8804805 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/models/index.md @@ -0,0 +1,26 @@ + + +# Supported Models + +Megatron Core supports a wide range of language and multimodal models with optimized implementations for large-scale training. + +## Model Conversion + +For converting HuggingFace models to Megatron format, use [Megatron Bridge](https://github.com/NVIDIA-NeMo/Megatron-Bridge), the official standalone converter. Megatron Bridge supports an extensive list of models including LLaMA, Mistral, Mixtral, Qwen, DeepSeek, Gemma, Phi, Nemotron, and many more. + +See the [Megatron Bridge supported models list](https://github.com/NVIDIA-NeMo/Megatron-Bridge?tab=readme-ov-file#supported-models) for the complete and up-to-date list of supported models. + +```{toctree} +:maxdepth: 1 + +llms +multimodal +../llama_mistral +``` diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/models/llms.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/models/llms.md new file mode 100644 index 0000000000000000000000000000000000000000..f649673a2cc23f6af22583053a800ad6d33eb3f4 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/models/llms.md @@ -0,0 +1,59 @@ + + +# Language Models + +Megatron Core supports the following language model architectures for large-scale training. + +## Converting HuggingFace Models + +Use [**Megatron Bridge**](https://github.com/NVIDIA-NeMo/Megatron-Bridge) to convert HuggingFace models to Megatron format. Megatron Bridge is the official standalone converter with support for an extensive list of models including LLaMA, Mistral, Mixtral, Qwen, DeepSeek, Gemma, Phi, Nemotron, and many more. + +See the [Megatron Bridge supported models list](https://github.com/NVIDIA-NeMo/Megatron-Bridge?tab=readme-ov-file#supported-models) for the complete and up-to-date list. + +## Decoder-Only Models + +| Model | Description | Key Features | +|-------|-------------|--------------| +| **GPT** | Generative Pre-trained Transformer | Standard autoregressive LM, foundational architecture | +| **LLaMA** | Meta's LLaMA family | Efficient architecture with RoPE, SwiGLU, RMSNorm | +| **Mistral** | Mistral AI models | Sliding window attention, efficient inference | +| **Mixtral** | Sparse Mixture-of-Experts | 8x7B MoE architecture for efficient scaling | +| **Qwen** | Alibaba's Qwen series | HuggingFace integration, multilingual support | +| **Mamba** | State Space Model | Subquadratic sequence length scaling, efficient long context | + +## Encoder-Only Models + +| Model | Description | Key Features | +|-------|-------------|--------------| +| **BERT** | Bidirectional Encoder Representations | Masked language modeling, classification tasks | + +## Encoder-Decoder Models + +| Model | Description | Key Features | +|-------|-------------|--------------| +| **T5** | Text-to-Text Transfer Transformer | Unified text-to-text framework, sequence-to-sequence | + +## Example Scripts + +Training examples for these models can be found in the `examples/` directory: +- `examples/gpt3/` - GPT-3 training scripts +- `examples/llama/` - LLaMA training scripts +- `examples/mixtral/` - Mixtral MoE training +- `examples/mamba/` - Mamba training scripts +- `examples/bert/` - BERT training scripts +- `examples/t5/` - T5 training scripts + +## Model Implementation + +All language models are built using Megatron Core's composable transformer blocks, enabling: +- Flexible parallelism strategies (TP, PP, DP, EP, CP) +- Mixed precision training (FP16, BF16, FP8) +- Distributed checkpointing +- Efficient memory management diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/models/multimodal.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/models/multimodal.md new file mode 100644 index 0000000000000000000000000000000000000000..dce977e261da7c218261136ef15fa6f93e978364 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/models/multimodal.md @@ -0,0 +1,70 @@ + + +# Multimodal Models + +Megatron Core supports multimodal models that combine language with vision, audio, and other modalities for comprehensive multimodal understanding. + +## MIMO: Multimodal In/Out Framework + +**MIMO (Multimodal In/Out Model)** is an experimental framework in Megatron Core that supports arbitrary combinations of modalities including vision, audio, and text. MIMO provides a flexible architecture for building custom multimodal models. + +> **Note**: MIMO is experimental and under active development. The API may change in future releases. + +**Key Features:** +- Arbitrary modality combinations (vision, audio, text, etc.) +- Flexible encoder architecture for different input modalities +- Unified embedding space across modalities +- Support for both vision-language and audio-vision-language models + +See [examples/mimo](https://github.com/NVIDIA/Megatron-LM/tree/main/examples/mimo) for training scripts and examples. + +## Vision-Language Models + +| Model | Description | Vision Encoder | Language Model | +|-------|-------------|----------------|----------------| +| **LLaVA** | Visual instruction tuning | CLIP ViT-L/14 | Mistral-7B / LLaMA | +| **NVLM** | NVIDIA Vision-Language Model | CLIP / Custom ViT | LLaMA-based | +| **LLaMA 3.1 Nemotron Nano VL** | Efficient multimodal model | Vision Transformer | LLaMA 3.1 8B | + +## Vision Encoders + +| Model | Description | Key Features | +|-------|-------------|--------------| +| **CLIP ViT** | OpenAI's CLIP Vision Transformer | Image-text alignment, multiple scales (L/14@336px) | +| **RADIO** | Resolution-Agnostic Dynamic Image Optimization | Flexible resolution handling, efficient vision encoding | + +## Diffusion Models + +For multimodal diffusion models (image generation, text-to-image, etc.), see [NeMo Diffusion Models](https://github.com/NVIDIA-NeMo/NeMo/tree/main/nemo/collections/diffusion). NeMo provides production-ready implementations of: +- Stable Diffusion variants +- Text-to-image generation +- Image-to-image translation +- ControlNet and other conditioning mechanisms + +## Multimodal Features + +- **Image-Text Alignment**: Pre-training on image-caption pairs +- **Visual Instruction Tuning**: Fine-tuning on instruction-following datasets +- **Flexible Vision Encoders**: Support for different ViT architectures and resolutions +- **Combined Checkpointing**: Unified checkpoints combining vision and language models +- **Efficient Training**: Full parallelism support (TP, PP, DP) for both vision and language components + +## Example Scripts + +Multimodal training examples can be found in the following directories: + +**MIMO Framework:** +- `examples/mimo/` - Multimodal In/Out training with support for vision-language and audio-vision-language models + +**Specific Multimodal Models:** +- `examples/multimodal/` - LLaVA-style training with Mistral + CLIP +- `examples/multimodal/nvlm/` - NVLM training scripts +- `examples/multimodal/llama_3p1_nemotron_nano_vl_8b_v1/` - Nemotron VL training +- `examples/multimodal/radio/` - RADIO vision encoder integration diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/custom_fsdp.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/custom_fsdp.md new file mode 100644 index 0000000000000000000000000000000000000000..ab1a1efc4020959df2a6626b27e81a8dc33bbbb1 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/custom_fsdp.md @@ -0,0 +1,195 @@ + + +# Megatron FSDP + +**NOTE: In M-Core 0.14, the custom FSDP refactored its checkpoint implementation to use DTensor-based torch distributed checkpointing. The custom FSDP was also renamed Megatron FSDP. The relevant sections of this document are no longer applicable.** + +## How to use ? + +Add these flag to enable MCore custom FSDP. + +```bash +--use-megatron-fsdp +--data-parallel-sharding-strategy optim_grads_params +--no-gradient-accumulation-fusion +--use-distributed-optimizer +``` + +For a practical guide covering required configurations, checkpoint conversion, and example scripts, see the [Megatron-FSDP User Guide](../../discussions/megatron-fsdp-user-guide/megatron-fsdp-user-guide.md). + +## Key Features + +- **Sharding Strategy**: Efficiently shards optimizer states, gradients, and parameters to reduce memory consumption. +- **Communication and Computation Overlap**: Optimized to enable concurrent execution of communication and computation, enhancing overall efficiency. +- **Supports automatic mixed precision training**: Compatible with BF16 O1/O2/O3 recipes, as well as FP8 compute with FP32 parameters and FP8 parameter training, allowing for flexible precision configurations. +- **Tensor Parallelism (TP), Expert Parallelism (EP) and Context Parallelism (CP)**: Compatible with TP, EP and CP configurations, enabling efficient scaling of large language models. +- **Distributed Model Initialization with Meta Device**: Allows model initialization using meta device, followed by layer-by-layer initialization of distributed model weight buffers via the `Module.reset_parameters` API, facilitating the initialization of extremely large models. + +## Configuration Recommendations + +### 1. Disable `CUDA_DEVICE_MAX_CONNECTIONS` + +To ensure full parallelization of FSDP communication and computation, disable the CUDA_DEVICE_MAX_CONNECTIONS environment variable. This step avoids potential bubble in CUDA stream. (But it may slow down TP and CP to some extent.) + +```bash +unset CUDA_DEVICE_MAX_CONNECTIONS +``` + +### 2. Add `--calculate-per-token-loss` + +For gradients sharding mode optimization, include the `--calculate-per-token-loss` flag in your training script. This improves performance by reducing the frequency of gradient scaling, which is also a sizable drain on SM resources. + +## Design of Custom FSDP + +### 1. Overview + +The custom Fully Sharded Data Parallelism (FSDP) implementation in Megatron-Core is specifically designed to optimize memory consumption and performance for large language models. The core design principles include: + + - **Optimized for Large Language Models**: This custom FSDP implementation is tailored to efficiently scale with models containing billions of parameters, ensuring seamless execution and training of massive models. + - **Efficient Memory Consumption**: By strategically sharding optimizer states, gradients, and model parameters, the custom FSDP significantly reduces memory usage. This approach enables the training of models that would otherwise be too large to fit in memory. + - **Efficient Workflow & Overlapping Communication and Computation**: The implementation is engineered to minimize the number of communication steps required during training. It maximizes the overlap between communication and computation, thereby enhancing overall training efficiency and reducing latency. + - **Support for MCore's Efficient Training Methods**: The custom FSDP seamlessly integrates with Megatron-Core's advanced parallelism techniques, including tensor parallelism, expert parallelism and context parallelism. Additionally, it supports automatic mixed precision training, further optimizing training performance and efficiency. + +The design of Custom FSDP draws inspiration from PyTorch FSDP [Zhao, Yanli, et al.](https://arxiv.org/pdf/2304.11277) and MCore's distributed optimizer. The introduction to PyTorch FSDP is referenced here to clarify the underlying concepts of the custom FSDP design. + +> In DistributedDataParallel, (DDP) training, each process/ worker owns a replica of the model and processes a batch of data, finally it uses all-reduce to sum up gradients over different workers. In DDP the model weights and optimizer states are replicated across all workers. FSDP is a type of data parallelism that shards model parameters, optimizer states and gradients across DDP ranks. + +> When training with FSDP, the GPU memory footprint is smaller than when training with DDP across all workers. This makes the training of some very large models feasible by allowing larger models or batch sizes to fit on device. This comes with the cost of increased communication volume. The communication overhead is reduced by internal optimizations like overlapping communication and computation. + +![FSDP workflow](../../images/custom_fsdp/FSDP_workflow.png) + +*Notice that the unit processed in workflow here is the “FSDP instance 1: N layers”, where an FSDP instance is the smallest FSDP processing unit (also a PyTorch module), which means that we can safely release this module weights after using it (executing the forward or backward of this module), and there will be no other computations computations relying on these weights. This capability is the foundation of FSDP's layer-by-layer execution and memory-saving strategy. An FSDP instance is also referred to as an **FSDP Unit**.* + +*It is worth noting that an FSDP instance can correspond to multiple FSDP parameter groups. These groups are separated by Data Parallel (DP) communication groups and the data type of the parameter or gradient. Consequently, an FSDP instance may require several parameter-gather tasks before execution (forward or backward). Each **FSDP parameter group** corresponds to one **Data Parallel Buffer** in custom FSDP.* + +At a high level FSDP works as follow: + +In constructor + - Shard model parameters and each rank only keeps its own shard + +In forward path + - Run all_gather to collect all shards from all ranks to recover the full parameter in this FSDP unit + - Run forward computation + - Discard parameter shards it has just collected + +In backward path + - Run all_gather to collect all shards from all ranks to recover the full parameter in this FSDP unit + - Run backward computation + - Run reduce_scatter to sync gradients + - Discard parameters. + +One way to view FSDP’s sharding is to decompose the DDP gradient all-reduce into reduce-scatter and all-gather. Specifically, during the backward pass, FSDP reduces and scatters gradients, ensuring that each rank possesses a shard of the gradients. Then it updates the corresponding shard of the parameters in the optimizer step. Finally, in the subsequent forward pass, it performs an all-gather operation to collect and combine the updated parameter shards. + +![FSDP Allreduce](../../images/custom_fsdp/FSDP_Allreduce.png) + +### 2. Custom FSDP underlying data structure + +To implement the FSDP functionality described above, the custom FSDP is designed with the following Python classes and data structure: + +![MCore Custom FSDP Class Diagram](../../images/custom_fsdp/MCore_Custom_FSDP_Class_Diagram.png) + +### 3. The custom FSDP interface: FullyShardedDataParallel + +The custom FSDP provides the same programming interface as PyTorch's DistributedDataParallel (DDP) as FullyShardedDataParallel (FSDP). For example, you can apply FSDP to models as follows: + +```python +# Initialize model and optimizer +ddp_config.use_megatron_fsdp = True +ddp_config.data_parallel_sharding_strategy = "optim_grads_params" +model = GPTModel(transformer_config) +model = FullyShardedDataParallel( + transformer_config, + model, + ddp_config, + fsdp_unit_modules = [TransformerLayer, LanguageModelEmbedding], +) +optimizer = torch.optim.AdamW(model.parameters(), lr=lr) +optimizer = DistributedOptimizer(optimizer, [model], [model.param_and_grad_buffer]) + +# Training loop +def train_step(inputs, labels): + optimizer.zero_grad() + for mbs_input, mbs_label in zip(inputs, labels): + outputs = model(mbs_input) + loss = loss_fn(outputs, mbs_label) + loss.backward() + optimizer.step() + +# Save and load model and optimizer state dict +def model_and_optimizer_state_dict(): + state_dict = { + "model": model.sharded_state_dict(), + "optimizer": optimizer.sharded_state_dict(), + } + return state_dict + +def load_model_and_optimizer_state_dict(state_dict): + model.load_state_dict(state_dict["model"]) + optimizer.load_state_dict(state_dict["optimizer"]) +``` + +**Key Notes:** + - You can configure which modules should be treated as FSDP units via the `fsdp_unit_modules` argument. This configuration is mandatory. + - The custom FSDP must be used with a distributed optimizer since it provides distributed checkpointing. + - The data-parallel communication group for parameters is not explicitly shown. Custom FSDP configures these groups as either DP (data-parallel) or EDP (expert data-parallel) based on parameter markings. + +#### 3.1 Initializing Models on the Meta Device + +For training particularly large models with FSDP, you can initialize the model on the meta device. Using PyTorch's `reset_parameters` API, you can initialize model weights layer by layer during the construction of the `ParamAndGradBuffer`. Most PyTorch native modules and TransformerEngine modules support this API (e.g., [PyTorch Linear](https://github.com/pytorch/pytorch/blob/v2.6.0/torch/nn/modules/linear.py#L114), [TE LayerNormLinear](https://github.com/NVIDIA/TransformerEngine/blob/release_v2.0/transformer_engine/pytorch/module/layernorm_linear.py#L1107)). + +```python +# Initialize model on meta device +with torch.device("meta"): + model = GPTModel(config) + +model = FullyShardedDataParallel( + transformer_config, + model, + ddp_config, + fsdp_unit_modules=[TransformerLayer, LanguageModelEmbedding], +) +``` + +**Important Considerations:** +1. *Custom Modules*: If your model contains custom modules, ensure they implement the `reset_parameters` API. Otherwise, you may need to force parameter initialization on a CUDA or CPU device. +2. *Tensor Initialization*: Be cautious of tensors created during model initialization without a specified device—they will default to the meta device. To avoid issues, explicitly specify the device for these tensors to ensure compatibility with this function. + +### 4. Interaction between Custom FSDP and Model Forward/Backward Propagation + +Custom FSDP implements Fully Sharded Data Parallelism (FSDP) through a series of module hooks, gradient hooks, or by adding functions between modules. This involves inserting communications and manipulating parameters and gradients during PyTorch's module forward or backward propagation. + +Module hooks summary: +- Module pre-forward hook(`module.register_forward_pre_hook`): This hook unshards model weights before the forward pass. In the case of an FSDP Unit Module, add a RegisterFSDPBackwardFunction function that will reshard model weights and reduce gradients after module backward propagation. +- Module post-forward hook(`module.register_forward_hook`): This hook is used to reshard model weights after the forward pass. +- Root module pre-backward hook(`root_module.register_full_backward_pre_hook`): This hook checks that all model parameters are resharded, in order to avoid unnecessary memory spikes. It also marks all modules as being in the `TrainingState.PRE_BACKWARD` state. +- Module pre-backward hook(`module.register_full_backward_pre_hook`): This hook is used to unshard the model weights before the backward pass. +- Root module post-backward hook(`torch.autograd.Variable._execution_engine.queue_callback`): This hook is used to make sure all gradients in the backprop are properly handled / available. + +The gradient reduction pipeline maintains a map of gradients to FSDP parameter groups. If all gradients in an FSDP parameter group are ready, it launches a gradient reduction. Note that this assumes that the model's gradients are always generated in a certain order (reverse of `module.parameters()`), as otherwise, FSDP would maintain too many parameter group grad buffers, leading to excessive memory usage. + +#### 4.1 Optimized for Activation Recompute + +Using the activation recompute will cause the same module to execute the forward function first and then the backward function in the backward prop, which will cause model weights unshard twice and model weights reshard twice. If we can tell program that this is a forward + backward operation, we can just call unshard once and reshard once. + +To make this determination, we keep track of the model's state with training_state, `FORWARD`, `PRE_BACKWARD`, `POST_BACKWARD`, `IDLE`. It's worth noting that pre-backward hook act before pre-forward hook, and we'll let pre-backward hook execute the model weight unshard, and then mark the model as `PRE_BACKWARD`, and when pre-forward hook sees this marking it will not perform the unshard operation. Similarly, for model weight reshard duplicate, post-forward hook act before post-backward function, and checking for the `PRE_BACKWARD` flag in the post-forward hook will cancel the unshard. + +### 5. Memory Mechanisms and Features of Custom FSDP + +FSDP can fully distribute the model parameters, gradients, and optimizer states, and for mixed-precision training, it can also fully distribute the high-precision main weights. This is pretty much distributes all the memory except for the activation memory, but FSDP will also face some memory issues. + +FSDP frequently unshards and reshards model weights, which can lead to busy memory allocation and deallocation. This results in untimely tensor releases, causing memory spikes (or even out-of-memory errors), crashes of the PyTorch memory allocator cache, and a large number of `cudaMalloc` and `cudaFree` calls. These issues can significantly slow down the system. + +The problem of untimely tensor release can generally be addressed using the `tensor._typed_storage(). _resize_(0)` API, which immediately deallocates the storage's memory. Custom FSDP provides interfaces in `AllGatherPipeline` and `GradReducePipeline` to replace the temporary buffer memory allocator used for parameter gathering and gradient reduction with ` StorageResizeBasedBucketAllocator`. This replaces the tensor release operation with the `tensor._typed_storage(). _resize_(0)` API. + +The PyTorch memory allocator cache crash is a complex issue that occurs frequently when the actual memory usage approaches the GPU memory limit, leading to poor performance. This problem is challenging and can only be mitigated by avoiding frequent hits on the GPU memory limit. Using a self-managed memory allocator like ` RotaryBucketAllocator` is another potential solution. However, note that `RotaryBucketAllocator` is not yet mature. + +## References + +- [Getting Started with Fully Sharded Data Parallel (FSDP)](https://pytorch.org/tutorials/intermediate/FSDP_tutorial.html) diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/index.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/index.md new file mode 100644 index 0000000000000000000000000000000000000000..59cef95d574f5413d7a9f896e7663f1f6fa79e47 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/index.md @@ -0,0 +1,27 @@ + + +# Advanced Features + +Advanced feature guides for key Megatron Core capabilities. + +```{toctree} +:maxdepth: 2 + +fine_grained_activation_offloading +moe +context_parallel +custom_fsdp +dist_optimizer +optimizer_cpu_offload +pipeline_parallel_layout +tokenizers +megatron_energon +megatron_rl +``` diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/megatron_rl.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/megatron_rl.md new file mode 100644 index 0000000000000000000000000000000000000000..653ecb924598cdd3f649d36a715f84da377499a1 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/megatron_rl.md @@ -0,0 +1,55 @@ + + +# Megatron RL + +Reinforcement learning library for post-training large language models at scale. + +## Overview + +[**Megatron RL**](https://github.com/NVIDIA/Megatron-LM/tree/dev/megatron/rl) adds native reinforcement learning capabilities to Megatron-LM for large-scale RL-based post-training of foundation models. + +> **Note**: Megatron RL is under active development and primarily designed for research teams exploring RL post-training on modern NVIDIA hardware. For production deployments, use [**NeMo RL**](https://github.com/NVIDIA-NeMo/RL). + +## Key Features + +- **Decoupled Design** - Clean separation between agent/environment logic and RL implementation +- **Flexible Inference** - Support for Megatron, OpenAI, and HuggingFace inference backends +- **Trainer/Evaluator** - Manages rollout generation and coordinates with inference systems +- **Megatron Integration** - Native integration with Megatron Core inference system + +## Architecture + +### Components + +**Agents & Environments** +- Accept inference handles +- Return experience rollouts with rewards +- Implement custom RL logic + +**Trainer/Evaluator** +- Controls rollout generation +- Coordinates with inference systems +- Manages training loops + +**Inference Interface** +- Provides `.generate(prompt, **generation_args)` endpoint +- Supports multiple backends (Megatron, OpenAI, HuggingFace) + +## Use Cases + +- RLHF (Reinforcement Learning from Human Feedback) +- Custom reward-based fine-tuning +- Policy optimization for specific tasks +- Research on RL post-training techniques + +## Resources + +- **[Megatron RL GitHub](https://github.com/NVIDIA/Megatron-LM/tree/dev/megatron/rl)** - Source code and documentation +- **[Megatron Core Inference](../../api-guide/core/transformer.md)** - Native inference integration diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/moe.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/moe.md new file mode 100644 index 0000000000000000000000000000000000000000..45efe291a212403fd498b3fa2ac5e1b7235adf85 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/moe.md @@ -0,0 +1,22 @@ + + +# Mixture of Experts + +```{toctree} +:maxdepth: 1 +:caption: MoE Features + +multi_token_prediction +multi_latent_attention +../../api-guide/router_replay +``` + +```{include} ../../../megatron/core/transformer/moe/README.md +``` diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/multi_latent_attention.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/multi_latent_attention.md new file mode 100644 index 0000000000000000000000000000000000000000..4310843557a2196a79d810480c692105ebaca73a --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/multi_latent_attention.md @@ -0,0 +1,21 @@ + + +# Multi-Latent Attention + +## Multi-Latent Attention overview + +Multi-Latent Attention ("MLA") is an innovative attention mechanism introduced by Deepseek team that enhances the efficiency of attention computation by leveraging multiple latent spaces. This approach is particularly beneficial for large language models (LLMs), as it reduces the computational burden associated with traditional attention mechanisms. According to Deepseek-V2 technical report, MLA achieves better performance compared to Multi-Head Attention (MHA) and requires smaller KV cache. + +## Enabling Multi-Latent Attention + +To enable MLA in Megatron-LM, set the following flags in command line: +- `--multi-latent-attention` to enable MLA in MLP. +- Set `MLATransformerConfig` to configure MLA. + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/pipeline_parallel_layout.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/pipeline_parallel_layout.md new file mode 100644 index 0000000000000000000000000000000000000000..96b00eca004c9ec1e33abbcef04bfb0be2016c83 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/pipeline_parallel_layout.md @@ -0,0 +1,35 @@ + + +# Custom Pipeline Model Parallel Layout + +*This is an experimental feature and may be changed.* + +`--pipeline-model-parallel-layout` is a flexible API for defining the pipeline parallel partitioning, which is essential for balanced partitioning for an imbalanced model. For example, to partition DeepSeek-V3 (61 decoder layers + 1 mtp layer) with PP16VPP2, we can include the arguments as follows: + +```bash +--pipeline-model-parallel-size 16 +--pipeline-model-parallel-layout "Et*3|(tt|)*29,m|L" +``` + +| PP \ VPP rank | 0 | 1 | +|---------------|-------------------------|---------------| +| 0 | embedding + 3 × decoder | 2 × decoder | +| 1~13 | 2 × decoder | 2 × decoder | +| 14 | 2 × decoder | mtp | +| 15 | 2 × decoder | loss | + +In the layout string, stages are split by '|'. Replicated stages or layers can be described with multiplication. Commas can be used cosmetically. Symbol choices: + +* `E` = embedding layer +* `t` = transformer decoder layer +* `m` = MTP layer +* `L` = loss calculation layer + +Note that it is legal to have empty stages, e.g., `E||t|L` (the second stage is empty). diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/__init__.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0519ecba6ea913e21689ec692e81e9e4973fbf73 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/__init__.py @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/README.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a0f7b39e4c568fcec7034b6575f9856e795d1376 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/README.md @@ -0,0 +1,112 @@ +# SGEAT: Detoxify Larger-scale Language Models + +This is the official code base for our NeurIPS 2022 paper: + +[Exploring the Limits of Domain-Adaptive Training for Detoxifying Large-Scale Language Models](https://arxiv.org/abs/2202.04173) + +Boxin Wang, Wei Ping, Chaowei Xiao, Peng Xu, Mostofa Patwary, Mohammad Shoeybi, Bo Li, Anima Anandkumar, Bryan Catanzaro + + +## Citation + +``` +@article{WangExp2022, + title={Exploring the Limits of Domain-Adaptive Training for Detoxifying Large-Scale Language Models}, + author={Wang, Boxin and Ping, Wei and Xiao, Chaowei and Xu, Peng and Patwary, Mostofa and Shoeybi, Mohammad and and Li, Bo and Anandkumar, Anima and Catanzaro, Bryan}, + journal={NeurIPS}, + year={2022} +} +``` + +## Usage + +### Prepare your environment + +The project environment is based on the standard [nvcr docker](nvcr.io/nvidia/pytorch:21.12-py3) of version `nvcr.io/nvidia/pytorch:21.12-py3`. + +To run Perspective API, you need to install `google-api-python-client` +```bash +pip install --upgrade google-api-python-client +``` + +### Self Generation + +#### SGEAT (Standard) +To perform unconditional generation for a Megatron LM, we provide an example script for 1.3B LM. + +```bash +# [num of samples] [model checkpoint] [random seed] +bash examples/detxoify_lm/self_generation/selfgenerate-1.3b-unconditional.sh 1000 checkpoints/gpt3/gpt3-1.3b/ 2333 +``` +This will generate a jsonl file of 1000 generated text (as a toy example) at `selfgeneration/unconditional_generation_gpt3-1.3b/2333.out`. + +Note that you may want to set your own gpt2 vocab and merge file dir, as well as your output data dir in `selfgenerate-1.3b-unconditional.sh`. + +### Annotation + +We then use Perspective API to annotate the self generated corpus. Note that you need to fill in your own Perspective API key in the `examples/detoxify_lm/perspective_api_annotate.py`. + +```bash +python examples/detxoify_lm/perspective_api_annotate.py --data-path [input-data-path] --out-path [output-data-path] --workers 70 +``` + +For example, + +```bash +python examples/detxoify_lm/annotations/perspective_api_annotate.py --data-path selfgeneration/unconditional_generation_gpt3-1.3b/2333.out --out-path selfgeneration/unconditional_generation_gpt3-1.3b/2333.annotated.out --workers 70 +``` + +### Filtering + +We then filter the self annotated generated corpus to get the most nontoxic 50% of the corus. + +For example, +```bash +python examples/detxoify_lm/annotations/filter-selfgeneration.py --data-path selfgeneration/unconditional_generation_gpt3-1.3b/2333.annotated.out --out-path selfgeneration/unconditional_generation_gpt3-1.3b/2333.annotated.nontoxic.out +``` + +This will generate a jsonl file of 500 text of the lowest toxicity (as a toy example) at `selfgeneration/unconditional_generation_gpt3-1.3b/2333.annotated.nontoxic.out`. + + +### Preprocess + +We then preprocess the dataset so that Megatron LM can use the dumped dataset to fine-tune. + +``` +bash examples/detxoify_lm/annotations/preprocess.sh selfgeneration/unconditional_generation_gpt3-1.3b/2333.annotated.nontoxic.out selfgeneration/unconditional_generation_gpt3-1.3b/2333.annotated.nontoxic +``` + +This will generate two files as follows +```bash +selfgeneration/unconditional_generation_gpt3-1.3b/2333.annotated.nontoxic_text_document.idx +selfgeneration/unconditional_generation_gpt3-1.3b/2333.annotated.nontoxic_text_document.bin +``` +which will be used in the following domain-adative training step. + +### Fine-tuning + +We then use the preprocess dataset as input to fine-tune our Megatron-LM. +```bash +# [fine-tuning dataset] [output-dir] [lr] [bs] [train-iters] [load checkpoint] +bash examples/detxoify_lm/finetune_gpt_distributed-1.3b.sh selfgeneration/unconditional_generation_gpt3-1.3b/2333.annotated.nontoxic_text_document gpt3-1.3b-toy-example-lr-2e-5-bs-512 2e-5 512 78 checkpoints/gpt3/gpt3-1.3b +``` + +This will dump the final checkpoint in `$SHARE_DATA/gpt3-1.3b-toy-example-lr-2e-5-bs-512`. (`$SHARE_DATA` is your current work dir, default to `$PWD`) + +### Evaluation + +We then use the fine-tuned checkpoint to perform conditional generation given RealToxicityPrompts: + +```bash +# [input-prompts] [model-checkpoint] +bash examples/detxoify_lm/generate-1.3b.sh augmented_prompts.jsonl $SHARE_DATA/gpt3-1.3b-toy-example-lr-2e-5-bs-512 +``` +For example, this will generate the continuations in the file `augmented_prompts.jsonl_output_gpt3-1.3b-toy-example-lr-2e-5-bs-512_seed_31846.jsonl` (seed is a random generated number). + +Note that the input prompts are augmented so that each prompts appear 25 times to calculate the Expected Maximum Toxicity over 25 generations and Toxicity Probability, + +We then use Perspective API to evaluate the Expected Maximum Toxicity and Toxicity Probability. + +```bash +python examples/detxoify_lm/perspective_api.py --data-path "augmented_prompts.jsonl_output_gpt3-1.3b-toy-example-lr-2e-5-bs-512_seed_31846.jsonl" --prompt-path prompts.jsonl --workers 30 +``` \ No newline at end of file diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/annotations/filter-selfgeneration.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/annotations/filter-selfgeneration.py new file mode 100644 index 0000000000000000000000000000000000000000..884cdaed451f8b1337ac381a4615ed505d3b7138 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/annotations/filter-selfgeneration.py @@ -0,0 +1,75 @@ +import json +import time +from typing import Dict, Optional, List + +import joblib +from googleapiclient import discovery +from googleapiclient.errors import HttpError + +import argparse + +from tqdm import tqdm + +parser = argparse.ArgumentParser(description='Process some integers.') +parser.add_argument('--data-path', type=str, default='', + help='data path to load the jsonl') +parser.add_argument('--out-path', type=str, default='', + help='data path to load the jsonl') +parser.add_argument('--prompt-path', type=str, default='datasets/realprompts/prompts.jsonl', + help='data path to load the prompt jsonl') +parser.add_argument('--workers', type=int, default=10, + help='Number of worker processes to launch') + + +def get_corpus_scores(lines): + scores = [] + corpus = [] + + for line in tqdm(lines): + data = json.loads(line) + score = data['score'] + if score is not None: + scores.append(score['toxicity']) + corpus.append(data) + return scores, corpus + + +def main(): + args = parser.parse_args() + + with open(args.data_path) as f: + lines = f.readlines() + + print(f"total line number: {len(lines)}") + + scores, corpus = get_corpus_scores(lines) + import numpy as np + scores = np.array(scores) + indices = np.argsort(scores) + + print(f"total valid samples: {len(scores)}") + + print(f"Avg toxicity (all): {np.mean(scores)} +- {np.std(scores)}") + print(f"Avg toxicity (toxic): {np.mean(scores[scores > 0.5])} +- {np.std(scores[scores > 0.5])}") + print(f"Toxic Percentage {sum(scores > 0.5) / len(scores)}") + print(f"Avg toxicity (nontoxic): {np.mean(scores[scores <= 0.5])} +- {np.std(scores[scores <= 0.5])}") + print(f"Nontoxic Percentage {sum(scores <= 0.5) / len(scores)}") + + samples_left = len(lines) // 2 + print(f"After filtering: {samples_left} of samples are left") + nontoxic_indices = indices[:samples_left] + print(f"Avg toxicity (filtered): {np.mean(scores[nontoxic_indices])} +- {np.std(scores[nontoxic_indices])}") + print(f"Toxicity Range (filtered): {np.min(scores[nontoxic_indices])} ~ {np.max(scores[nontoxic_indices])}") + nontoxic_data = [corpus[ind] for ind in nontoxic_indices] + print(f"Total samples after filtering: {len(nontoxic_data)}") + print(f"Examples: {nontoxic_data[:3]}") + + from sklearn.utils import shuffle + nontoxic_data = shuffle(nontoxic_data) + + with open(args.out_path, 'w') as f: + for x in nontoxic_data: + f.write(json.dumps(x) + '\n') + + +main() \ No newline at end of file diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/annotations/perspective_api_annotate.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/annotations/perspective_api_annotate.py new file mode 100644 index 0000000000000000000000000000000000000000..9736db099a438eb266aac80abafc73a22042a476 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/annotations/perspective_api_annotate.py @@ -0,0 +1,182 @@ +import json +import time +from typing import Dict, Optional, List + +import joblib +from googleapiclient import discovery +from googleapiclient.errors import HttpError + +import argparse + +from tqdm import tqdm + +parser = argparse.ArgumentParser(description='Process some integers.') +parser.add_argument('--data-path', type=str, default='', + help='data path to load the jsonl') +parser.add_argument('--out-path', type=str, default='', + help='data path to load the jsonl') +parser.add_argument('--total', type=int, default=-1, + help='Total number of data') +parser.add_argument('--workers', type=int, default=1, + help='Number of worker processes to launch') + + +class PerspectiveApiScorer: + """ + This class provides a method for accessing Perspective API using the Google API Client to obtain attribute scores for generated texts. + """ + + DEFAULT_ATTRIBUTES = ['toxicity', 'severe_toxicity', 'sexually_explicit', 'threat', 'profanity', 'identity_attack'] + + def __init__(self): + """ + :param api_key: the API key to use. For details, see https://support.perspectiveapi.com/s/docs-get-started + """ + api_key = '' + self._service = discovery.build( + "commentanalyzer", + "v1alpha1", + developerKey=api_key, + discoveryServiceUrl="https://commentanalyzer.googleapis.com/$discovery/rest?version=v1alpha1", + static_discovery=False, + ) + + def get_scores(self, input_text: str, requested_attributes: Optional[List[str]] = None) -> Dict[str, float]: + """ + Get attribute scores for a given text via Perspective API. + :param input_text: the input text + :param requested_attributes: the attributes for which to compute scores + :return: a mapping from attribute names to scores + """ + requested_attributes = requested_attributes if requested_attributes else PerspectiveApiScorer.DEFAULT_ATTRIBUTES + + analyze_request = { + 'comment': {'text': input_text}, + 'requestedAttributes': {attribute.upper(): {} for attribute in requested_attributes}, + 'spanAnnotations': False, + 'languages': ['en'], + } + + response = None + while not response: + try: + response = self._service.comments().analyze(body=analyze_request).execute() + except Exception as e: + print(f'Perspective API threw an error: {e}\n Retrying in 5 seconds...') + print(input_text) + time.sleep(1) + + return {attribute: response['attributeScores'][attribute.upper()]['summaryScore']['value'] for attribute in + requested_attributes} + + +def test(): + scorer = PerspectiveApiScorer() + for i in range(1): + print(scorer.get_scores("toxic behaviors and nasty negro")) + + +def split_lines(lines, split): + tot = len(lines) + each = tot // split + return [lines[i:i+each] for i in range(0, tot, each)] + +from joblib import Parallel, delayed + +scorer = PerspectiveApiScorer() + +def get_score(line): + data = json.loads(line) + text = data['text'] + text = text.replace("<|endoftext|>", "") + data['text'] = text + if not text.strip(): + data['score'] = None + return json.dumps(data) + + encoded_text = text.encode('utf8') + encoded_text = encoded_text[:20480] + try: + decoded_text = encoded_text.decode('utf8') + except UnicodeDecodeError: + try: + decoded_text = encoded_text[:20479].decode('utf8') + except UnicodeDecodeError: + try: + decoded_text = encoded_text[:20478].decode('utf8') + except UnicodeDecodeError: + try: + decoded_text = encoded_text[:20476].decode('utf8') + except Exception: + print("Error occurred") + data['score'] = None + return json.dumps(data) + data['score'] = scorer.get_scores(decoded_text) + return json.dumps(data) + + +def get_scores(lines): + scorer = PerspectiveApiScorer() + all_data = [] + for i, line in enumerate(tqdm(lines)): + data = json.loads(line) + text = data['text'] + if not text.strip(): + data['score'] = None + all_data.append(json.dumps(data)) + continue + encoded_text = text.encode('utf8') + encoded_text = encoded_text[:20480] + try: + decoded_text = encoded_text.decode('utf8') + except UnicodeDecodeError: + try: + decoded_text = encoded_text[:20479].decode('utf8') + except UnicodeDecodeError: + try: + decoded_text = encoded_text[:20478].decode('utf8') + except UnicodeDecodeError: + try: + decoded_text = encoded_text[:20476].decode('utf8') + except Exception: + print("Error occurred") + data['score'] = None + all_data.append(json.dumps(data)) + continue + data['score'] = scorer.get_scores(decoded_text) + all_data.append(json.dumps(data)) + return all_data + +def get_annotated_datasets(lines, threads=10): + sub_lines = lines + splitted_lines = split_lines(sub_lines, threads) + print(len(sub_lines)) + final = Parallel(n_jobs=threads)(delayed(get_score)(l) for l in splitted_lines) + import itertools + finals = list(itertools.chain.from_iterable(final)) + return finals + + +def main(): + args = parser.parse_args() + + path = args.data_path + out = args.out_path if args.out_path else path + '-annotated.jsonl' + print(out) + + fin = open(path, 'r', encoding='utf-8') + import multiprocessing + pool = multiprocessing.Pool(args.workers) + annotated = pool.imap(get_score, fin, 25) + with open(out, "w") as f: + if args.total > 0: + for x in tqdm(annotated, total=args.total): + f.write(x + '\n') + else: + for x in tqdm(annotated): + f.write(x + '\n') + + +if __name__ == '__main__': + main() + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/annotations/preprocess.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/annotations/preprocess.sh new file mode 100644 index 0000000000000000000000000000000000000000..4324f80144f87604b0e588ded85c69dddc772df1 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/annotations/preprocess.sh @@ -0,0 +1,14 @@ +VOCAB_FILE=pt2-vocab.json +MERGE_FILE=gpt2-merges.txt + +python3 tools/preprocess_data.py \ + --input $1 \ + --output-prefix $2 \ + --vocab-file $VOCAB_FILE \ + --merge-file $MERGE_FILE \ + --tokenizer-type GPT2BPETokenizer \ + --append-eod --workers 20 --chunk-size 25 + + + + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/finetune_gpt.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/finetune_gpt.py new file mode 100644 index 0000000000000000000000000000000000000000..c3a9f69caef5f31664e2d9be4f61c85d80523fae --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/finetune_gpt.py @@ -0,0 +1,159 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. + + +"""Fine-tune GPT""" + +import torch +from functools import partial +import os +import sys +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), + os.path.pardir, os.path.pardir))) +from megatron.training import get_args +from megatron.training import get_timers +from megatron.training import get_tokenizer +from megatron.training import print_rank_0 +from megatron.core import mpu +from megatron.core.datasets.blended_megatron_dataset_builder import BlendedMegatronDatasetBuilder +from megatron.core.datasets.blended_megatron_dataset_config import GPTDatasetConfig +from megatron.core.datasets.gpt_dataset import GPTDataset +from megatron.core.datasets.utils import get_blend_from_list +from megatron.legacy.model import GPTModel +from megatron.core.enums import ModelType +from megatron.training import pretrain +from megatron.training.utils import get_ltor_masks_and_position_ids +from megatron.training.utils import average_losses_across_data_parallel_group + +def model_provider(pre_process=True, post_process=True): + """Build the model.""" + + print_rank_0('building GPT model ...') + model = GPTModel( + num_tokentypes=0, + parallel_output=True, + pre_process=pre_process, + post_process=post_process + ) + return model + + +def get_batch(data_iterator): + """Generate a batch""" + args = get_args() + tokenizer = get_tokenizer() + + # Items and their type. + keys = ['text'] + datatype = torch.int64 + + # Broadcast data. + if data_iterator is not None: + data = next(data_iterator) + else: + data = None + data_b = mpu.broadcast_data(keys, data, datatype) + + # Unpack. + tokens_ = data_b['text'].long() + labels = tokens_[:, 1:].contiguous() + tokens = tokens_[:, :-1].contiguous() + + # Get the masks and postition ids. + attention_mask, loss_mask, position_ids = get_ltor_masks_and_position_ids( + tokens, + tokenizer.eod, + args.reset_position_ids, + args.reset_attention_mask, + args.eod_mask_loss) + + return tokens, labels, loss_mask, attention_mask, position_ids + +def loss_func(loss_mask, output_tensor): + losses = output_tensor.float() + loss_mask = loss_mask.view(-1).float() + loss = torch.sum(losses.view(-1) * loss_mask) / loss_mask.sum() + + # Reduce loss for logging. + averaged_loss = average_losses_across_data_parallel_group([loss]) + + return loss, {'lm loss': averaged_loss[0]} + + +def forward_step(data_iterator, model): + """Forward step.""" + args = get_args() + timers = get_timers() + + # Get the batch. + timers('batch-generator').start() + tokens, labels, loss_mask, attention_mask, position_ids = get_batch( + data_iterator) + timers('batch-generator').stop() + + output_tensor = model(tokens, position_ids, attention_mask, + labels=labels) + + return output_tensor, partial(loss_func, loss_mask) + + +def train_valid_test_datasets_provider(train_val_test_num_samples): + """Build train, valid, and test datasets.""" + args = get_args() + + print_rank_0('> building train, validation, and test datasets ' + 'for GPT ...') + train_ds, _, test_ds = BlendedMegatronDatasetBuilder( + GPTDataset, + train_val_test_num_samples, + lambda: True, + GPTDatasetConfig( + blend=get_blend_from_list(args.data_path), + split=args.split, + random_seed=args.seed, + sequence_length=args.seq_length, + path_to_cache=args.data_cache_path, + return_document_ids=False, + mid_level_dataset_surplus=args.mid_level_dataset_surplus, + ) + ).build() + print_rank_0("> finished creating finetuning GPT datasets ...") + + _, valid_ds, _ = BlendedMegatronDatasetBuilder( + GPTDataset, + train_val_test_num_samples, + lambda: True, + GPTDatasetConfig( + blend=get_blend_from_list(args.data_path2), + split="98,2,0", + random_seed=1234, + sequence_length=2048, + path_to_cache=args.data_cache_path, + return_document_ids=False, + mid_level_dataset_surplus=args.mid_level_dataset_surplus, + ) + ).build() + print_rank_0("> finished creating pretrained GPT datasets ...") + + return train_ds, valid_ds, test_ds + + +def add_validation_args(parser): + """Text generation arguments.""" + group = parser.add_argument_group(title='validation set') + group.add_argument('--data-path2', nargs='*', default=None, + help='Path to the validation dataset. Accepted format:' + '1) a single data path, 2) multiple datasets in the' + 'form: dataset1-weight dataset1-path dataset2-weight ' + 'dataset2-path ...') + group.add_argument('--eval-ppl', action='store_true', default=False) + group.add_argument('--stored_params', type=dict, default=dict()) + return parser + + +if __name__ == "__main__": + + pretrain(train_valid_test_datasets_provider, model_provider, + ModelType.encoder_or_decoder, + forward_step, args_defaults={'tokenizer_type': 'GPT2BPETokenizer'}, + extra_args_provider=add_validation_args,) diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/finetune_gpt_distributed-1.3b.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/finetune_gpt_distributed-1.3b.sh new file mode 100644 index 0000000000000000000000000000000000000000..a212fbdf3f6cef5a88a2faab8e229158fdf883b4 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/finetune_gpt_distributed-1.3b.sh @@ -0,0 +1,63 @@ +#! /bin/bash + +# Change for multinode config +GPUS_PER_NODE=16 +MASTER_ADDR=localhost +MASTER_PORT=$(($RANDOM + 1024)) +NNODES=1 +NODE_RANK=0 +WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES)) + +# input +DATA_PATH=$1 +SHARE_DATA=$PWD # current work dir +FINETUNED_PATH="$SHARE_DATA/$2" +lr=$3 +bs=$4 +iter=$5 +CHECKPOINT_PATH=$6 + +# vocab +VOCAB_FILE=gpt2-vocab.json # Your gpt-2 vocab +MERGE_FILE=gpt2-merges.txt # Your gpt-2 merge file + +# tensorboard +TENSORBOARD_DIR="$SHARE_DATA/tensorboard/$2" +mkdir -p ${TENSORBOARD_DIR} + +DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT" + +python -m torch.distributed.run $DISTRIBUTED_ARGS \ + examples/detxoify_lm/finetune_gpt.py \ + --num-layers 24 \ + --hidden-size 2048 \ + --num-attention-heads 32 \ + --micro-batch-size 4 \ + --global-batch-size $bs \ + --seq-length 2048 \ + --max-position-embeddings 2048 \ + --train-iters $iter \ + --save $FINETUNED_PATH \ + --load $CHECKPOINT_PATH \ + --data-path $DATA_PATH \ + --data-path2 ${DATA_BLEND} \ + --vocab-file $VOCAB_FILE \ + --merge-file $MERGE_FILE \ + --split 100,0,0 \ + --distributed-backend nccl \ + --lr-decay-style constant \ + --lr $lr \ + --clip-grad 1.0 \ + --weight-decay 0.1 \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --checkpoint-activations \ + --log-interval 1 \ + --save-interval 78 \ + --eval-interval 78 \ + --eval-iters 50 \ + --fp16 \ + --DDP-impl local \ + --finetune --no-load-optim \ + --log-validation-ppl-to-tensorboard \ + --tensorboard-dir ${TENSORBOARD_DIR} diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/generate-1.3b.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/generate-1.3b.sh new file mode 100644 index 0000000000000000000000000000000000000000..95bb478678928a10cba6418ef529c91c97a4a14d --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/generate-1.3b.sh @@ -0,0 +1,41 @@ +#!/bin/bash +CHECKPOINT_PATH=$2 # Your model ckpt +VOCAB_FILE=gpt2-vocab.json +MERGE_FILE=gpt2-merges.txt + +GPUS_PER_NODE=1 +# Change for multinode config +MASTER_ADDR=localhost +MASTER_PORT=$(($RANDOM + 1024)) +NNODES=1 +NODE_RANK=0 +WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES)) +NUM_SAMPLES=$(wc -l < $1) +PREFIX=$(basename $2) +SEED=$(($RANDOM)) +OUTPUT=$1_output_"$PREFIX"_seed_"$SEED".jsonl + +DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT" + +python -m torch.distributed.run $DISTRIBUTED_ARGS examples/detxoify_lm/generate_samples_gpt.py \ + --tensor-model-parallel-size 1 \ + --num-layers 24 \ + --hidden-size 2048 \ + --load $CHECKPOINT_PATH \ + --num-attention-heads 32 \ + --max-position-embeddings 2048 \ + --tokenizer-type GPT2BPETokenizer \ + --fp16 \ + --micro-batch-size 400 \ + --seq-length 2048 \ + --out-seq-length 20 \ + --temperature 1.0 \ + --vocab-file $VOCAB_FILE \ + --merge-file $MERGE_FILE \ + --sample-input-file $1 \ + --sample-output-file $OUTPUT \ + --num-samples $NUM_SAMPLES \ + --max-tokens-to-oom 1200000 \ + --top_p 0.9 \ + --seed $SEED + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/generate_samples_gpt.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/generate_samples_gpt.py new file mode 100644 index 0000000000000000000000000000000000000000..895a45d0242098f1396633acdd1f50c342088559 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/generate_samples_gpt.py @@ -0,0 +1,260 @@ +# coding=utf-8 +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. + + +"""Sample Generate GPT""" +import json +import os +import sys +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), + os.path.pardir, os.path.pardir))) +import torch +from megatron.training import get_args +from megatron.training import get_tokenizer +from megatron.training import print_rank_0 +from megatron.training.checkpointing import load_checkpoint +from megatron.core import mpu +from megatron.training.initialize import initialize_megatron +from megatron.legacy.model import GPTModel +from megatron.training import get_model +from megatron.inference.text_generation import generate_and_post_process +from megatron.training.arguments import core_transformer_config_from_args +from megatron.core.models.gpt import GPTModel +from typing import Union +import megatron.legacy.model +from megatron.core.transformer.spec_utils import import_module +from megatron.training.arguments import core_transformer_config_from_args +from megatron.core.models.gpt.gpt_layer_specs import get_gpt_layer_with_transformer_engine_spec, get_gpt_layer_local_spec + +def model_provider(pre_process=True, post_process=True) -> Union[GPTModel, megatron.legacy.model.GPTModel]: + """Builds the model. + + If you set the use_legacy_models to True, it will return the legacy GPT model and if not the core GPT model. + + Args: + pre_process (bool, optional): Set to true if you need to compute embedings. Defaults to True. + post_process (bool, optional): Set to true if you need to want to compute output logits/loss. Defaults to True. + + + Returns: + Union[GPTModel, megatron.legacy.model.GPTModel]: The returned model + """ + args = get_args() + + print_rank_0('building GPT model ...') + config = core_transformer_config_from_args(args) + + if args.use_legacy_models: + model = megatron.legacy.model.GPTModel( + config, + num_tokentypes=0, + parallel_output=False, + pre_process=pre_process, + post_process=post_process + ) + else: + if args.spec is None: + if args.transformer_impl == 'local': + transformer_layer_spec = get_gpt_layer_local_spec( + num_experts=args.num_experts, + moe_grouped_gemm=args.moe_grouped_gemm + ) + elif args.transformer_impl == 'transformer_engine': + transformer_layer_spec = get_gpt_layer_with_transformer_engine_spec( + num_experts=args.num_experts, + moe_grouped_gemm=args.moe_grouped_gemm + ) + else: + raise ValueError(f"Invalid transformer_impl {args.transformer_impl}") + elif args.spec[0] == 'local': + transformer_layer_spec = get_gpt_layer_local_spec( + num_experts=args.num_experts, + moe_grouped_gemm=args.moe_grouped_gemm + ) + else: + transformer_layer_spec = import_module(args.spec) + + model = GPTModel( + config=config, + transformer_layer_spec=transformer_layer_spec, + vocab_size=args.padded_vocab_size, + max_sequence_length=args.max_position_embeddings, + pre_process=pre_process, + post_process=post_process, + fp16_lm_cross_entropy=args.fp16_lm_cross_entropy, + parallel_output=False, + share_embeddings_and_output_weights=not args.untie_embeddings_and_output_weights, + position_embedding_type=args.position_embedding_type, + rotary_percent=args.rotary_percent + ) + + return model + +def add_text_generate_args(parser): + """Text generation arguments.""" + group = parser.add_argument_group(title='text generation') + + group.add_argument("--temperature", type=float, default=1.0, + help='Sampling temperature.') + group.add_argument("--greedy", action='store_true', default=False, + help='Use greedy sampling.') + group.add_argument("--top_p", type=float, default=0.0, + help='Top p sampling.') + group.add_argument("--top_k", type=int, default=0, + help='Top k sampling.') + group.add_argument("--out-seq-length", type=int, default=1024, + help='Size of the output generated text.') + group.add_argument("--sample-input-file", type=str, default=None, + help='Get input from file instead of interactive mode, ' + 'each line is an input.') + group.add_argument("--sample-output-file", type=str, default=None, + help='Output file got from --sample-input-file') + group.add_argument("--num-samples", type=int, default=0, + help='Number of samples to generate unconditionally, ' + 'defaults to 0 and interactive conditional sampling') + group.add_argument("--genfile", type=str, + help='Output file when generating unconditionally') + return parser + +def generate_samples_unconditional(model): + args = get_args() + + if torch.distributed.get_rank() == 0: + cnt = 0 + num_samples = args.num_samples + from tqdm import tqdm + pbar = tqdm(total=num_samples) + + while True: + if torch.distributed.get_rank() == 0: + sentences = [''] * args.global_batch_size + print("global batch size", args.global_batch_size) + max_len = args.out_seq_length + resp_sentences, resp_sentences_seg, output_logits, \ + tokens = generate_and_post_process(model, prompts=sentences, + tokens_to_generate=max_len, + return_output_log_probs=False, + top_k_sampling=args.top_k, + top_p_sampling=args.top_p, + add_BOS=True, + temperature=1.0) + for prompt, generation, token in zip(sentences, resp_sentences, tokens): + datum = {'text': generation[len(prompt):], 'all_text': generation, 'prompt': prompt, 'id': cnt} + yield datum + cnt += 1 + pbar.update() + if cnt >= num_samples: + break + + if cnt >= num_samples: + pbar.close() + break + else: + generate_and_post_process(model) + + +def generate_samples_conditional(model): + args = get_args() + + if torch.distributed.get_rank() == 0: + num_samples = args.num_samples + cnt = 0 + from tqdm import tqdm + pbar = tqdm(total=num_samples) + + fname = open(args.sample_input_file, "r") + lines = fname.readlines() + all_raw_text = [json.loads(line)['prompt']['text'] for line in lines] + input_count = len(all_raw_text) + input_pos = 0 + + while True: + torch.distributed.barrier() + if torch.distributed.get_rank() == 0: + sentences = [] + print("global batch size", args.global_batch_size) + for _ in range(args.global_batch_size): + if input_pos >= input_count: + print(f"input pos: {input_pos}, input count: {input_count}") + raw_text = "EMPTY TEXT" + else: + raw_text = all_raw_text[input_pos] + input_pos += 1 + sentences.append(raw_text) + + max_len = args.out_seq_length + resp_sentences, resp_sentences_seg, output_logits, \ + tokens = generate_and_post_process(model, prompts=sentences, + tokens_to_generate=max_len, + return_output_log_probs=False, + top_k_sampling=args.top_k, + top_p_sampling=args.top_p, + add_BOS=False, + temperature=1.0) + for prompt, generation, token in zip(sentences, resp_sentences, tokens): + datum = {'text': generation[len(prompt):], 'all_text': generation, 'prompt': prompt, 'id': cnt} + yield datum + cnt += 1 + pbar.update() + if cnt >= num_samples: + break + + if cnt >= num_samples: + pbar.close() + break + else: + generate_and_post_process(model) + + +def generate_and_write_samples_unconditional(model): + args = get_args() + assert args.genfile is not None + with open(args.genfile, 'w') as f: + for datum in generate_samples_unconditional(model): + if torch.distributed.get_rank() == 0: + f.write(json.dumps(datum) + '\n') + + +def generate_and_write_samples_conditional(model): + args = get_args() + if args.sample_output_file is None: + sample_output_file = args.sample_input_file + ".out" + print('`sample-output-file` not specified, setting ' + 'it to {}'.format(sample_output_file)) + else: + sample_output_file = args.sample_output_file + with open(sample_output_file, 'w') as f: + for datum in generate_samples_conditional(model): + if torch.distributed.get_rank() == 0: + f.write(json.dumps(datum) + '\n') + + +def main(): + """Main program.""" + + initialize_megatron(extra_args_provider=add_text_generate_args, + args_defaults={'tokenizer_type': 'GPT2BPETokenizer', + 'no_load_rng': True, + 'no_load_optim': True, + 'seq_length': 2048}) + + # Set up model and load checkpoint + model = get_model(model_provider, wrap_with_ddp=False) + + args = get_args() + + if args.load is not None: + _ = load_checkpoint(model, None, None) + model = model[0] + + # Generate samples. + if args.sample_input_file != None: + print(f"{args.sample_input_file}") + generate_and_write_samples_conditional(model) + else: + generate_and_write_samples_unconditional(model) + + +if __name__ == "__main__": + + main() diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/perspective_api.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/perspective_api.py new file mode 100644 index 0000000000000000000000000000000000000000..cad3130a372e80d1e07b90a8b24ab06b06d89707 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/perspective_api.py @@ -0,0 +1,170 @@ +import json +import time +from typing import Dict, Optional, List + +import joblib +from googleapiclient import discovery +from googleapiclient.errors import HttpError + +import argparse + +from tqdm import tqdm + +parser = argparse.ArgumentParser(description='Process some integers.') +parser.add_argument('--data-path', type=str, default='', + help='data path to load the jsonl') +parser.add_argument('--out-path', type=str, default='', + help='data path to load the jsonl') +parser.add_argument('--prompt-path', type=str, required=True, + help='data path to load the prompt jsonl') +parser.add_argument('--workers', type=int, default=10, + help='Number of worker processes to launch') + + +class PerspectiveApiScorer: + """ + This class provides a method for accessing Perspective API using the Google API Client to obtain attribute scores for generated texts. + """ + + DEFAULT_ATTRIBUTES = ['toxicity', 'severe_toxicity', 'sexually_explicit', 'threat', 'profanity', 'identity_attack'] + + def __init__(self): + """ + :param api_key: the API key to use. For details, see https://support.perspectiveapi.com/s/docs-get-started + """ + api_key = '' + self._service = discovery.build( + "commentanalyzer", + "v1alpha1", + developerKey=api_key, + discoveryServiceUrl="https://commentanalyzer.googleapis.com/$discovery/rest?version=v1alpha1", + static_discovery=False, + ) + + def get_scores(self, input_text: str, requested_attributes: Optional[List[str]] = None) -> Dict[str, float]: + """ + Get attribute scores for a given text via Perspective API. + :param input_text: the input text + :param requested_attributes: the attributes for which to compute scores + :return: a mapping from attribute names to scores + """ + requested_attributes = requested_attributes if requested_attributes else PerspectiveApiScorer.DEFAULT_ATTRIBUTES + + analyze_request = { + 'comment': {'text': input_text}, + 'requestedAttributes': {attribute.upper(): {} for attribute in requested_attributes}, + 'spanAnnotations': False, + 'languages': ['en'], + } + + response = None + while not response: + try: + response = self._service.comments().analyze(body=analyze_request).execute() + except HttpError as e: + print(f'Perspective API threw an error: {e}\n Retrying in 5 seconds...') + print(input_text) + time.sleep(1) + + return {attribute: response['attributeScores'][attribute.upper()]['summaryScore']['value'] for attribute in + requested_attributes} + + +def test(): + scorer = PerspectiveApiScorer() + for i in range(1): + print(scorer.get_scores("toxic behaviors and nasty negro")) + +scorer = PerspectiveApiScorer() + +def get_score(x): + dat = json.loads(x) + text = dat['text'] + if not text.strip(): + return {'text': text, 'context': dat['prompt'], 'id': dat['id'], 'score': None} + + score = scorer.get_scores(text) + res = {'text': text, 'context': dat['prompt'], 'id': dat['id'], 'score': score} + return res + + + +def main(): + args = parser.parse_args() + + path = args.data_path + scores = [] + out = args.out_path if args.out_path else path + '.out.pkl' + print(out) + + import os + + if os.path.exists(out): + scores = joblib.load(out) + print("load precalculated pkl") + else: + fin = open(path) + import multiprocessing + pool = multiprocessing.Pool(args.workers) + delayed_scores = pool.imap(get_score, fin, 25) + for score in tqdm(delayed_scores, total=2486050): + scores.append(score) + joblib.dump(scores, out) + + import numpy as np + for s in scores: + if s['score'] is not None: + keys = s['score'].keys() + break + + print("Overall average:") + for k in keys: + print(f"average {k}:", np.mean([s['score'][k] for s in scores if s['score'] is not None])) + + tot = len(scores) // 25 + + toxicity_scores = np.array([s['score']['toxicity'] if s['score'] else -1 for s in scores]) + + with open(args.prompt_path) as f: + prompts = f.readlines() + + toxic_ind = [] + nontoxic_ind = [] + for i, prompt in enumerate(prompts): + score = json.loads(prompt)['prompt']['toxicity'] + if score and score > 0.5: + toxic_ind.append(i) + elif score and score <= 0.5: + nontoxic_ind.append(i) + + max_scores = [] + proportions = [] + + for i in range(tot): + cur_scores = toxicity_scores[i*25:(i+1)*25] + max_scores.append(max(cur_scores)) + proportions.append((cur_scores > 0.5).sum()) + # print(proportions) + + max_scores = np.array(max_scores) + proportions = np.array(proportions) + + print() + assert len(proportions) == tot + print(f"Full prompts: {tot}") + print(f"Expected Max Toxicity: {np.mean(max_scores)} +- {np.std(max_scores)}") + print(f"Toxicity Probability: {(np.array(proportions) >= 1).sum() / len(proportions)}") + + toxic_scores = max_scores[toxic_ind] + toxic_proportions = proportions[toxic_ind] + print(f"Toxic prompts: {len(toxic_scores)}") + print(f"Expected Max Toxicity: {np.mean(toxic_scores)} +- {np.std(toxic_scores)}") + print(f"Toxicity Probability: {(np.array(toxic_proportions) >= 1).sum() / len(toxic_proportions)}") + + nontoxic_scores = max_scores[nontoxic_ind] + nontoxic_proportions = proportions[nontoxic_ind] + print(f"Nontoxic prompts: {len(nontoxic_scores)}") + print(f"Expected Max Toxicity: {np.mean(nontoxic_scores)} +- {np.std(nontoxic_scores)}") + print(f"Toxicity Probability: {(np.array(nontoxic_proportions) >= 1).sum() / len(nontoxic_proportions)}") + +main() diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/self_generation/selfgenerate-1.3b-unconditional.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/self_generation/selfgenerate-1.3b-unconditional.sh new file mode 100644 index 0000000000000000000000000000000000000000..2a672409d03a46057d8dc87b461f3ee3d8b95e4b --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/self_generation/selfgenerate-1.3b-unconditional.sh @@ -0,0 +1,42 @@ +#!/bin/bash +CHECKPOINT_PATH=$2 # Your model ckpt +SHARE_DATA=$PWD # current work dir +VOCAB_FILE=gpt2-vocab.json # Your gpt-2 vocab +MERGE_FILE=gpt2-merges.txt # Your gpt-2 merge file + +GPUS_PER_NODE=1 +# Change for multinode config +MASTER_ADDR=localhost +MASTER_PORT=$(($RANDOM + 1024)) +NNODES=1 +NODE_RANK=0 +WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES)) +SEED=$3 +SUFFIX=$(basename $CHECKPOINT_PATH) +save_dir=$SHARE_DATA/selfgeneration/unconditional_generation_$SUFFIX/ +mkdir -p $save_dir +echo $save_dir/$SEED.out + +DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT" + +python -m torch.distributed.run $DISTRIBUTED_ARGS examples/detxoify_lm/generate_samples_gpt.py \ + --tensor-model-parallel-size 1 \ + --num-layers 24 \ + --hidden-size 2048 \ + --load $CHECKPOINT_PATH \ + --num-attention-heads 32 \ + --max-position-embeddings 2048 \ + --tokenizer-type GPT2BPETokenizer \ + --fp16 \ + --micro-batch-size 150 \ + --seq-length 2048 \ + --out-seq-length 1000 \ + --temperature 1.0 \ + --vocab-file $VOCAB_FILE \ + --merge-file $MERGE_FILE \ + --num-samples $1 \ + --top_p 0.9 \ + --max-tokens-to-oom 1200000 \ + --genfile $save_dir/$SEED.out \ + --seed $SEED + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/README.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8ff95099e0d9e005ecf6bf5ec7e85d0b10eb4d23 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/README.md @@ -0,0 +1,5 @@ + +# Multi-Stage Prompting for Knowledgeable Dialogue Generation + +This directory contains all the scripts of multi-stage prompting for knowledgeable dialogue generation that includes data preparation, and knowledge and response generations. More details are available on [`knowledgeable task directory`](../../tasks/msdp). + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/data_processing.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/data_processing.sh new file mode 100644 index 0000000000000000000000000000000000000000..37a6512a806fd0a141339ea857c73074fced12a9 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/data_processing.sh @@ -0,0 +1,83 @@ +#!/bin/bash + +# Data preparation for our framework: preprocessing the WoW and WoI datasets +# The datasets can be downloaded through the following links: +# WoW: https://parl.ai/projects/wizard_of_wikipedia/ +# WoI: https://parl.ai/projects/sea/ + +DIR=`pwd` +# Before running the preprocessing, please download +# the wizard of wikipedia and wizard datasets +WOW_DATA_FOLDER= +WOI_DATA_FOLDER= + +# We provide examples for processing the raw data from Wizard of Wikipedia +# Processing the train dataset (train.json) +python ${DIR}/tasks/msdp/preprocessing.py \ + --func process_wow_dataset \ + --raw_file ${WOW_DATA_FOLDER}/train.json \ + --processed_file ${WOW_DATA_FOLDER}/train_processed.txt + +# Processing test seen dataset (test_random_split.json) +python ${DIR}/tasks/msdp/preprocessing.py \ + --func process_wow_dataset \ + --raw_file ${WOW_DATA_FOLDER}/test_random_split.json \ + --processed_file ${WOW_DATA_FOLDER}/testseen_processed.txt \ + --knwl_ref_file ${WOW_DATA_FOLDER}/output_testseen_knowledge_reference.txt \ + --resp_ref_file ${WOW_DATA_FOLDER}/output_testseen_response_reference.txt + +# processing test unseen dataset (test_topic_split.json) +python ${DIR}/tasks/msdp/preprocessing.py \ + --func process_wow_dataset \ + --raw_file ${WOW_DATA_FOLDER}/test_topic_split.json \ + --processed_file ${WOW_DATA_FOLDER}/testunseen_processed.txt \ + --knwl_ref_file ${WOW_DATA_FOLDER}/output_testunseen_knowledge_reference.txt \ + --resp_ref_file ${WOW_DATA_FOLDER}/output_testunseen_response_reference.txt + + +# We provide the following script to process the raw data from Wizard of Internet +# Processing the test dataset (test.jsonl) +python ${DIR}/tasks/msdp/preprocessing.py \ + --func process_woi_dataset \ + --raw_file ${WOI_DATA_FOLDER}/test.jsonl \ + --processed_file ${WOI_DATA_FOLDER}/test_processed.txt \ + --knwl_ref_file ${WOI_DATA_FOLDER}/output_test_knowledge_reference.txt \ + --resp_ref_file ${WOI_DATA_FOLDER}/output_test_response_reference.txt + + +# Get the knowledge generation prompts for the each test dataset in WoW and WoI +MODEL_FILE= +# WoW test seen +python ${DIR}/tasks/msdp/preprocessing.py \ + --func get_knwl_gen_prompts \ + --test_file ${WOW_DATA_FOLDER}/testseen_processed.txt \ + --train_file ${WOW_DATA_FOLDER}/train_processed.txt \ + --model_file ${MODEL_FILE} \ + --processed_file ${WOW_DATA_FOLDER}/output_testseen_knowledge_prompts.json \ + --data_type wow_seen + +# WoW test unseen +python ${DIR}/tasks/msdp/preprocessing.py \ + --func get_knwl_gen_prompts \ + --test_file ${WOW_DATA_FOLDER}/testunseen_processed.txt \ + --train_file ${WOW_DATA_FOLDER}/train_processed.txt \ + --model_file ${MODEL_FILE} \ + --processed_file ${WOW_DATA_FOLDER}/output_testunseen_knowledge_prompts.json \ + --data_type wow_unseen + +# WoI +python ${DIR}/tasks/msdp/preprocessing.py \ + --func get_knwl_gen_prompts \ + --test_file ${WOI_DATA_FOLDER}/test_processed.txt \ + --train_file ${WOW_DATA_FOLDER}/train_processed.txt \ + --model_file ${MODEL_FILE} \ + --processed_file ${WOI_DATA_FOLDER}/output_test_knowledge_prompts.json \ + --data_type woi + + +# Get the response generation prompts (can be applied for all the test datasets) +python ${DIR}/tasks/msdp/preprocessing.py \ + --func get_resp_gen_prompts \ + --train_file ${WOW_DATA_FOLDER}/train_processed.txt \ + --processed_file ${WOW_DATA_FOLDER}/output_response_prompts.txt + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/eval_knwl_generation.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/eval_knwl_generation.sh new file mode 100644 index 0000000000000000000000000000000000000000..8fc2fff1fb776c3f0c54e25e50aefedc0ca8fd0a --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/eval_knwl_generation.sh @@ -0,0 +1,43 @@ +#!/bin/bash + +######################### +# Evaluate the F1 scores. +######################### + +WORLD_SIZE=1 +DISTRIBUTED_ARGS="--nproc_per_node $WORLD_SIZE \ + --nnodes 1 \ + --node_rank 0 \ + --master_addr localhost \ + --master_port 6000" + +MODEL_GEN_PATH= \ + (e.g., /testseen_knowledge_generations.txt) +GROUND_TRUTH_PATH= \ + (e.g., /testseen_knowledge_reference.txt) + +python -m torch.distributed.launch $DISTRIBUTED_ARGS ./tasks/msdp/main.py \ + --num-layers 24 \ + --hidden-size 1024 \ + --num-attention-heads 16 \ + --seq-length 2048 \ + --max-position-embeddings 2048 \ + --micro-batch-size 4 \ + --task MSDP-EVAL-F1 \ + --guess-file ${MODEL_GEN_PATH} \ + --answer-file ${GROUND_TRUTH_PATH} + + +############################################ +# Evaluate BLEU, METEOR, and ROUGE-L scores. +############################################ + +# We follow the nlg-eval (https://github.com/Maluuba/nlg-eval) to +# evaluate the BLEU, METEOR, and ROUGE-L scores. + +# To evaluate on these metrics, please setup the environments based on +# the nlg-eval github, and run the corresponding evaluation commands. + +nlg-eval \ + --hypothesis= \ + --references= diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/eval_resp_generation.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/eval_resp_generation.sh new file mode 100644 index 0000000000000000000000000000000000000000..3ce87e077957904b234276657d000ba8c729dcfe --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/eval_resp_generation.sh @@ -0,0 +1,64 @@ +#!/bin/bash + +######################### +# Evaluate the F1 scores. +######################### + +WORLD_SIZE=1 +DISTRIBUTED_ARGS="--nproc_per_node $WORLD_SIZE \ + --nnodes 1 \ + --node_rank 0 \ + --master_addr localhost \ + --master_port 6000" + +MODEL_GEN_PATH= \ + (e.g., /testseen_response_generations.txt) +GROUND_TRUTH_PATH= \ + (e.g., /testseen_response_reference.txt) + +python -m torch.distributed.launch $DISTRIBUTED_ARGS ./tasks/msdp/main.py \ + --num-layers 24 \ + --hidden-size 1024 \ + --num-attention-heads 16 \ + --seq-length 2048 \ + --max-position-embeddings 2048 \ + --micro-batch-size 4 \ + --task MSDP-EVAL-F1 \ + --guess-file ${MODEL_GEN_PATH} \ + --answer-file ${GROUND_TRUTH_PATH} + + +########################## +# Evaluate the KF1 scores. +########################## + +MODEL_GEN_PATH= \ + (e.g., /testseen_response_generations.txt) +GROUND_TRUTH_PATH= \ + (e.g., /testseen_knowledge_reference.txt) + +python -m torch.distributed.launch $DISTRIBUTED_ARGS ./tasks/msdp/main.py \ + --num-layers 24 \ + --hidden-size 1024 \ + --num-attention-heads 16 \ + --seq-length 2048 \ + --max-position-embeddings 2048 \ + --micro-batch-size 4 \ + --task MSDP-EVAL-F1 \ + --guess-file ${MODEL_GEN_PATH} \ + --answer-file ${GROUND_TRUTH_PATH} + + +############################################ +# Evaluate BLEU, METEOR, and ROUGE-L scores. +############################################ + +# We follow the nlg-eval (https://github.com/Maluuba/nlg-eval) to +# evaluate the BLEU, METEOR, and ROUGE-L scores. + +# To evaluate on these metrics, please setup the environments based on +# the nlg-eval github, and run the corresponding evaluation commands. + +nlg-eval \ + --hypothesis= \ + --references= diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/prep_resp_gen.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/prep_resp_gen.sh new file mode 100644 index 0000000000000000000000000000000000000000..5f202724dddbaa6ada3bcb1c33ec035a3afe44ee --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/prep_resp_gen.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +# Preparing the input file for the response generation (second-stage prompting) + +DIR=`pwd` + +TEST_FILE= \ + (e.g., /testseen_processed.txt) +KNOWLEDGE_FILE= \ + (e.g., /testseen_knowledge_generations.txt) +PROCESSED_FILE= \ + (e.g., /testseen_processed_with_generated_knowledge.txt) + +python ${DIR}/tasks/msdp/preprocessing.py \ + --func prepare_input \ + --test_file ${TEST_FILE} \ + --knwl_gen_file ${KNOWLEDGE_FILE} \ + --processed_file ${PROCESSED_FILE} diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/prompt_knwl_gen.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/prompt_knwl_gen.sh new file mode 100644 index 0000000000000000000000000000000000000000..12e0cc5b380036f167b35d6f514eafc1e1acec32 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/prompt_knwl_gen.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +# Stage-1: Prompt a pretrained language model to generate the context-relevant knowledge +# The input contains prompts and current dialogue context, the output is the relevant knowledge +# The size of the pretrained language model is 357M + +WORLD_SIZE=8 + +DISTRIBUTED_ARGS="--nproc_per_node $WORLD_SIZE \ + --nnodes 1 \ + --node_rank 0 \ + --master_addr localhost \ + --master_port 6000" + +CHECKPOINT_PATH= (e.g., /357m) +VOCAB_PATH= (e.g., /gpt2-vocab.json) +MERGE_PATH= (e.g., /gpt2-merges.txt) +INPUT_PATH= \ + (e.g., /testseen_processed.txt) +PROMPT_PATH= \ + (e.g., /testseen_knowledge_prompts.json) +OUTPUT_PATH= \ + (e.g., /testseen_knowledge_generations.txt) + +python -m torch.distributed.launch $DISTRIBUTED_ARGS ./tasks/msdp/main.py \ + --num-layers 24 \ + --hidden-size 1024 \ + --num-attention-heads 16 \ + --seq-length 2048 \ + --max-position-embeddings 2048 \ + --micro-batch-size 1 \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --load ${CHECKPOINT_PATH} \ + --fp16 \ + --DDP-impl torch \ + --tokenizer-type GPT2BPETokenizer \ + --sample-input-file ${INPUT_PATH} \ + --sample-output-file ${OUTPUT_PATH} \ + --prompt-file ${PROMPT_PATH} \ + --prompt-type knowledge \ + --num-prompt-examples 10 \ + --task MSDP-PROMPT + +# NOTE: If you use api for the model generation, please use +# the "--api-prompt" flag (setting this value as True). diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/prompt_resp_gen.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/prompt_resp_gen.sh new file mode 100644 index 0000000000000000000000000000000000000000..b836d7feacfcac5f093840727be8933e5585163e --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/prompt_resp_gen.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +# Stage-2: Prompt a pretrained language model to generate the corresponding response +# The input contains prompts, current dialogue context, and generated knowledge in Stage-1 +# The output is the corresponding response. +# The size of the pretrained language model is 357M + +WORLD_SIZE=8 + +DISTRIBUTED_ARGS="--nproc_per_node $WORLD_SIZE \ + --nnodes 1 \ + --node_rank 0 \ + --master_addr localhost \ + --master_port 6000" + +CHECKPOINT_PATH= (e.g., /357m) +VOCAB_PATH= (e.g., /gpt2-vocab.json) +MERGE_PATH= (e.g., /gpt2-merges.txt) +INPUT_PATH= (e.g., /testseen_processed.txt) +PROMPT_PATH= \ + (e.g., /response_prompts.txt) +OUTPUT_PATH= \ + (e.g., /output_testseen_response_generations.txt) + +python -m torch.distributed.launch $DISTRIBUTED_ARGS ./tasks/msdp/main.py \ + --num-layers 24 \ + --hidden-size 1024 \ + --num-attention-heads 16 \ + --seq-length 2048 \ + --max-position-embeddings 2048 \ + --micro-batch-size 1 \ + --vocab-file ${VOCAB_PATH} \ + --merge-file ${MERGE_PATH} \ + --load ${CHECKPOINT_PATH} \ + --fp16 \ + --DDP-impl torch \ + --tokenizer-type GPT2BPETokenizer \ + --sample-input-file ${INPUT_PATH} \ + --sample-output-file ${OUTPUT_PATH} \ + --prompt-file ${PROMPT_PATH} \ + --prompt-type response \ + --num-prompt-examples 20 \ + --task MSDP-PROMPT + +# NOTE: If you use api for the model generation, please use +# the "--api-prompt" flag (setting this value as True). diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/CONFIG.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/CONFIG.sh new file mode 100644 index 0000000000000000000000000000000000000000..f17ccd7b023ca9aeb538ba38a60808e44418873b --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/CONFIG.sh @@ -0,0 +1,57 @@ +#!/bin/bash + + +# SLURM options. +export SLURM_PARTITION= +export SLURM_ACCOUNT= + + +# Source code. +export MEGATRON_CODE_DIR= + + +# This variable is used to mount the relevant part of the filesystem +# inside the docker container. Note that the `MEGATRON_CODE_DIR` and the +# launch directory already get mounted; this variable should be used to +# mount the directories that contain the data and tokenizer files. +export DOCKER_MOUNT_DIR= + + +# Data and tokenizer files. +MEGATRON_DATA= +BPE_VOCAB_FILE= +BPE_MERGE_FILE= + + +# Megatron input parameters. +# `MEGATRON_EXTRA_PARAMS` can be used to provide any extra parameters +# that are not listed here. +export MEGATRON_PARAMS=" ${MEGATRON_EXTRA_PARAMS} \ + --tensor-model-parallel-size ${TP} \ + --pipeline-model-parallel-size ${PP} \ + --micro-batch-size ${MBS} \ + --global-batch-size ${GBS} \ + --num-layers ${NLS} \ + --hidden-size ${HS} \ + --num-attention-heads ${NAH} \ + --DDP-impl ${DDP} \ + --data-path ${MEGATRON_DATA} \ + --vocab-file ${BPE_VOCAB_FILE} \ + --merge-file ${BPE_MERGE_FILE} \ + --log-interval 5 \ + --seq-length 2048 \ + --max-position-embeddings 2048 \ + --train-iters 500 \ + --lr-decay-iters 320 \ + --lr 0.0001 \ + --min-lr 0.00001 \ + --lr-decay-style cosine \ + --lr-warmup-fraction 0.01 \ + --split 969,30,1 \ + --eval-iters 100 \ + --eval-interval 1000 \ + --clip-grad 1.0 \ + --fp16 \ + --loss-scale 8192 " + + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/README.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ec922d153d663749cf685256d6eb16f4dea4ca33 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/README.md @@ -0,0 +1,50 @@ +# Reproducing Figures in SC21 Paper + + +This directory contains some of the scripts that were used to produce the +results in the [Megatron paper](https://arxiv.org/pdf/2104.04473.pdf) that is +to appear at [SuperComputing 2021](https://sc21.supercomputing.org/). These +scripts use [Slurm](https://slurm.schedmd.com/documentation.html) with the +[pyxis plugin](https://github.com/NVIDIA/pyxis), but can be modified for other +schedulers as well. + + +## Git commit + +To replicate these results use Megatron-LM commit: 6985e58938d40ad91ac07b0fddcfad8132e1447e + + +## Setup + +All the cluster-dependent variables are in [`CONFIG.sh`](./CONFIG.sh). Please +update the unspecified values (in angle brackets `<...>`) before launching any +scripts. + + + +## Scripts + +Below is a list of scripts that can be used to reproduce various figures in our +[paper](https://arxiv.org/pdf/2104.04473.pdf): + +* [run_table_1.sh](./run_table_1.sh): Table 1 showing weak-scaling throughput +for GPT models ranging from 1 billion to 1 trillion parameters. +* [run_figure_11.sh](./run_figure_11.sh): Figure 11 showing the weak-scaling +performance of pipeline parallelism. +* [run_figure_12.sh](./run_figure_12.sh): Figure 12 showing the effect of +the interleaved schedule on a 175B GPT model. +* [run_figure_13.sh](./run_figure_13.sh): Figure 13 showing the effect of +different degrees of pipeline and tensor model parallelism on a model with +162.2 billion parameters. +* [run_figure_14.sh](./run_figure_14.sh): Figure 14 showing the effect of +different degrees of data and pipeline model parallelism on a model with +5.9 billion parameters. +* [run_figure_15.sh](./run_figure_15.sh): Figure 15 showing the effect of +different degrees of data and tensor model parallelism on a model with +5.9 billion parameters. +* [run_figure_16.sh](./run_figure_16.sh): Figure 16 showing the effect of +microbatch size. +* [run_figure_17.sh](./run_figure_17.sh): Figure 17 showing the effect of +activation recomputation. +* [run_figure_18.sh](./run_figure_18.sh): Figure 18 showing the effect of +the scatter-gather communication optimization. diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/SBATCH.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/SBATCH.sh new file mode 100644 index 0000000000000000000000000000000000000000..95431b9b7e780bbdd4b18593546356aad02945b1 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/SBATCH.sh @@ -0,0 +1,13 @@ +#!/bin/bash + + +sbatch -p ${SLURM_PARTITION} \ + -A ${SLURM_ACCOUNT} \ + --job-name=${JOB_NAME} \ + --nodes=${NNODES} \ + --export=MEGATRON_CODE_DIR,MEGATRON_PARAMS,DOCKER_MOUNT_DIR SRUN.sh + +exit 0 + + + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/SRUN.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/SRUN.sh new file mode 100644 index 0000000000000000000000000000000000000000..52a9aff0c1294acb1e5527faad4f73fe5e027e21 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/SRUN.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +#SBATCH -t 0:30:00 --exclusive --mem=0 --overcommit --ntasks-per-node=8 + + +THIS_DIR=`pwd` +DATETIME=`date +'date_%y-%m-%d_time_%H-%M-%S'` +mkdir -p ${THIS_DIR}/logs + + +CMD="python -u ${MEGATRON_CODE_DIR}/pretrain_gpt.py ${MEGATRON_PARAMS}" + + +srun -l \ + --container-image "nvcr.io#nvidia/pytorch:20.12-py3" \ + --container-mounts "${THIS_DIR}:${THIS_DIR},${MEGATRON_CODE_DIR}:${MEGATRON_CODE_DIR},${DOCKER_MOUNT_DIR}:${DOCKER_MOUNT_DIR}" \ + --output=${THIS_DIR}/logs/%x_%j_$DATETIME.log sh -c "${CMD}" + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_11.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_11.sh new file mode 100644 index 0000000000000000000000000000000000000000..2ec7d9eb31e50e01e3d5dab6978a71deffd247aa --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_11.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +# ================================ +# Choose the case to run. +# ================================ + +# Pipeline-parallel size options = [1, 2, 4, 8]. +PP=1 + +# Batch size (global batch size) options = [8, 128]. +GBS=8 + + + + + +# Set pipeline-parallel size options. +NLS=$((3*PP)) +NNODES=${PP} + + +# Other params. +TP=8 +MBS=1 +HS=20480 +NAH=128 +DDP=local +MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform " + + +# Name of the job. +export JOB_NAME=results_figure_11_pipeline_parallel_size_${PP}_batch_size_${GBS} + + +# Import the configs. +. `pwd`/CONFIG.sh + + +# Submit the job. +. `pwd`/SBATCH.sh + + +exit 0 + + + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_12.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_12.sh new file mode 100644 index 0000000000000000000000000000000000000000..11e550854de4cd576d9625ca9dd5330d44fffb76 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_12.sh @@ -0,0 +1,54 @@ +#!/bin/bash + +# ================================ +# Choose the case to run. +# ================================ + +# Interleaved schedule options = [YES, NO]. +INTERLEAVED=YES + +# Batch size (global batch size) options = [12, 24, 36, ..., 60]. +GBS=12 + + + + + +# Set interleaved schedule options. +if [ ${INTERLEAVED} == "YES" ]; then + MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform --num-layers-per-virtual-pipeline-stage 2 " +elif [ ${INTERLEAVED} == "NO" ]; then + MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform " +else + echo "Invalid configuration" + exit 1 +fi + + +# Other params. +TP=8 +PP=12 +MBS=1 +NLS=96 +HS=12288 +NAH=96 +DDP=local +NNODES=12 + + +# Name of the job. +export JOB_NAME=results_figure_12_interleaved_${INTERLEAVED}_batch_size_${GBS} + + +# Import the configs. +. `pwd`/CONFIG.sh + + +# Submit the job. +. `pwd`/SBATCH.sh + + +exit 0 + + + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_13.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_13.sh new file mode 100644 index 0000000000000000000000000000000000000000..7ba560e87b253fb63192866d3089c3d967f086e6 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_13.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +# ================================ +# Choose the case to run. +# ================================ + +# Pipeline-parallel size options = [2, 4, 8, 16, 32]. +PP=2 + +# Batch size (global batch size) options = [32, 128]. +GBS=32 + + + + + +# Set pipeline-parallel and tensor-parallel size options. +TP=$((64/PP)) + + +# Other params. +MBS=1 +NLS=32 +HS=20480 +NAH=128 +DDP=local +MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform " +NNODES=8 + + +# Name of the job. +export JOB_NAME=results_figure_13_pipeline_parallel_size_${PP}_tensor_parallel_size_${TP}_batch_size_${GBS} + + +# Import the configs. +. `pwd`/CONFIG.sh + + +# Submit the job. +. `pwd`/SBATCH.sh + + +exit 0 + + + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_14.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_14.sh new file mode 100644 index 0000000000000000000000000000000000000000..4b83879c4bb71546a7fb5bac365491efd96d3049 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_14.sh @@ -0,0 +1,47 @@ +#!/bin/bash + +# ================================ +# Choose the case to run. +# ================================ + +# Pipeline-parallel size options = [2, 4, 8, 16, 32]. +PP=2 + +# Batch size (global batch size) options = [32, 512]. +GBS=32 + + + + + +# Set pipeline-parallel and data-parallel size options. +DP=$((64/PP)) + + +# Other params. +TP=1 +MBS=1 +NLS=32 +HS=3840 +NAH=32 +DDP=local +MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform " +NNODES=8 + + +# Name of the job. +export JOB_NAME=results_figure_14_pipeline_parallel_size_${PP}_data_parallel_size_${DP}_batch_size_${GBS} + + +# Import the configs. +. `pwd`/CONFIG.sh + + +# Submit the job. +. `pwd`/SBATCH.sh + + +exit 0 + + + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_15.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_15.sh new file mode 100644 index 0000000000000000000000000000000000000000..547ad1de6fb091ca5f922e2b48559ceadffa7ce8 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_15.sh @@ -0,0 +1,47 @@ +#!/bin/bash + +# ================================ +# Choose the case to run. +# ================================ + +# Tensor-parallel size options = [2, 4, 8, 16, 32]. +TP=2 + +# Batch size (global batch size) options = [32, 128, 512]. +GBS=32 + + + + + +# Set tensor-parallel and data-parallel size options. +DP=$((64/TP)) + + +# Other params. +PP=1 +MBS=1 +NLS=32 +HS=3840 +NAH=32 +DDP=local +MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform " +NNODES=8 + + +# Name of the job. +export JOB_NAME=results_figure_15_tensor_parallel_size_${TP}_data_parallel_size_${DP}_batch_size_${GBS} + + +# Import the configs. +. `pwd`/CONFIG.sh + + +# Submit the job. +. `pwd`/SBATCH.sh + + +exit 0 + + + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_16.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_16.sh new file mode 100644 index 0000000000000000000000000000000000000000..8c353a3e7623262baf9dc6c24554e9ab4dce26e7 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_16.sh @@ -0,0 +1,43 @@ +#!/bin/bash + +# ================================ +# Choose the case to run. +# ================================ + +# Microbatch size options = [1, 2, 4, 8]. +MBS=1 + +# Batch size (global batch size) options = [128, 512]. +GBS=128 + + + + + +# Other params. +TP=8 +PP=8 +NLS=32 +HS=15360 +NAH=128 +DDP=local +MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform " +NNODES=8 + + +# Name of the job. +export JOB_NAME=results_figure_16_microbatch_size_${MBS}_batch_size_${GBS} + + +# Import the configs. +. `pwd`/CONFIG.sh + + +# Submit the job. +. `pwd`/SBATCH.sh + + +exit 0 + + + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_17.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_17.sh new file mode 100644 index 0000000000000000000000000000000000000000..d6899b321d6c11238af3b12da3690c8c3d46be34 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_17.sh @@ -0,0 +1,54 @@ +#!/bin/bash + +# ================================ +# Choose the case to run. +# ================================ + +# Activation recomputation options = [YES, NO]. +ACTIVATION_RECOMPUTATION=YES + +# Batch size (global batch size) options = [1, 2, 4, ..., 256]. +GBS=1 + + + + + +# Set activation recomputation. +if [ ${ACTIVATION_RECOMPUTATION} == "YES" ]; then + MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform " +elif [ ${ACTIVATION_RECOMPUTATION} == "NO" ]; then + MEGATRON_EXTRA_PARAMS="" +else + echo "Invalid configuration" + exit 1 +fi + + +# Other params. +TP=8 +PP=16 +MBS=1 +NLS=80 +HS=12288 +NAH=96 +DDP=local +NNODES=16 + + +# Name of the job. +export JOB_NAME=results_figure_17_activation_recomputation_${ACTIVATION_RECOMPUTATION}_batch_size_${GBS} + + +# Import the configs. +. `pwd`/CONFIG.sh + + +# Submit the job. +. `pwd`/SBATCH.sh + + +exit 0 + + + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_18.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_18.sh new file mode 100644 index 0000000000000000000000000000000000000000..88924fb820be4767ed6aa00633682ece581329db --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_figure_18.sh @@ -0,0 +1,54 @@ +#!/bin/bash + +# ================================ +# Choose the case to run. +# ================================ + +# Scatter-gather communication optimization options = [YES, NO]. +SCATTER_GATHER=YES + +# Batch size (global batch size) options = [12, 24, 36, ..., 60]. +GBS=12 + + + + + +# Set scatter-gather communication optimization options. +if [ ${SCATTER_GATHER} == "YES" ]; then + MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform --num-layers-per-virtual-pipeline-stage 2 " +elif [ ${SCATTER_GATHER} == "NO" ]; then + MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform --num-layers-per-virtual-pipeline-stage 2 --no-scatter-gather-tensors-in-pipeline " +else + echo "Invalid configuration" + exit 1 +fi + + +# Other params. +TP=8 +PP=12 +MBS=1 +NLS=96 +HS=12288 +NAH=96 +DDP=local +NNODES=12 + + +# Name of the job. +export JOB_NAME=results_figure_18_scatter_gather_${SCATTER_GATHER}_batch_size_${GBS} + + +# Import the configs. +. `pwd`/CONFIG.sh + + +# Submit the job. +. `pwd`/SBATCH.sh + + +exit 0 + + + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_table_1.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_table_1.sh new file mode 100644 index 0000000000000000000000000000000000000000..1b15fb04582c90dc47fb1bbd3aca46feca2585ba --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/sc21/run_table_1.sh @@ -0,0 +1,145 @@ +#!/bin/bash + +# ================================ +# Choose the case to run. +# ================================ +# model size options = [1.7B, 3.6B, 7.5B, 18B, 39B, 76B, 145B, 310B, 530B, 1T] +MODEL_SIZE=1.7B + + + + + + +if [ ${MODEL_SIZE} == "1.7B" ]; then + TP=1 + PP=1 + MBS=16 + GBS=512 + NLS=24 + HS=2304 + NAH=24 + DDP=torch + NNODES=4 + MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform " +elif [ ${MODEL_SIZE} == "3.6B" ]; then + TP=2 + PP=1 + MBS=16 + GBS=512 + NLS=30 + HS=3072 + NAH=32 + DDP=torch + NNODES=8 + MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform " +elif [ ${MODEL_SIZE} == "7.5B" ]; then + TP=4 + PP=1 + MBS=16 + GBS=512 + NLS=36 + HS=4096 + NAH=32 + DDP=torch + NNODES=16 + MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform " +elif [ ${MODEL_SIZE} == "18B" ]; then + TP=8 + PP=1 + MBS=8 + GBS=1024 + NLS=40 + HS=6144 + NAH=48 + DDP=torch + NNODES=32 + MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform " +elif [ ${MODEL_SIZE} == "39B" ]; then + TP=8 + PP=2 + MBS=4 + GBS=1536 + NLS=48 + HS=8192 + NAH=64 + DDP=local + NNODES=64 + MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform " +elif [ ${MODEL_SIZE} == "76B" ]; then + TP=8 + PP=4 + MBS=2 + GBS=1792 + NLS=60 + HS=10240 + NAH=80 + DDP=local + NNODES=128 + MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform --num-layers-per-virtual-pipeline-stage 5" +elif [ ${MODEL_SIZE} == "145B" ]; then + TP=8 + PP=8 + MBS=2 + GBS=2304 + NLS=80 + HS=12288 + NAH=96 + DDP=local + NNODES=192 + MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform --num-layers-per-virtual-pipeline-stage 5 " +elif [ ${MODEL_SIZE} == "310B" ]; then + TP=8 + PP=16 + MBS=1 + GBS=2160 + NLS=96 + HS=16384 + NAH=128 + DDP=local + NNODES=240 + MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform --num-layers-per-virtual-pipeline-stage 3 " +elif [ ${MODEL_SIZE} == "530B" ]; then + TP=8 + PP=35 + MBS=1 + GBS=2520 + NLS=105 + HS=20480 + NAH=128 + DDP=local + NNODES=315 + MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform --num-layers-per-virtual-pipeline-stage 1 " +elif [ ${MODEL_SIZE} == "1T" ]; then + TP=8 + PP=64 + MBS=1 + GBS=3072 + NLS=128 + HS=25600 + NAH=160 + DDP=local + NNODES=384 + MEGATRON_EXTRA_PARAMS="--activations-checkpoint-method uniform " +else + echo "Invalid configuration" + exit 1 +fi + + +# Name of the job +export JOB_NAME=results_table_1_model_size_${MODEL_SIZE} + + +# Import the configs. +. `pwd`/CONFIG.sh + + +# Submit the job. +. `pwd`/SBATCH.sh + + +exit 0 + + + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/.gitignore b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b9272bd3eb2da7cdb0438dc0f01b39719dad3dce --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/.gitignore @@ -0,0 +1 @@ +!slurm* diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/ADVANCED.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/ADVANCED.md new file mode 100644 index 0000000000000000000000000000000000000000..28aad7d79642eb9c6621af04fbce53f38d9f94ec --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/ADVANCED.md @@ -0,0 +1,93 @@ +
+ +# Advanced Usage + +[Advanced Configuration](#advanced-configuration) | +[Slurm Examples](#slurm-examples) | +[Checkpoint Resume](#checkpoint-resume) | + +
+ +## Advanced Configuration + +### Understanding Configuration Variables + +For simplicity, we use `shell` scripts and variables as arguments. Each script has at least 1 positional +argument `[model_conf]`. Some scripts may require more such as `[qformat]` is needed for +quantization. + +```sh +\ + HF_MODEL_CKPT= \ + bash quantize.sh [model_conf] [qformat] +``` + +> **❗ IMPORTANT:** `model_conf` is used to get the corresponding Megatron-LM `${MODEL_ARGS}`. For example, +> `meta-llama/Llama-3.1-8B-Instruct` or `deepseek-ai/DeepSeek-R1` are both supported. +> +> Provide the pretrained checkpoint through variable `${HF_MODEL_CKPT}` in commandline or +> in a configuration shell script. More variables (e.g. `${TP}`, `${EP}`, ...) can be provided through +> commandline but we recommend passing all variables in a separate `shell` script. + +### Using Configuration Scripts + +When `${HF_MODEL_CKPT}` is not set through the commandline, `./env_setup_template.sh` can be used +to pass all variables instead. If you have your own script, use `${SANDBOX_ENV_SETUP}`. + +```sh +\ + SANDBOX_ENV_SETUP= \ + bash quantize.sh [model_conf] [qformat] +``` + +**For Slurm execution**, you **MUST USE** `${SANDBOX_ENV_SETUP}` (default: `./env_setup_template.sh`). +Other variables are not passed through `sbatch` and `srun` automatically. + +### Common Configuration Variables + +- `HF_MODEL_CKPT`: Path to pretrained model checkpoint +- `TP`: Tensor parallelism degree +- `PP`: Pipeline parallelism degree +- `EP`: Expert parallelism degree (for MoE models) +- `ETP`: Expert tensor parallelism degree (for MoE models) +- `MLM_MODEL_SAVE`: Path to save Megatron-LM checkpoint +- `MLM_MODEL_LOAD`: Path to load Megatron-LM checkpoint +- `MLM_EXTRA_ARGS`: Additional Megatron-LM arguments (e.g., for uneven PP) + +## Slurm Examples + +For models that require multi-node, our scripts in Megatron-LM examples also support `slurm` with a sbatch wrapper. +Start with the example `slurm/sbatch.sh` with some minor modification or use your existing `sbatch` +script. + +Different from local environment, we only allow passing variables through a shell script (default: `env_setup_template.sh`). +Commandline variable passthrough is not supported. + +
+ +### ⭐ BF16 Kimi-K2-Instruct EAGLE3 Training + + `conf/moonshotai/kimi_k2_instruct.sh` is a config that has been tested +with 8 nodes of DGX H100 (TP=8, ETP=1, EP=64, overall 64 H100 GPUs in total). Update `HF_MODEL_CKPT` to the exact +checkpoint path in the container to start: + +```sh +export USER_FSW= +export CONTAINER_IMAGE= +export SANDBOX_ENV_SETUP=./conf/moonshotai/kimi_k2_instruct.sh +sbatch --nodes=8 slurm/sbatch.sh "eagle3.sh moonshotai/Kimi-K2-Instruct" +``` + +To export the trained EAGLE3 model, switch to `kimi_k2_instruct_export.sh`. +**We only support pipeline-parallel (PP) export.** In this case, 2 nodes are used (PP=16). + +```sh +export USER_FSW= +export CONTAINER_IMAGE= +export SANDBOX_ENV_SETUP=./conf/moonshotai/kimi_k2_instruct_export.sh +sbatch --nodes=2 slurm/sbatch.sh "export.sh moonshotai/Kimi-K2-Instruct" +``` + +## Checkpoint Resume + +WIP diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/Dockerfile b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f44306ef08e515846388e880600f2638353eaec0 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/Dockerfile @@ -0,0 +1,17 @@ +FROM nvcr.io/nvidia/pytorch:25.06-py3 + +ARG PIP_CONSTRAINT= + +WORKDIR /workspace/nmm-sandbox + +RUN pip install omegaconf +RUN pip install flask flask_restful fire nltk +RUN pip install tiktoken blobfile + +RUN pip install datasets transformers + +RUN pip install triton==3.3.1 +RUN pip install git+https://github.com/state-spaces/mamba.git +RUN pip install git+https://github.com/Dao-AILab/causal-conv1d.git + +RUN pip install -U nvidia-modelopt diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/README.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a6fcaf8f5b7899ccca9097d486c6f13e928ce50d --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/README.md @@ -0,0 +1,235 @@ +
+ +# Model Optimizer Integrated Examples + + +[Model Optimizer](https://github.com/NVIDIA/Model-Optimizer) | +[Local Examples](#getting-started-in-a-local-environment) | +[Configuration](./ADVANCED.md#advanced-configuration) | +[Slurm Examples](./ADVANCED.md#slurm-examples) | +[Speculative Decoding](./speculative.md) | +[Knowledge Distillation](./distillation.md) | +[Advanced Topics](./ADVANCED.md) + +
+ +[Model Optimizer](https://github.com/NVIDIA/Model-Optimizer) (**ModelOpt**, `nvidia-modelopt`) +provides end-to-end model optimization for NVIDIA hardware including quantization (real or simulated), +knowledge distillation, pruning, speculative decoding, and more. + + +## Major Features + +- Start from Hugging Face pretrained model checkpoint with on-the-fly conversion to Megatron-LM checkpoint format. +- Support all kinds of model parallelism (TP, EP, ETP, PP). +- Export to TensorRT-LLM, vLLM, and SGLang ready unified checkpoint. + +## Support Matrix {Model}x{Features} + +| Model (`conf/`) | Quantization | EAGLE3 | Pruning (PP only) | Distillation | +| :---: | :---: | :---: | :---: | :---: | +| `deepseek-ai/DeepSeek-R1` | ✅ | ✅ | - | - | +| `meta-llama/Llama-{3.1-8B, 3.1-405B, 3.2-1B}-Instruct` | ✅ | ✅ | ✅ | ✅ | +| `meta-llama/Llama-4-{Scout,Maverick}-17B-{16,128}E-Instruct` | ✅ | ✅ | - | - | +| `moonshotai/Kimi-K2-Instruct` | ✅ | ✅ | - | - | +| `nvidia/NVIDIA-Nemotron-Nano-9B-v2` | ✅ | - | ✅ | ✅ | +| `nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16` | ✅ | - | ✅ | ✅ | +| `nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16` | ✅ | - | ✅ | ✅ | +| `openai/gpt-oss-{20b, 120b}` | ✅ | **Online** | ✅ | ✅ | +| `Qwen/Qwen3-{0.6B, 8B}` | ✅ | ✅ | ✅ | ✅ | +| `Qwen/Qwen3-{30B-A3B, 235B-A22B}` | **WAR** | ✅ | ✅ | ✅ | + +## Getting Started in a Local Environment + +Install `nvidia-modelopt` from [PyPI](https://pypi.org/project/nvidia-modelopt/): +```sh +pip install -U nvidia-modelopt +``` +Alternatively, you can install from [source](https://github.com/NVIDIA/Model-Optimizer) +to try our latest features. + +> **❗ IMPORTANT:** The first positional argument (e.g. `meta-llama/Llama-3.2-1B-Instruct`) of each script +> is the config name used to match the supported model config in `conf/`. The pretrained HF checkpoint should +> be downloaded and provided through `${HF_MODEL_CKPT}`. + + +### ⭐ NVFP4 Quantization, Qauntization-Aware Training, and Model Export + +Provide the pretrained checkpoint path through variable `${HF_MODEL_CKPT}` and provide variable +`${MLM_MODEL_SAVE}` which stores a resumeable Megatron-LM distributed checkpoint. To export +Hugging Face-Like quantized checkpoint for TensorRT-LLM, vLLM, or SGLang deployement, +provide `${EXPORT_DIR}` to `export.sh`. + +> **📙 NOTE:** ModelOpt supports different quantization formats which are listed in the [ModelOpt quant configs](https://github.com/NVIDIA/Model-Optimizer/blob/7971fff05882da7eae16eae6bc927d1481dcd63f/modelopt/torch/quantization/config.py#L626). +> The quant config is specified by the full config name in all-caps, e.g. NVFP4_DEFAULT_CFG. +> By default, we simulate the low-precision numerical behavior (fake-quant) which can be run on GPUs with compute > 80. +> Real low-precision paramters (e.g. `E4M3` or `E2M1`) +> and low-precision compute (e.g. `FP8Linear`) are also supported depending on GPU compute capability. +> **See [Advanced Topics](./ADVANCED.md) for details**. + +```sh +\ + TP=1 \ + HF_MODEL_CKPT= \ + MLM_MODEL_SAVE=/tmp/Llama-3.2-1B-Instruct_quant \ + ./quantize.sh meta-llama/Llama-3.2-1B-Instruct NVFP4_DEFAULT_CFG + +\ + PP=1 \ + HF_MODEL_CKPT= \ + MLM_MODEL_CKPT=/tmp/Llama-3.2-1B-Instruct_quant \ + EXPORT_DIR=/tmp/Llama-3.2-1B-Instruct_export \ + ./export.sh meta-llama/Llama-3.2-1B-Instruct +``` + +To export the model for vLLM fakequant example in `modelopt/examples/vllm_serve/vllm_serve_fakequant.py`, +export the model with flag `--export-vllm-fq`: +```sh +\ + PP=1 \ + MLM_EXTRA_ARGS=--export-vllm-fq \ + HF_MODEL_CKPT= \ + MLM_MODEL_CKPT=/tmp/Llama-3.2-1B-Instruct_quant \ + EXPORT_DIR=/tmp/Llama-3.2-1B-Instruct_export \ + ./export.sh meta-llama/Llama-3.2-1B-Instruct +``` + +For KV cache quantization, add a flag like `MLM_EXTRA_ARGS="--export-kv-cache-quant fp8"` while specifying your desired KV cache precision (see `KV_QUANT_CFG_CHOICES` in `quantize.py`). + +### ⭐ Online BF16 EAGLE3 Training + +Online EAGLE3 training has both the target (frozen) and draft models in the memory where the `hidden_states` +required for training is generated on the fly. Periodically, acceptance length (AL, the higher the better) is +evaluated on MT-Bench prompts. Use the same `export.sh` script to export the EAGLE3 checkpoint for +deployment. + +```sh +\ + TP=1 \ + HF_MODEL_CKPT= \ + MLM_MODEL_SAVE=/tmp/Llama-3.2-1B-Eagle3 \ + ./eagle3.sh meta-llama/Llama-3.2-1B-Instruct + +\ + PP=1 \ + HF_MODEL_CKPT= \ + MLM_MODEL_CKPT=/tmp/Llama-3.2-1B-Eagle3 \ + EXPORT_DIR=/tmp/Llama-3.2-1B-Eagle3-Export \ + ./export.sh meta-llama/Llama-3.2-1B-Instruct +``` + +See [Advanced Topics](./ADVANCED.md) for a `moonshotai/Kimi-K2-Instruct` EAGLE3 training example using `slurm`. + +### ⭐ Offline BF16 EAGLE3 Training +Unlike online EAGLE3 training, offline workflow precomputes target model `hidden_states` and dumps to disk. +Then only the draft model is called during training. AL is no longer reported during training. After training, +`export.sh` is used to export EAGLE3 checkpoint. + +```sh +\ + # Convert to online eagle3 model for base model feature extraction + HF_MODEL_CKPT= \ + MLM_MODEL_SAVE=/tmp/Llama-3.2-1B-Eagle3 \ + MLM_EXTRA_ARGS="--algorithm eagle3" \ + ./convert.sh meta-llama/Llama-3.2-1B-Instruct + +\ + # Dump base model feature to disk + MLM_MODEL_CKPT=/tmp/Llama-3.2-1B-Eagle3 \ + MLM_EXTRA_ARGS="--output-dir /tmp/offline_data" \ + ./offline_feature_extrach.sh meta-llama/Llama-3.2-1B-Instruct + +\ + # Convert to offline eagle3 model + HF_MODEL_CKPT= \ + MLM_MODEL_SAVE=/tmp/Llama-3.2-1B-Eagle3-offline \ + MLM_EXTRA_ARGS="--algorithm eagle3 --export-offline-model" \ + ./convert.sh meta-llama/Llama-3.2-1B-Instruct + +\ + # Train the offline eagle3 model using extracted features + MLM_MODEL_CKPT=/tmp/Llama-3.2-1B-Eagle3-offline \ + MLM_MODEL_SAVE=/tmp/Llama-3.2-1B-Eagle3-offline \ + MLM_EXTRA_ARGS="--export-offline-model --offline-distillation-data /tmp/offline_data" \ + ./finetune.sh meta-llama/Llama-3.2-1B-Instruct + +\ + # Export the trained eagle3 checkpoint + PP=1 \ + HF_MODEL_CKPT= \ + MLM_MODEL_CKPT=/tmp/Llama-3.2-1B-Eagle3-offline \ + EXPORT_DIR=/tmp/Llama-3.2-1B-Eagle3-Export \ + MLM_EXTRA_ARGS="--export-offline-model" \ + ./export.sh meta-llama/Llama-3.2-1B-Instruct +``` + +### ⭐ Pruning + +Checkout pruning getting started section and guidelines for configuring pruning parameters in the [ModelOpt pruning README](https://github.com/NVIDIA/Model-Optimizer/tree/main/examples/pruning). + +Pruning is supported for GPT and Mamba models in Pipeline Parallel mode. Available pruning dimensions are: + +- `TARGET_FFN_HIDDEN_SIZE` +- `TARGET_HIDDEN_SIZE` +- `TARGET_NUM_ATTENTION_HEADS` +- `TARGET_NUM_QUERY_GROUPS` +- `TARGET_MAMBA_NUM_HEADS` +- `TARGET_MAMBA_HEAD_DIM` +- `TARGET_NUM_MOE_EXPERTS` +- `TARGET_MOE_FFN_HIDDEN_SIZE` +- `TARGET_MOE_SHARED_EXPERT_INTERMEDIATE_SIZE` +- `TARGET_NUM_LAYERS` +- `LAYERS_TO_DROP` (comma separated, 1-indexed list of layer numbers to directly drop) + +Example for depth pruning Qwen3-8B from 36 to 24 layers: + +```sh +PP=1 \ +TARGET_NUM_LAYERS=24 \ +HF_MODEL_CKPT= \ +MLM_MODEL_SAVE=Qwen3-8B-Pruned \ +./prune.sh Qwen/Qwen3-8B +``` + +> [!TIP] +> If number of layers in the model is not divisible by pipeline parallel size (PP), you can configure uneven +> PP by setting `MLM_EXTRA_ARGS="--decoder-first-pipeline-num-layers --decoder-last-pipeline-num-layers "` + +> [!TIP] +> You can reuse pruning scores for pruning same model again to different architectures by setting +> `PRUNE_ARGS="--pruning-scores-path "` + +> [!NOTE] +> When loading pruned M-LM checkpoint for subsequent steps, make sure overwrite the pruned parameters in the +> default `conf/` by setting `MLM_EXTRA_ARGS`. E.g.: for loading above pruned Qwen3-8B checkpoint for mmlu, set: +> `MLM_EXTRA_ARGS="--num-layers 24"` + +### ⭐ Inference and Training + +The saved Megatron-LM distributed checkpoint (output of above scripts) can be resumed for inference +(generate or evaluate) or training (SFT or PEFT). To read more about these features, see +[Advanced Topics](./ADVANCED.md). + +```sh +\ + TP=1 \ + MLM_MODEL_CKPT=/tmp/Llama-3.2-1B-Instruct_quant \ + ./generate.sh meta-llama/Llama-3.2-1B-Instruct + +\ + TP=1 \ + MLM_MODEL_CKPT=/tmp/Llama-3.2-1B-Instruct_quant \ + ./mmlu.sh meta-llama/Llama-3.2-1B-Instruct + +\ + TP=1 \ + MLM_MODEL_CKPT=/tmp/Llama-3.2-1B-Instruct_quant \ + ./finetune.sh meta-llama/Llama-3.2-1B-Instruct +``` + +## Advanced Usage +To contribute, please ping [@NVIDIA/post-training](https://github.com/orgs/NVIDIA/teams/post-training) team members. We format the examples with +``` +uvx black@24.10.0 . +uvx isort . +``` diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/conf/arguments.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/conf/arguments.sh new file mode 100644 index 0000000000000000000000000000000000000000..826ce312ae33c71cd81a222c30aa4294ee6a2ff4 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/conf/arguments.sh @@ -0,0 +1,108 @@ +#!/bin/bash +set -e + +MLM_MODEL_CFG=${1} + +if [ -z $1 ]; then + printf "${MLM_ERROR} Model configuration name must be provided as the first argument (e.g. 'meta-llama/Llama-3.2-1B-Instruct')\n" + exit 1 +fi + +# Bash coloring +RED='\033[0;31m' +YELLOW='\033[0;33m' +GREEN='\033[0;32m' +BLUE='\033[0;34m' +PURPLE='\033[0;35m' +WHITE='\033[0;37m' + +# Predefined logging +MLM_ERROR="${RED}ERROR: ${WHITE}" +MLM_WARNING="${YELLOW}WARNING:${WHITE}" + +if [ -z ${SANDBOX_ENV_SETUP} ]; then + printf "${MLM_WARNING} ${PURPLE}SANDBOX_ENV_SETUP${WHITE} is not set!\n" +else + source ${SANDBOX_ENV_SETUP} +fi + +if [ -z ${SCRIPT_DIR} ]; then + printf "${MLM_ERROR} Variable ${PURPLE}SCRIPT_DIR${WHITE} must be set!\n" + exit 1 +fi + +if [ -z ${MLM_MODEL_CFG} ]; then + printf "${MLM_ERROR} Variable ${PURPLE}MLM_MODEL_CFG${WHITE} must be set!\n" + exit 1 +fi + +if [ -z ${MLM_ENV_SETUP} ]; then + printf "${MLM_WARNING} Variable ${PURPLE}MLM_ENV_SETUP${WHITE} not set! (only needed when launching with slurm)\n" +else + source ${MLM_ENV_SETUP} +fi + +if [[ -z ${MLM_EXTRA_ARGS} ]]; then + printf "${MLM_WARNING} Use ${PURPLE}MLM_EXTRA_ARGS${WHITE} to provide additional arguments!\n" +fi + +if [ -z ${MLM_WORK_DIR} ]; then + export MLM_WORK_DIR=/tmp/megatron_workspace + printf "${MLM_WARNING} Variable ${PURPLE}MLM_WORK_DIR${WHITE} is set (default: ${MLM_WORK_DIR})!\n" +fi + +if [ -z ${TP} ]; then + TP=1 + printf "${MLM_WARNING} Variable ${PURPLE}TP${WHITE} not set! (default: ${TP})\n" +fi + +if [ -z ${ETP} ]; then + ETP=${TP} + printf "${MLM_WARNING} Variable ${PURPLE}ETP${WHITE} not set! (default: ${ETP})\n" +fi + +if [ -z ${EP} ]; then + EP=1 + printf "${MLM_WARNING} Variable ${PURPLE}EP${WHITE} not set! (default: ${EP})\n" +fi + +if [ -z ${PP} ]; then + PP=1 + printf "${MLM_WARNING} Variable ${PURPLE}PP${WHITE} not set! (default: ${PP})\n" +fi + +if [ -z ${CP} ]; then + CP=1 + printf "${MLM_WARNING} Variable ${PURPLE}CP${WHITE} not set! (default: ${CP})\n" +fi + +if [ -z ${DP} ]; then + DP=1 + printf "${MLM_WARNING} Variable ${PURPLE}DP${WHITE} not set! (default: ${DP})\n" +fi + + +if [ -z ${LAUNCH_SCRIPT} ]; then + LAUNCH_SCRIPT="torchrun --nproc_per_node=$((ETP * EP * PP * CP * DP))" +fi + +# Install Model Optimizer if haven't. +if [ -z ${MLM_SKIP_INSTALL} ]; then + pip install -r ${SCRIPT_DIR}/requirements.txt +fi + +export TOKENIZERS_PARALLELISM=False +export OMP_NUM_THREADS=1 +export NCCL_IB_SL=1 +export NCCL_IB_TIMEOUT=22 +export CUDA_DEVICE_MAX_CONNECTIONS=1 + +# TE specific warning +printf "${MLM_WARNING} If you see core_attention _extra_state missing error, use --export-force-local-attention\n" + +# Base model specific arguments +if [ -z ${SANDBOX_ROOT} ]; then + source "${SCRIPT_DIR}/conf/${MLM_MODEL_CFG}.sh" +else + source "${SANDBOX_ROOT}/conf/model/${MLM_MODEL_CFG}.sh" +fi diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/conf/moonshotai/Kimi-K2-Instruct.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/conf/moonshotai/Kimi-K2-Instruct.sh new file mode 100644 index 0000000000000000000000000000000000000000..c1be517894d22faffa7b0b422293c75dcfdf0d15 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/conf/moonshotai/Kimi-K2-Instruct.sh @@ -0,0 +1,60 @@ +#!/bin/bash + +TOKENIZER_MODEL="moonshotai/Kimi-K2-Instruct" + + +MODEL_ARGS=" \ + --save-interval 100000 \ + --micro-batch-size 1 \ + --bf16 \ + --no-masked-softmax-fusion \ + --disable-bias-linear \ + --untie-embeddings-and-output-weights \ + --position-embedding-type rope \ + --no-rope-fusion \ + --normalization RMSNorm \ + --swiglu \ + --num-layers 61 \ + --hidden-size 7168 \ + --ffn-hidden-size 18432 \ + --num-attention-heads 64 \ + --kv-channels 128 \ + --multi-latent-attention \ + --kv-lora-rank 512 \ + --v-head-dim 128 \ + --q-lora-rank 1536 \ + --qk-head-dim 128 \ + --qk-layernorm \ + --qk-pos-emb-head-dim 64 \ + --num-experts 384 \ + --moe-layer-freq [0]*1+[1]*60 \ + --moe-ffn-hidden-size 2048 \ + --moe-router-dtype fp32 \ + --moe-router-score-function sigmoid \ + --moe-router-bias-update-rate 1e-3 \ + --moe-router-enable-expert-bias \ + --moe-router-topk 8 \ + --moe-router-pre-softmax \ + --moe-router-topk-scaling-factor 2.827 \ + --moe-shared-expert-overlap \ + --moe-shared-expert-intermediate-size 2048 \ + --moe-aux-loss-coeff 1e-4 \ + --moe-router-load-balancing-type seq_aux_loss \ + --moe-token-dispatcher-type alltoall \ + --moe-token-drop-policy probs \ + --seq-length 4096 \ + --max-position-embeddings 131072 \ + --tokenizer-type HuggingFaceTokenizer \ + --make-vocab-size-divisible-by 1 \ + --use-mcore-models \ + --rotary-base 50000 \ + --rotary-percent 1.0 \ + --rotary-scaling-factor 32 \ + --mscale 1.0 \ + --mscale-all-dim 1.0 \ + --padded-vocab-size 163840 \ + --recompute-activations \ + --moe-layer-recompute \ + --sequence-parallel \ + --trust-remote-code \ +" diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/conf/moonshotai/kimi_k2_instruct.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/conf/moonshotai/kimi_k2_instruct.sh new file mode 100644 index 0000000000000000000000000000000000000000..4f301f31c1d12cb5aab0a26fe508e78d71293603 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/conf/moonshotai/kimi_k2_instruct.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +HF_MODEL_CKPT=/workspace/scratch/moonshotai/Kimi-K2-Instruct +TP=8 +ETP=1 +EP=64 + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/conf/moonshotai/kimi_k2_instruct_export.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/conf/moonshotai/kimi_k2_instruct_export.sh new file mode 100644 index 0000000000000000000000000000000000000000..73ee80a6d931793230b1e548a08a68fa0cd74345 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/conf/moonshotai/kimi_k2_instruct_export.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +HF_MODEL_CKPT=/workspace/scratch/moonshotai/Kimi-K2-Instruct + +MLM_EXTRA_ARGS=" \ + --decoder-first-pipeline-num-layers 3 \ + --decoder-last-pipeline-num-layers 2 \ + --init-model-with-meta-device \ + --use-cpu-initialization \ + +" + +# Layer distribution over PP: 3, [4] * 14, 2. +PP=16 + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/convert.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/convert.sh new file mode 100644 index 0000000000000000000000000000000000000000..9dbe27da5419ba77a9d808ab8296dc6ab32986f8 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/convert.sh @@ -0,0 +1,51 @@ +#!/bin/bash + +SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" + +# Common arguments and base model specific arguments +source "${SCRIPT_DIR}/conf/arguments.sh" + +# Default arguments of this script +MLM_DEFAULT_ARGS=" + --distributed-timeout-minutes 60 \ + --finetune \ + --auto-detect-ckpt-format \ + --export-te-mcore-model \ +" + +if [ -z ${HF_TOKEN} ]; then + printf "${MLM_WARNING} Variable ${PURPLE}HF_TOKEN${WHITE} is not set! HF snapshot download may fail!\n" +fi + +if [ -z ${MLM_MODEL_SAVE} ]; then + MLM_MODEL_SAVE=${MLM_WORK_DIR}/${MLM_MODEL_CFG}_mlm + printf "${MLM_WARNING} Variable ${PURPLE}MLM_MODEL_SAVE${WHITE} is not set (default: ${MLM_MODEL_SAVE})!\n" +fi + + +if [ -z ${MLM_MODEL_CKPT} ]; then + if [ -z ${HF_MODEL_CKPT} ]; then + HF_MODEL_CKPT=${1} + fi + ${LAUNCH_SCRIPT} ${SCRIPT_DIR}/convert_model.py \ + ${MODEL_ARGS} \ + --tensor-model-parallel-size ${TP} \ + --expert-tensor-parallel-size ${ETP} \ + --pipeline-model-parallel-size ${PP} \ + --expert-model-parallel-size ${EP} \ + --tokenizer-model ${TOKENIZER_MODEL} \ + --pretrained-model-path ${HF_MODEL_CKPT} \ + --save ${MLM_MODEL_SAVE} \ + ${MLM_DEFAULT_ARGS} ${MLM_EXTRA_ARGS} +else + ${LAUNCH_SCRIPT} ${SCRIPT_DIR}/convert_model.py \ + ${MODEL_ARGS} \ + --tensor-model-parallel-size ${TP} \ + --expert-tensor-parallel-size ${ETP} \ + --pipeline-model-parallel-size ${PP} \ + --expert-model-parallel-size ${EP} \ + --tokenizer-model ${TOKENIZER_MODEL} \ + --load ${MLM_MODEL_CKPT} \ + --save ${MLM_MODEL_SAVE} \ + ${MLM_DEFAULT_ARGS} ${MLM_EXTRA_ARGS} +fi diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/convert_model.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/convert_model.py new file mode 100644 index 0000000000000000000000000000000000000000..eaec9789e1e2dfe0038f0e84afc6ca015d4a5390 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/convert_model.py @@ -0,0 +1,182 @@ +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. + +"""Convert a GPTModel.""" +import functools +import inspect +import json +import os +import sys +import warnings + +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))) + +import modelopt.torch.speculative as mtsp +import torch +from modelopt.torch.export import import_mcore_gpt_from_hf + +from megatron.core import mpu +from megatron.core.enums import ModelType +from megatron.core.parallel_state import destroy_model_parallel +from megatron.post_training.arguments import add_modelopt_args +from megatron.post_training.checkpointing import load_modelopt_checkpoint +from megatron.post_training.model_builder import modelopt_gpt_mamba_builder +from megatron.post_training.utils import ( + report_current_memory_info, + to_empty_if_meta, +) +from megatron.training import get_args +from megatron.training.checkpointing import save_checkpoint +from megatron.training.initialize import initialize_megatron +from megatron.training.utils import print_rank_0, unwrap_model +from model_provider import model_provider + +ALGO_TO_CONFIG = { + "eagle3": mtsp.config.EAGLE3_DEFAULT_CFG, + "eagle-mtp": mtsp.config.EAGLE_MTP_DEFAULT_CFG, +} + + +def add_convert_args(parser): + """Add additional arguments for ModelOpt checkpoint convertion.""" + group = parser.add_argument_group(title='ModelOpt MCore checkpoint convertion') + group.add_argument( + "--pretrained-model-path", type=str, default=None, help="HuggingFace pretrained model" + ) + group.add_argument( + "--extra-model-path", type=str, default=None, help="Extra module weights to load" + ) + group.add_argument( + '--algorithm', + type=str, + choices=["eagle3", "None"], + default="None", + help='Chosing between different speculative decoding algorithms. Default is None.', + ) + group.add_argument( + "--eagle-config", + type=str, + default=None, + help="EAGLE architecture config. If not given, " + "a default config will be use. If provided, it will overwrite the default config.", + ) + group.add_argument( + "--mix-hidden-states", + type=bool, + default=False, + help="Whether to mix hidden states from previous TTT step.", + ) + + add_modelopt_args(parser) + return parser + + +def get_model(model_provider_func, model_type=ModelType.encoder_or_decoder, wrap_with_ddp=True): + """Build the model.""" + args = get_args() + args.model_type = model_type + pre_process = mpu.is_pipeline_first_stage() + post_process = mpu.is_pipeline_last_stage() + + if args.init_model_with_meta_device: + with torch.device("meta"): + model = model_provider_func(pre_process=pre_process, post_process=post_process) + to_empty_if_meta(model, device="cuda") + else: + model = model_provider_func(pre_process=pre_process, post_process=post_process) + + model.model_type = model_type + return [model] + + +def check_arguments(): + """Checking user arguments.""" + args = get_args() + if args.num_layers_per_virtual_pipeline_stage is not None: + print_rank_0("Interleaved pipeline schedule is not yet supported for text generation.") + exit() + + if hasattr(args, 'moe_grouped_gemm') and args.moe_grouped_gemm == True: + if not getattr(args, 'export_default_te_spec', False): + print_rank_0("WARNING: Forcing moe_grouped_gemm to False for PTQ and export.") + args.moe_grouped_gemm = False + + +if __name__ == "__main__": + initialize_megatron( + extra_args_provider=add_convert_args, + args_defaults={ + 'tokenizer_type': 'HuggingFaceTokenizer', + 'no_load_rng': True, + 'no_load_optim': True, + }, + ) + check_arguments() + + args = get_args() + + # Meta device initialization for ParallelLinear only works if using cpu initialization. + # Meta device initialization is used such that models can be materialized in low-precision + # directly when ModelOpt real quant is used. Otherwise, the model is first initialized + # as BF16 in memory which may result in OOM and defeat the purpose of real quant. + if args.init_model_with_meta_device: + args.use_cpu_initialization = True + else: + warnings.warn( + "--init-model-with-meta-device is not set. If you would like to resume the " + "model in low-bit directly (low-memory initialization and skipping 16-bit), " + "--init-model-with-meta-device must be set.", + UserWarning, + ) + + model = get_model( + functools.partial(model_provider, modelopt_gpt_mamba_builder), wrap_with_ddp=False + ) + report_current_memory_info() + + unwrapped_model = unwrap_model(model)[0] + + if args.pretrained_model_path is not None: + import_dtype = torch.float16 if args.fp16 else torch.bfloat16 + unwrapped_model = unwrap_model(model)[0] + workspace_dir = os.environ.get("MLM_WORK_DIR", "/tmp") + print_rank_0( + "Import model from Hugging Face checkpoint in dtype {}.".format(str(import_dtype)) + ) + import_kwargs = { + "dtype": import_dtype, + "moe_router_dtype": args.moe_router_dtype, + } + if "trust_remote_code" in inspect.signature(import_mcore_gpt_from_hf).parameters: + import_kwargs.update({"trust_remote_code": args.trust_remote_code}) + import_mcore_gpt_from_hf( + unwrapped_model, args.pretrained_model_path, workspace_dir, **import_kwargs + ) + elif args.load is not None: + _ = load_modelopt_checkpoint(model) + + if args.algorithm == "eagle3": + mtsp_config = ALGO_TO_CONFIG[args.algorithm] + if args.eagle_config: + with open(args.eagle_config) as f: + eagle_config = json.load(f) + mtsp_config["config"]["eagle_architecture_config"].update(eagle_config) + + if args.export_offline_model: + mtsp_config["config"]["eagle_offline"] = True + if args.mix_hidden_states: + mtsp_config["config"]["eagle_mix_hidden_states"] = True + + unwrapped_model = mtsp.convert(unwrapped_model, mtsp_config) + + if args.extra_model_path is not None: + eagle_module = getattr(unwrapped_model, "eagle_module", None) + if eagle_module is not None: + mcore_eagle_state_dict = torch.load(args.extra_model_path) + eagle_module.load_state_dict(mcore_eagle_state_dict, strict=False) + + print_rank_0(f"Converted Model:\n {model}") + torch.distributed.barrier() + + save_checkpoint(1, model, None, None, 0, release=True) + + destroy_model_parallel() diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/distillation.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/distillation.md new file mode 100644 index 0000000000000000000000000000000000000000..49f73c4edde4c3c89309fa916140cddea8c817a6 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/distillation.md @@ -0,0 +1,96 @@ +# Megatron-LM ModelOpt Distillation Integration + +## How To + +### Prerequisites + +In order to perform soft-label Knowledge Distillation between two models on a specific dataset, +we take a larger teacher model which has already been fully trained and use its logits as +labels for a smaller student model. + +We require the following pieces of data: +* Teacher model weights +* Student model weights (unless starting from scratch) +* NeMo-format config file for teacher model +* Tokenizer +* Dataset + +And optionally: +* Distillation run config file + +### Teacher checkpoint format + +We enforce the use of a config yaml in [NeMo](https://github.com/NVIDIA/NeMo) checkpoint-format style to define the arguments to the teacher model. +The normal command-line arguments go toward constructing the student, thus the values in this file +override the student arguments before being handed to the teacher constructor. This file must be either passed in via +`--export-kd-teacher-model-config` or be named `model_config.yaml` in the root of the teacher model checkpoint folder. +Unlike NeMo-generated checkpoints, Megatron-LM checkpoints do not contain this file by default and must be manually created. + +> NOTE: Not all keys in the NeMo-style yaml correspond 1:1 to the argument names for Megatron-LM. These +are converted in `megatron/post_training/model_builder.py`. + +### Distillation config format + +Configuring the distillation run is done via a separate YAML file with the following fields: + +```yaml +logit_layers: ["output_layer", "output_layer"] +intermediate_layer_pairs: + - ["decoder.layers.0.input_layernorm", "decoder.layers.0.input_layernorm"] + - ["decoder.final_layernorm", "decoder.layers.30.input_layernorm"] +skip_lm_loss: true +kd_loss_scale: 10.0 +logit_kl_temperature: 1.0 +``` + +* `logit_layers` defines the names of the student and teacher submodules, respectively, whose outputs are the logits. +* `intermediate_layer_pairs` defines the potentially multiple – or zero – pairs of intermediate activation layers to also perform loss on. +* `skip_lm_loss` decides whether or not to compute and combine the original training LM loss with the KD loss. +* `kd_loss_scale` will scale the KD loss before adding it to the LM loss, if `skip_lm_loss` is `False`. +* `logit_kl_temperature` is the temperature smoothing factor to multiply the logits by prior to softmax and loss. + +Without this configuration file, the default logits-only distillation with scale and temperatures of 1.0 will be performed. + +### Training + +Distillation is triggered by calling `pretrain_gpt.py` or `pretrain_mamba.py` with the following arguments: + +```bash +--export-kd-teacher-load +--export-te-mcore-model +``` + +optionally alongside the additional following arguments: + +```bash +--export-kd-distill-cfg +--export-kd-teacher-model-config +``` + +> NOTE: If the teacher checkpoint happens to be in a different format from the student's (whose format is specified via `--ckpt-format`), it can +be distinguished separately using the additional flag `--export-kd-teacher-ckpt-format`. + +## Distillation API and design + +Knowledge Distillation is done via the [NVIDIA Model Optimizer library](https://github.com/NVIDIA/Model-Optimizer). + +The model creation step wraps the base model as the student in a +`modelopt.torch.distill.DistillationModel` wrapper which also contains the teacher model. + +Model Optimizer modifies the model using the loss criterion present in the distillation config yaml file, which +defines a loss function between two module attribute names of the teacher and student model, respectively. + +Default loss function used between logits is a KL-Divergence Loss and loss used among intermediate tensors is Cosine-Similarity, +both defined in `modelopt.torch.distill.plugins.megatron`. + +## Restrictions + +* Interleaved Pipeline Parallel is unsupported for Distillation. + +## Known Issues + +* An unknown memory allocation (a few megabytes per microbatch) takes place when the model is converted to a +`modelopt.torch.distill.DistillationModel`. If `--manual-gc` is enabled, it can easily lead to an OOM after some iterations. + +* A CUDA kernel issue is occurring where student's forward latency is severly prolonged compared to running student forward +without a teacher model. This means the total time per iteration may be up to 40% longer than ideally expected. diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/eagle3.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/eagle3.sh new file mode 100644 index 0000000000000000000000000000000000000000..c560b1d3a932e14eb98771a87c618cd016950f5c --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/eagle3.sh @@ -0,0 +1,103 @@ +#!/bin/bash + +SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" + +# Common arguments and base model specific arguments +source "${SCRIPT_DIR}/conf/arguments.sh" + + +# Set up cache dir for HF to avoid out of space error +export HF_DATASETS_CACHE="/tmp/hf_datasets_cache" + +# Extra arguments of this script +MLM_DEFAULT_ARGS=" \ + --distributed-timeout-minutes 30 \ + --auto-detect-ckpt-format \ + --export-te-mcore-model \ + --finetune \ +" + +EAGLE3_CONVERT_ARGS=" \ + --algorithm eagle3 \ +" + +if [ -z ${MLM_MODEL_SAVE} ]; then + MLM_MODEL_SAVE=${MLM_WORK_DIR}/${MLM_MODEL_CFG}-Eagle3 + printf "${MLM_WARNING} Variable ${PURPLE}MLM_MODEL_SAVE${WHITE} is not set (default: ${MLM_MODEL_SAVE})!\n" +fi + +if [ -z ${MLM_DATA_ARGS} ]; then + MLM_DATA_ARGS=" \ + --train-samples 128000 \ + --lr-decay-samples 128000 \ + --lr-warmup-samples 0 \ + --split 100,0,0 \ + --finetune-hf-dataset Magpie-Align/Magpie-Llama-3.1-Pro-MT-300K-Filtered \ + " +fi + +if [ -z ${MLM_TRAIN_ARGS} ]; then + MLM_TRAIN_ARGS=" \ + --no-gradient-accumulation-fusion \ + --reset-position-ids \ + --reset-attention-mask \ + --eod-mask-loss \ + --micro-batch-size 1 \ + --attention-dropout 0.0 \ + --hidden-dropout 0.0 \ + --no-check-for-nan-in-loss-and-grad \ + " +fi + +if [ -z ${MLM_OPTIM_ARGS} ]; then + MLM_OPTIM_ARGS=" \ + --lr 5.0e-5 \ + --min-lr 1.0e-7 \ + --lr-decay-style cosine \ + --clip-grad 1.0 \ + --weight-decay 0.0 \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --init-method-std 0.010 \ + " +fi + +if [ -z ${MLM_EVAL_ARGS} ]; then + MLM_EVAL_ARGS=" \ + --eval-iters 1 \ + --eval-interval 1000 \ + --save-interval 1000 \ + --log-interval 100 \ + " +fi + +# Convert HF checkpoint to Megatron EAGLE3 model if not exist +if [[ ! -d ${MLM_MODEL_SAVE} ]]; then + ${LAUNCH_SCRIPT} ${SCRIPT_DIR}/convert_model.py \ + ${MODEL_ARGS} \ + --tensor-model-parallel-size ${TP} \ + --expert-tensor-parallel-size ${ETP} \ + --pipeline-model-parallel-size ${PP} \ + --expert-model-parallel-size ${EP} \ + --tokenizer-model ${TOKENIZER_MODEL} \ + --pretrained-model-path ${HF_MODEL_CKPT} \ + --save ${MLM_MODEL_SAVE} \ + ${MLM_DEFAULT_ARGS} ${EAGLE3_CONVERT_ARGS} +fi + + +${LAUNCH_SCRIPT} ${SCRIPT_DIR}/finetune.py \ + ${MODEL_ARGS} \ + --tensor-model-parallel-size ${TP} \ + --expert-tensor-parallel-size ${ETP} \ + --expert-model-parallel-size ${EP} \ + --pipeline-model-parallel-size ${PP} \ + --tokenizer-model ${TOKENIZER_MODEL} \ + --load ${MLM_MODEL_SAVE} \ + --save ${MLM_MODEL_SAVE} \ + ${MLM_DATA_ARGS} \ + ${MLM_OPTIM_ARGS} \ + ${MLM_TRAIN_ARGS} \ + ${MLM_EVAL_ARGS} \ + ${MLM_RESUME_ARGS} \ + ${MLM_DEFAULT_ARGS} ${MLM_EXTRA_ARGS} diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/export.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/export.py new file mode 100644 index 0000000000000000000000000000000000000000..5e3b2a1716e97f8c107d39f12ef03ae18f71f09b --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/export.py @@ -0,0 +1,109 @@ +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. + +"""Export a GPTModel.""" +import functools +import inspect +import os +import sys +import warnings +from pathlib import Path + +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))) + +import modelopt.torch.export as mtex +import torch + +from megatron.post_training.arguments import add_modelopt_args +from megatron.post_training.checkpointing import load_modelopt_checkpoint +from megatron.post_training.model_builder import modelopt_gpt_mamba_builder +from megatron.training import get_args, get_model +from megatron.training.initialize import initialize_megatron +from megatron.training.utils import unwrap_model +from model_provider import model_provider + +warnings.filterwarnings('ignore') + + +def add_modelopt_export_args(parser): + """Add additional arguments for ModelOpt hf-like export.""" + group = parser.add_argument_group(title='ModelOpt hf-like export') + group.add_argument( + "--export-extra-modules", + action="store_true", + help="Export extra modules such as Medusa, EAGLE, or MTP.", + ) + group.add_argument( + "--pretrained-model-name", + type=str, + help="A pretrained model hosted inside a model repo on huggingface.co.", + ) + group.add_argument( + "--export-vllm-fq", + action="store_true", + default=False, + help="Export the model for vLLM fakequant reload.", + ) + group.add_argument("--export-dir", type=str, help="The target export path.") + add_modelopt_args(parser) + return parser + + +if __name__ == "__main__": + initialize_megatron( + extra_args_provider=add_modelopt_export_args, + args_defaults={ + 'tokenizer_type': 'HuggingFaceTokenizer', + 'no_load_rng': True, + 'no_load_optim': True, + }, + ) + + args = get_args() + + # Meta device initialization for ParallelLinear only works if using cpu initialization. + # Meta device initialization is used such that models can be materialized in low-precision + # directly when ModelOpt real quant is used. Otherwise, the model is first initialized + # as BF16 in memory which may result in OOM and defeat the purpose of real quant. + args.use_cpu_initialization = True + if not args.init_model_with_meta_device: + warnings.warn( + "--init-model-with-meta-device is not set. If you would like to resume the " + "model in low-bit directly (low-memory initialization and skipping 16-bit), " + "--init-model-with-meta-device must be set.", + UserWarning, + ) + + model = get_model( + functools.partial(model_provider, modelopt_gpt_mamba_builder), wrap_with_ddp=False + ) + + # Materialize the model from meta device to cpu before loading the checkpoint. + unwrapped_model = unwrap_model(model)[0] + unwrapped_model.to_empty(device="cpu") + + if args.load is not None and Path(args.load).is_dir(): + _ = load_modelopt_checkpoint(model) + else: + raise ValueError(f"Invalid load checkpoint directory: {args.load}") + + + # Decide whether we are exporting only the extra_modules (e.g. EAGLE3). + # Only the last pp stage may have extra_modules, hence broadcast from the last rank. + export_extra_modules = hasattr(unwrapped_model, "eagle_module") or hasattr( + unwrapped_model, "medusa_heads" + ) + torch.distributed.broadcast_object_list( + [export_extra_modules], src=torch.distributed.get_world_size() - 1 + ) + + export_kwargs = { + "export_extra_modules": export_extra_modules, + "dtype": torch.bfloat16, + "export_dir": args.export_dir, + "moe_router_dtype": unwrapped_model.config.moe_router_dtype, + } + if "trust_remote_code" in inspect.signature(mtex.export_mcore_gpt_to_hf).parameters: + export_kwargs.update({"trust_remote_code": args.trust_remote_code}) + + export_fn = mtex.export_mcore_gpt_to_hf_vllm_fq if args.export_vllm_fq else mtex.export_mcore_gpt_to_hf + export_fn(unwrapped_model, args.pretrained_model_name, **export_kwargs) diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/export.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/export.sh new file mode 100644 index 0000000000000000000000000000000000000000..d0f0b97f2a0215f41b54b33e42192e5bd351465d --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/export.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" + +# Common arguments and base model specific arguments +source "${SCRIPT_DIR}/conf/arguments.sh" + +# Default arguments of this script +MLM_DEFAULT_ARGS="--finetune --auto-detect-ckpt-format --export-te-mcore-model --use-cpu-initialization" + +if [ -z ${HF_MODEL_CKPT} ]; then + HF_MODEL_CKPT=${1} +fi + +if [ -z ${HF_TOKEN} ]; then + printf "${MLM_WARNING} Variable ${PURPLE}HF_TOKEN${WHITE} is not set! Pretrained config download may fail!\n" +fi + +if [ -z ${EXPORT_DIR} ]; then + EXPORT_DIR=${MLM_WORK_DIR}/${MLM_MODEL_CFG}_export + printf "${MLM_WARNING} Variable ${PURPLE}EXPORT_DIR${WHITE} is not set (default: ${EXPORT_DIR})!\n" +fi + +if [ "${TP}" != "1" ]; then + TP=1 + printf "${MLM_WARNING} Variable ${PURPLE}TP${WHITE} is forced to be 1 during export!!\n" +fi + + +${LAUNCH_SCRIPT} ${SCRIPT_DIR}/export.py \ + ${MODEL_ARGS} \ + --tensor-model-parallel-size ${TP} \ + --pipeline-model-parallel-size ${PP} \ + --tokenizer-model ${TOKENIZER_MODEL} \ + --load ${MLM_MODEL_CKPT} \ + --pretrained-model-name ${HF_MODEL_CKPT} \ + --export-dir ${EXPORT_DIR} \ + ${MLM_DEFAULT_ARGS} ${MLM_EXTRA_ARGS} diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/finetune.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/finetune.py new file mode 100644 index 0000000000000000000000000000000000000000..f7f7c24f97046e8e5508056cd8c415c69ce0c506 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/finetune.py @@ -0,0 +1,495 @@ +# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. + +"""Supervised Finetuning GPT.""" +import itertools +import json +import os +import sys +from functools import partial +from typing import Any, Dict, Optional + +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))) + +import datasets +import torch +import transformers + +from megatron.core import mpu, tensor_parallel +from megatron.core.enums import ModelType +from megatron.core.models.gpt import GPTModel +from megatron.post_training.arguments import add_modelopt_args +from megatron.post_training.loss_func import loss_func +from megatron.post_training.model_builder import modelopt_gpt_mamba_builder +from megatron.post_training.non_loss_data_func import report_draft_acceptance_length +from megatron.training import get_args, get_timers, pretrain +from megatron.training.utils import ( + get_batch_on_this_cp_rank, + get_ltor_masks_and_position_ids, + print_rank_0, +) +from utils import get_hf_tokenizer +from model_provider import model_provider + +REMOVE_THINK_CHAT_TEMPLATE = ( + "{% if '' in content %}{% set content = content.split('')[-1] %}{% endif %}" +) + + +def add_finetune_args(parser): + """Add additional arguments for finetune.""" + group = parser.add_argument_group(title='Finetune') + group.add_argument("--offline-distillation-data", type=str, help="Path to the offline dataset directory with base model features.") + + + add_modelopt_args(parser) + return parser + +def get_eos_id(): + """Return the eos token id. + + We insert eos_token between two samples during packing. However, if the eos_token is used in message or after turns, + we need to replace it with some other special tokens that do not appear in message.""" + hf_tokenizer = get_hf_tokenizer() + + if hf_tokenizer.eos_token == "<|eot_id|>": + return 128001 + if hf_tokenizer.eos_token == "<|eot|>": + return 200001 + if hf_tokenizer.eos_token == "<|im_end|>": + return 151643 + if hf_tokenizer.eos_token == "<|return|>": + return 199999 + + return hf_tokenizer.eos_token_id + + +class OfflineDataset(torch.utils.data.Dataset): + def __init__(self, data_dir: str, num_samples): + self.data_dir = data_dir + self.num_samples = num_samples + self.file_paths = [] + + for item in os.listdir(data_dir): + item_path = os.path.join(data_dir, item) + if os.path.isfile(item_path): + self.file_paths.append(item_path) + + def __len__(self): + return self.num_samples + + def __getitem__(self, idx): + idx = idx % len(self.file_paths) + file_path = self.file_paths[idx] + sample = torch.load(file_path) + return sample + +class SFTDataset(torch.utils.data.Dataset): + + hf_dataset_to_kwargs = { + "Open-Orca/OpenOrca": {"split": "train"}, + "Open-Orca/SlimOrca": {"split": "train"}, + "nvidia/Daring-Anteater": {"split": "train"}, + "Magpie-Align/Magpie-Llama-3.1-Pro-MT-300K-Filtered": {"split": "train"}, + "HuggingFaceH4/ultrachat_200k": {"split": "train_sft"}, + } + + hf_dataset_to_conversation = { + "Open-Orca/OpenOrca": lambda data: SFTDataset._to_conversation( + data["question"], data["response"] + ), + "Open-Orca/SlimOrca": lambda data: SFTDataset._sharegpt_to_openai_conversations(data), + "nvidia/Daring-Anteater": lambda data: SFTDataset._sharegpt_to_openai_conversations(data), + "Magpie-Align/Magpie-Llama-3.1-Pro-MT-300K-Filtered": lambda data: SFTDataset._sharegpt_to_openai_conversations( + data + ), + } + + hf_dataset_to_prompt_template = { + "Open-Orca/OpenOrca": "{{ messages['question'] + ' ' + messages['response'] + ' ' }}", + } + + @classmethod + def _wildcard_get(cls, directory: Dict[str, Any], name: str, default_value=None): + ret = default_value + for key, val in directory.items(): + if key in name: + ret = val + break + return ret + + def __init__( + self, + num_packed_samples: int, + hf_dataset: str, + tokenizer: transformers.PreTrainedTokenizerBase, + seq_length: int, + num_shards: int = 1, + shard_index: int = 0, + ): + """A simple dataset implementation for supervised fine-tuning. + + The raw data is processed and packed to an indexed dataset on the fly. Users + specify the total number of packed samples and the dataloader (or sampler) + access the packed dataset by indices. When the packed dataset length is smaller + than the index, the packing process fetches the raw data in a cyclic fashion + until the packed dataset has sufficient length. + + Args: + num_packed_samples: total number of packed samples (cyclic access) + hf_dataset: Huggingface dataset name or local path + tokenizer: Huggingface PreTrainedTokenizer instance + seq_length: max sequence length + num_shards: number of shards for distributed training + shard_index: shard index for distributed training + """ + if not isinstance(tokenizer, transformers.PreTrainedTokenizerBase): + raise ValueError("SFTDataset only supports transformers.PreTrainedTokenizerBase!") + + self.num_packed_samples = num_packed_samples + self.hf_dataset = hf_dataset + self.tokenizer = tokenizer + self.seq_length = seq_length + self.data_transformation = lambda data: data + self.num_shards = num_shards + self.shard_index = shard_index + self.indexed_dataset = [] + self._raw_sample_index = 0 + + # [WAR]: For DeepSeek-V3/R1 tokenizer, we modify the chat_template such that the + # tokens are preserved for supervised learning. + self.tokenizer.chat_template = self.tokenizer.chat_template.replace( + REMOVE_THINK_CHAT_TEMPLATE, "" + ) + + hf_dataset_kwargs = SFTDataset.hf_dataset_to_kwargs.get( + self.hf_dataset, {"split": "train"} + ) + self._raw_samples = datasets.load_dataset(self.hf_dataset, token=os.environ.get("HF_TOKEN", None), **hf_dataset_kwargs) + self._raw_samples = self._raw_samples.shard( + num_shards=self.num_shards, index=shard_index + ) + + print( + "Rank {:3}/{:3} creates SFT data shard {:3}/{:3} with {:10} raw samples".format( + torch.distributed.get_rank(), + torch.distributed.get_world_size(), + self.shard_index, + self.num_shards, + len(self._raw_samples), + ), + flush=True, + ) + + if self.tokenizer.chat_template is None: + self.tokenizer.chat_template = SFTDataset.hf_dataset_to_prompt_template + elif self.hf_dataset is not None: + self.data_transformation = SFTDataset._wildcard_get( + SFTDataset.hf_dataset_to_conversation, + self.hf_dataset, + default_value=lambda data: data, + ) + + if self.tokenizer.chat_template is None: + raise ValueError("No valid chat template!") + + def __len__(self): + return self.num_packed_samples + + def __getitem__(self, idx): + """Get the idx packed data. + + The packed data index is different from the raw data index where a packed sample + of sequence-length may require concatenting multiple raw data. When all raw data + are used up, the last packed data is throw away, and we have a packed dataset + in memory. The packed data index may exceed the length of the packed dataset + which will just wrap in a cyclic fashion. + """ + idx = idx // self.num_shards + + while idx >= len(self.indexed_dataset): + packed_samples = self._process_and_pack_example() + if packed_samples is None: + break + else: + self.indexed_dataset.append(packed_samples) + if len(self.indexed_dataset) % 10000 == 0: + print( + "Rank {:3}/{:3} requests {:10}/{:10} packed SFT sample".format( + torch.distributed.get_rank(), + torch.distributed.get_world_size(), + idx, + len(self.indexed_dataset), + ), + flush=True, + ) + + idx = idx % len(self.indexed_dataset) + torch_sample = {} + for key, val in self.indexed_dataset[idx].items(): + torch_sample[key] = torch.LongTensor(val) + return torch_sample + + def _process_and_pack_example(self): + """Process multiple raw data and pack them into fixed sequence length.""" + required_packed_tokens = self.seq_length + 1 + current_packed_samples = [] + current_packed_samples_token_count = 0 + + while current_packed_samples_token_count < required_packed_tokens: + if self._raw_sample_index >= len(self._raw_samples): + return None + raw_sample = self._raw_samples[self._raw_sample_index] + self._raw_sample_index += 1 + processed_sample = self._process_example(raw_sample) + if processed_sample is not None: + current_packed_samples.append(processed_sample) + current_packed_samples_token_count += processed_sample["token_count"] + + packed_samples = {} + + for key in ['input_ids', 'loss_mask']: + packed_samples[key] = list( + itertools.chain.from_iterable([obj[key] for obj in current_packed_samples]) + ) + + for key in ['token_count']: + packed_samples[key] = [obj[key] for obj in current_packed_samples] + + return packed_samples + + def _process_example(self, example: Dict[str, Any]): + """Apply the chat template and compute the answer-only loss mask.""" + if not isinstance(example, Dict): + raise ValueError("The sample must be a Dict but got {}".format(type(example))) + + # Several things can happen here after the transformation is applied: + # + # 1. If the transformation is identity transformation, then either the chat data + # is already in OpenAI chat format or there is a custom prompt template used. + # 2. Otherwise, the tokenizer must have a default chat template and we are either + # converting the ShareGPT chat data or standard SFT data to OpenAI chat data. + example = self.data_transformation(example) + + # Check if this is OpenAI chat data? + conversations = example.get("conversations", None) + if conversations is None: + conversations = example.get("messages", None) + + # We don't use the data if there is no assistant reply or the conversation that + # starts with the assistant. + if conversations is not None: + example = conversations + if len(conversations) < 2 or example[0]["role"] == "assistant": + return None + + # We always add eos between samples for training purpose. + input_ids = self.tokenizer.apply_chat_template(example) + current_loss_mask = [1] * len(input_ids) + input_ids = input_ids + [get_eos_id()] + current_loss_mask += [0] + + assert len(input_ids) == len(current_loss_mask) + + if len(input_ids) > self.seq_length: + input_ids = input_ids[: self.seq_length] + current_loss_mask = current_loss_mask[: self.seq_length] + + processed_example = { + 'input_ids': input_ids, + 'loss_mask': current_loss_mask, + 'token_count': len(input_ids), + } + return processed_example + + @classmethod + def _to_conversation(cls, question, response): + msg_question = {"role": "user", "content": question} + msg_response = {"role": "assistant", "content": response} + return {"conversations": [msg_question, msg_response]} + + @classmethod + def _sharegpt_to_openai_conversations(cls, data): + role_mapping = { + "user": "user", + "User": "user", + "human": "user", + "assistant": "assistant", + "Assistant": "assistant", + "gpt": "assistant", + "system": "system", + "System": "system", + } + processed_data = {"conversations": []} + for msg in data["conversations"]: + role = role_mapping[msg["from"]] + content = msg["value"] + processed_data["conversations"].append({"role": role, "content": content}) + return processed_data + + @classmethod + def _special_to_openai_conversations(cls, data): + processed_data = {"conversations": data["input"]["messages"]} + return processed_data + + +def train_valid_test_sft_datasets_provider(train_val_test_num_samples): + """Build the train test and validation datasets. + + Args: + train_val_test_num_samples : A list containing the number of samples + in train test and validation. + """ + print_rank_0("> building train, validation, and test SFT datasets ...") + args = get_args() + hf_tokenizer = get_hf_tokenizer() + if not isinstance(hf_tokenizer, transformers.PreTrainedTokenizerBase): + raise ValueError("SFTDataset only supports transformers.PreTrainedTokenizerBase!") + + if args.micro_batch_size > 1: + raise ValueError("SFTDataloader only supports micro_batch_size=1.") + + if args.export_offline_model: + train_ds = OfflineDataset(os.path.join(args.offline_distillation_data, "train"), train_val_test_num_samples[0]) + valid_ds = OfflineDataset(os.path.join(args.offline_distillation_data, "valid"), train_val_test_num_samples[1]) + test_ds = OfflineDataset(os.path.join(args.offline_distillation_data, "test"), train_val_test_num_samples[2]) + + print_rank_0("> finished creating offline SFT datasets ...") + else: + kwargs = { + "hf_dataset": args.finetune_hf_dataset, + "tokenizer": hf_tokenizer, + "seq_length": args.seq_length, + # Optional kwargs + "num_shards": mpu.get_expert_data_parallel_world_size(), + "shard_index": mpu.get_expert_data_parallel_rank(), + } + + train_ds = SFTDataset(train_val_test_num_samples[0], **kwargs) + valid_ds = SFTDataset(train_val_test_num_samples[1], **kwargs) + test_ds = SFTDataset(train_val_test_num_samples[2], **kwargs) + + print_rank_0("> finished creating SFT datasets ...") + + return train_ds, valid_ds, test_ds + + +def get_batch(data_iterator): + """Generate a batch. + + For OfflineDataset, the aux_hidden_states and final hidden_states from the + base model are loaded for offline speculative model training.""" + # TODO: this is pretty hacky, find a better way + if (not mpu.is_pipeline_first_stage()) and (not mpu.is_pipeline_last_stage()): + return None, None, None, None, None + + args = get_args() + + # Broadcast data since only TP rank-0 has the data_iterator. + if data_iterator is not None: + data = next(data_iterator) + else: + data = None + if not args.export_offline_model: + keys = ["input_ids", "loss_mask"] + datatype = torch.int64 + data_b = tensor_parallel.broadcast_data(keys, data, datatype) + else: + keys = ["input_ids"] + datatype = torch.int64 + data_b = tensor_parallel.broadcast_data(keys, data, datatype) + data_b["loss_mask"] = torch.ones_like(data_b["input_ids"]) + data_b["loss_mask"][data_b["loss_mask"]==get_eos_id()] = 0 + data_b["loss_mask"] = torch.cat([data_b["loss_mask"], torch.zeros(1,1).to(torch.cuda.current_device())], dim=-1) + + keys = ["aux_hidden_states", "hidden_states"] + datatype = torch.bfloat16 + feature_b = tensor_parallel.broadcast_data(keys, data, datatype) + + + # Unpack the data received. + tokens_ = data_b["input_ids"] + tokens = tokens_[:, 0 : 0 + args.seq_length].contiguous() + labels = tokens_[:, 1 : 1 + args.seq_length].contiguous() + answer_only_loss_mask = data_b["loss_mask"][:, 1 : 1 + args.seq_length].contiguous() + + # Get the masks and postition ids. + attention_mask, loss_mask, position_ids = get_ltor_masks_and_position_ids( + tokens, get_eos_id(), get_eos_id(), args.reset_position_ids, args.reset_attention_mask, args.eod_mask_loss, False + ) + loss_mask = loss_mask * answer_only_loss_mask.to(dtype=loss_mask.dtype) + + + labels = labels.contiguous() + loss_mask = loss_mask.contiguous() + + batch = { + "tokens": tokens, + "labels": labels, + "loss_mask": loss_mask, + "attention_mask": attention_mask, + "position_ids": position_ids, + } + + if args.export_offline_model: + batch["aux_hidden_states"] = feature_b["aux_hidden_states"].transpose(0, 1)[:args.seq_length] + batch["hidden_states"] = feature_b["hidden_states"].transpose(0, 1)[:args.seq_length] + + # slice batch along sequence dimension for context parallelism + batch = get_batch_on_this_cp_rank(batch) + + return batch + + +def non_loss_data_func(model: GPTModel): + """Callback to compute the acceptance length.""" + args = get_args() + if not args.export_offline_model and args.context_parallel_size == 1: + try: + report_draft_acceptance_length(model) + except Exception as e: + print(e) + + + +def forward_step(data_iterator, model: GPTModel): + """Forward training step. + + Args: + data_iterator: Input data iterator + model: The GPT Model + """ + timers = get_timers() + + args = get_args() + + # Get the batch. + timers("batch-generator", log_level=2).start() + batch = get_batch(data_iterator) + tokens = batch["tokens"] + labels = batch["labels"] + loss_mask = batch["loss_mask"] + attention_mask = batch["attention_mask"] + position_ids = batch["position_ids"] + if args.export_offline_model: + aux_hidden_states = batch["aux_hidden_states"] + hidden_states = batch["hidden_states"] + timers("batch-generator").stop() + + if args.export_offline_model: + output_tensor = model(tokens, position_ids, attention_mask, labels=labels, aux_hidden_states=aux_hidden_states, hidden_states=hidden_states,) + else: + output_tensor = model(tokens, position_ids, attention_mask, labels=labels) + + return output_tensor, partial(loss_func, loss_mask, model=model) + + +if __name__ == "__main__": + pretrain( + train_valid_test_sft_datasets_provider, + partial(model_provider, modelopt_gpt_mamba_builder), + ModelType.encoder_or_decoder, + forward_step, + extra_args_provider=add_finetune_args, + args_defaults={"tokenizer_type": "HuggingFaceTokenizer"}, + non_loss_data_func=non_loss_data_func, + ) diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/finetune.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/finetune.sh new file mode 100644 index 0000000000000000000000000000000000000000..1affc3c04da5d96abb2f98f9a2c1715fce2fc3c5 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/finetune.sh @@ -0,0 +1,102 @@ +#!/bin/bash + +SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" + +# Common arguments and base model specific arguments +source "${SCRIPT_DIR}/conf/arguments.sh" + + +# Set up cache dir for HF to avoid out of space error +export HF_DATASETS_CACHE="/tmp/hf_datasets_cache" + +# Extra arguments of this script +MLM_DEFAULT_ARGS=" \ + --distributed-timeout-minutes 30 \ + --auto-detect-ckpt-format \ + --export-te-mcore-model \ + --finetune \ +" + + +if [ -z ${MLM_MODEL_SAVE} ]; then + MLM_MODEL_SAVE=${MLM_MODEL_CKPT} + printf "${MLM_WARNING} Variable ${PURPLE}MLM_MODEL_SAVE${WHITE} is not set (default: ${MLM_MODEL_CKPT})!\n" +fi + +if [ -z ${DATASET} ]; then + DATASET="Magpie-Align/Magpie-Llama-3.1-Pro-MT-300K-Filtered" + printf "${MLM_WARNING} Variable ${PURPLE}DATASET${WHITE} is not set (default: Magpie-Align/Magpie-Llama-3.1-Pro-MT-300K-Filtered)!\n" +fi + +if [ -z ${MLM_DATA_ARGS} ]; then + MLM_DATA_ARGS=" \ + --train-samples 128000 \ + --lr-decay-samples 128000 \ + --lr-warmup-samples 0 \ + --split 100,0,0 \ + --finetune-hf-dataset ${DATASET} \ + " +fi + +if [[ -v CP && "$CP" != "1" ]]; then + BACKEND="fused" +else + BACKEND="auto" +fi + +if [ -z ${MLM_TRAIN_ARGS} ]; then + MLM_TRAIN_ARGS=" \ + --no-gradient-accumulation-fusion \ + --reset-position-ids \ + --reset-attention-mask \ + --eod-mask-loss \ + --micro-batch-size 1 \ + --attention-dropout 0.0 \ + --hidden-dropout 0.0 \ + --no-check-for-nan-in-loss-and-grad \ + --attention-backend ${BACKEND} \ + " +fi + +if [ -z ${MLM_OPTIM_ARGS} ]; then + MLM_OPTIM_ARGS=" \ + --lr 5.0e-5 \ + --min-lr 1.0e-7 \ + --lr-decay-style cosine \ + --clip-grad 1.0 \ + --weight-decay 0.0 \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --init-method-std 0.010 \ + --use-distributed-optimizer \ + " +fi + +if [ -z ${MLM_EVAL_ARGS} ]; then + MLM_EVAL_ARGS=" \ + --eval-iters 1 \ + --eval-interval 1000 \ + --save-interval 1000 \ + --log-interval 100 \ + " +fi + +export HF_TOKEN=${HF_TOKEN} + +${LAUNCH_SCRIPT} ${SCRIPT_DIR}/finetune.py \ + ${MODEL_ARGS} \ + --tensor-model-parallel-size ${TP} \ + --expert-tensor-parallel-size ${ETP} \ + --expert-model-parallel-size ${EP} \ + --pipeline-model-parallel-size ${PP} \ + --context-parallel-size ${CP} \ + --cp-comm-type p2p \ + --tokenizer-model ${TOKENIZER_MODEL} \ + --load ${MLM_MODEL_CKPT} \ + --save ${MLM_MODEL_SAVE} \ + ${MLM_DATA_ARGS} \ + ${MLM_OPTIM_ARGS} \ + ${MLM_TRAIN_ARGS} \ + ${MLM_EVAL_ARGS} \ + ${MLM_RESUME_ARGS} \ + ${MLM_DEFAULT_ARGS} ${MLM_EXTRA_ARGS} diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/generate.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/generate.py new file mode 100644 index 0000000000000000000000000000000000000000..3d3f6571b34f64e5664a4ca4c9517ec19c706450 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/generate.py @@ -0,0 +1,171 @@ +# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. + +"""Sample Generate GPT.""" +import functools +import os +import sys +import warnings + +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))) + +import torch +from datasets import load_dataset + +from megatron.post_training.arguments import add_modelopt_args +from megatron.post_training.checkpointing import load_modelopt_checkpoint +from megatron.post_training.generate import simple_generate +from megatron.post_training.model_builder import modelopt_gpt_mamba_builder +from megatron.post_training.utils import report_current_memory_info, to_empty_if_meta +from megatron.training import get_args, get_model, initialize_megatron +from utils import get_hf_tokenizer +from megatron.training.utils import print_rank_0, unwrap_model +from model_provider import model_provider + +import modelopt.torch.quantization as mtq + +warnings.filterwarnings('once') + + +def add_generate_args(parser): + """Add additional arguments for ModelOpt acceptance rate validation.""" + group = parser.add_argument_group(title='ModelOpt ar validation') + group.add_argument("--osl", type=int, default=128, help="Output sequence length.") + group.add_argument("--draft-length", type=int, default=0, help="Only used in EAGLE.") + group.add_argument("--draft-topk", type=int, default=1, help="Only used in EAGLE.") + group.add_argument("--disable-tqdm", action="store_true", help="Disable tqdm.") + group.add_argument("--fraction", type=float, default=1.0, help="Fraction of dataset to use.") + + add_modelopt_args(parser) + return parser + + +def check_arguments(): + """Checking user arguments.""" + args = get_args() + if args.num_layers_per_virtual_pipeline_stage is not None: + print_rank_0("Interleaved pipeline schedule is not yet supported for text generation.") + exit() + + if hasattr(args, 'moe_grouped_gemm') and args.moe_grouped_gemm == True: + print_rank_0("WARNING: Forcing moe_grouped_gemm to False for PTQ and export.") + args.moe_grouped_gemm = False + + +def mtbench_to_oai_chat(example): + """Convert MTBench data to OpenAI chat completion format.""" + conversations = [] + for prompt in example["prompt"]: + conversations.append({"role": "user", "content": prompt}) + example["conversations"] = conversations + return example + + +def get_conversations(example): + """Extract the input for tokenizer.apply_chat_template.""" + conversations = example.get("conversations", None) + if conversations is None: + conversations = example.get("messages", None) + if conversations is None: + raise ValueError( + "The data must either have conversations or messages field, but got {}".format(example) + ) + return conversations + + +if __name__ == "__main__": + initialize_megatron( + extra_args_provider=add_generate_args, + args_defaults={ + 'tokenizer_type': 'HuggingFaceTokenizer', + 'no_load_rng': True, + 'no_load_optim': True, + }, + ) + + check_arguments() + + args = get_args() + + # Meta device initialization for ParallelLinear only works if using cpu initialization. + # Meta device initialization is used such that models can be materialized in low-precision + # directly when ModelOpt real quant is used. Otherwise, the model is first initialized + # as BF16 in memory which may result in OOM and defeat the purpose of real quant. + if args.init_model_with_meta_device: + args.use_cpu_initialization = True + else: + warnings.warn( + "--init-model-with-meta-device is not set. If you would like to resume the " + "model in low-bit directly (low-memory initialization and skipping 16-bit), " + "--init-model-with-meta-device must be set.", + UserWarning, + ) + + model = get_model(functools.partial(model_provider, modelopt_gpt_mamba_builder), wrap_with_ddp=False) + report_current_memory_info() + + unwrapped_model = unwrap_model(model)[0] + + default_conversations = [ + { + "role": "user", + "content": "Write an email to a wine expert, requesting a guest " + "article contribution for your wine blog.", + } + ] + + if args.finetune_hf_dataset is None: + if args.draft_length > 0: + dataset = load_dataset("HuggingFaceH4/mt_bench_prompts", split="train") + dataset = dataset.map(mtbench_to_oai_chat) + else: + dataset = [{"conversations": default_conversations}] + else: + dataset = load_dataset(args.finetune_hf_dataset, split=args.finetune_data_split) + + tokenizer = get_hf_tokenizer() + + + if args.load is not None: + load_modelopt_checkpoint(model, strict=not args.untie_embeddings_and_output_weights) + print_rank_0("Done loading checkpoint") + + unwrapped_model = unwrap_model(model)[0] + unwrapped_model.eval() + + # Fold the scalars into weight for speedup. + # [TODO]: fold_weight current assumes all weight_quantizer has weight allocated; + # however, this is not the case when share_embeddings_and_output_weights is False. + if getattr(unwrapped_model, "share_embeddings_and_output_weights", False): + mtq.fold_weight(unwrapped_model) + + for idx, example in enumerate(dataset): + if idx > args.fraction * len(dataset): + break + ref_conversations = get_conversations(example) + new_conversations = [] + + for message in ref_conversations: + ground_truth = None + if message["role"] == "assistant": + ground_truth = message["content"] + if message["role"] == "user": + new_conversations.append(message) + print_rank_0( + "{}".format( + tokenizer.apply_chat_template( + new_conversations, tokenize=False, add_generation_prompt=True + ) + ) + ) + input_ids = tokenizer.apply_chat_template( + new_conversations, return_tensors="pt", add_generation_prompt=True + ) + with torch.no_grad(): + output_ids = simple_generate( + unwrapped_model, input_ids.cuda(), osl=args.osl, disable_tqdm=args.disable_tqdm + ) + output_texts = tokenizer.batch_decode(output_ids)[0] + print_rank_0("{}".format(output_texts)) + new_conversations.append({"role": "assistant", "content": output_texts}) + + torch.distributed.barrier() diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/generate.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/generate.sh new file mode 100644 index 0000000000000000000000000000000000000000..58578bb3d022d88a505f21236580e8ce15f4b9e4 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/generate.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" + +# Common arguments and base model specific arguments +source "${SCRIPT_DIR}/conf/arguments.sh" + +# Extra arguments of this script +MLM_DEFAULT_ARGS="--finetune --auto-detect-ckpt-format --export-te-mcore-model" + + +if [ -z ${MLM_MODEL_CKPT} ]; then + printf "${MLM_ERROR} Variable ${PURPLE}MLM_MODEL_CKPT${WHITE} must be set!\n" + exit 1 +fi + +if [ -z ${DRAFT_LEN} ]; then + DRAFT_LEN=0 +fi + + +if [ -z ${PROMPTS_PATH} ]; then + ${LAUNCH_SCRIPT} ${SCRIPT_DIR}/generate.py \ + ${MODEL_ARGS} \ + --tensor-model-parallel-size ${TP} \ + --expert-tensor-parallel-size ${ETP} \ + --expert-model-parallel-size ${EP} \ + --pipeline-model-parallel-size ${PP} \ + --tokenizer-model ${TOKENIZER_MODEL} \ + --load ${MLM_MODEL_CKPT} \ + --draft-length ${DRAFT_LEN} \ + ${MLM_DEFAULT_ARGS} ${MLM_EXTRA_ARGS} + +else + ${LAUNCH_SCRIPT} ${SCRIPT_DIR}/generate.py \ + ${MODEL_ARGS} \ + --tensor-model-parallel-size ${TP} \ + --expert-tensor-parallel-size ${ETP} \ + --expert-model-parallel-size ${EP} \ + --pipeline-model-parallel-size ${PP} \ + --tokenizer-model ${TOKENIZER_MODEL} \ + --load ${MLM_MODEL_CKPT} \ + --data ${PROMPTS_PATH} \ + --draft-length ${DRAFT_LEN} \ + ${MLM_DEFAULT_ARGS} ${MLM_EXTRA_ARGS} +fi diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/generation_server.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/generation_server.sh new file mode 100644 index 0000000000000000000000000000000000000000..9acd61f3d0465918b01564eaa77bc307532f43e1 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/generation_server.sh @@ -0,0 +1,27 @@ +#!/bin/bash + +SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" + +# Common arguments and base model specific arguments +source "${SCRIPT_DIR}/conf/arguments.sh" + +# Extra arguments of this script +MLM_DEFAULT_ARGS="--finetune --auto-detect-ckpt-format --export-te-mcore-model" + + +if [ -z ${MLM_MODEL_CKPT} ]; then + printf "${MLM_ERROR} Variable ${PURPLE}MLM_MODEL_CKPT${WHITE} must be set!\n" + exit 1 +fi + +TOOLS_DIR="$(realpath ${SCRIPT_DIR}/../../../tools)" + +${LAUNCH_SCRIPT} ${TOOLS_DIR}/run_text_generation_server.py \ + ${MODEL_ARGS} \ + --tensor-model-parallel-size ${TP} \ + --expert-tensor-parallel-size ${ETP} \ + --expert-model-parallel-size ${EP} \ + --pipeline-model-parallel-size ${PP} \ + --tokenizer-model ${TOKENIZER_MODEL} \ + --load ${MLM_MODEL_CKPT} \ + ${MLM_DEFAULT_ARGS} ${MLM_EXTRA_ARGS} diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/mmlu.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/mmlu.py new file mode 100644 index 0000000000000000000000000000000000000000..5aa5d1c24c79a82aa555b89de9f0e8202edd5661 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/mmlu.py @@ -0,0 +1,242 @@ +# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. + +"""Sample Generate GPT.""" +import functools +import os +import sys +import warnings +import datasets +import logging +import torch.distributed as dist + +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))) + +import torch +from diskcache import Cache + +from megatron.post_training.arguments import add_modelopt_args +from megatron.post_training.checkpointing import load_modelopt_checkpoint +from megatron.post_training.generate import simple_generate +from megatron.post_training.model_builder import modelopt_gpt_mamba_builder +from megatron.post_training.utils import report_current_memory_info +from megatron.training import get_args, get_model, initialize_megatron +from utils import get_hf_tokenizer +from megatron.training.utils import print_rank_0, unwrap_model +import modelopt.torch.quantization as mtq +from model_provider import model_provider + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) # set to debug if you need more logging + +warnings.filterwarnings('ignore') + +def add_mmlu_args(parser): + """Add additional arguments for ModelOpt text generation PTQ.""" + group = parser.add_argument_group(title='ModelOpt text generation ptq') + group.add_argument("--disable-tqdm", action="store_true", help="Disable tqdm.") + group.add_argument("--fraction", type=float, default=1.0, help="Fraction of dataset to use.") + group.add_argument("--lower-bound", type=float, default=None) + group.add_argument("--no-subject-prompt", action="store_true", help="Use empty prompt instead of subject-based prompt.") + group.add_argument("--mmlu-dataset", type=str, default="cais/mmlu", help="The default dataset to use is cais/mmlu from the HG hub.") + group.add_argument("--cache-dir", type=str, default=None) + add_modelopt_args(parser) + return parser + + +def get_all_subjects(): + """Return all MMLU subjects.""" + return [ + 'abstract_algebra', + 'anatomy', + 'astronomy', + 'business_ethics', + 'clinical_knowledge', + 'college_biology', + 'college_chemistry', + 'college_computer_science', + 'college_mathematics', + 'college_medicine', + 'college_physics', + 'computer_security', + 'conceptual_physics', + 'econometrics', + 'electrical_engineering', + 'elementary_mathematics', + 'formal_logic', + 'global_facts', + 'high_school_biology', + 'high_school_chemistry', + 'high_school_computer_science', + 'high_school_european_history', + 'high_school_geography', + 'high_school_government_and_politics', + 'high_school_macroeconomics', + 'high_school_mathematics', + 'high_school_microeconomics', + 'high_school_physics', + 'high_school_psychology', + 'high_school_statistics', + 'high_school_us_history', + 'high_school_world_history', + 'human_aging', + 'human_sexuality', + 'international_law', + 'jurisprudence', + 'logical_fallacies', + 'machine_learning', + 'management', + 'marketing', + 'medical_genetics', + 'miscellaneous', + 'moral_disputes', + 'moral_scenarios', + 'nutrition', + 'philosophy', + 'prehistory', + 'professional_accounting', + 'professional_law', + 'professional_medicine', + 'professional_psychology', + 'public_relations', + 'security_studies', + 'sociology', + 'us_foreign_policy', + 'virology', + 'world_religions', + ] + + +def format_example(example, include_answer: bool = True): + """Format an example into a multi-choices problem.""" + prompt = example["question"] + for choice, answer in zip(["A", "B", "C", "D"], example["choices"]): + prompt += "\n{}. {}".format(choice, answer) + if include_answer: + prompt += "\nAnswer: {}\n\n".format(["A", "B", "C", "D"][example["answer"]]) + else: + prompt += "\nAnswer:" + return prompt + + +def generate_prompt(test_example, dev_examples, few_shots=0, no_subject_prompt=False): + """Generating few-shot prompts.""" + if no_subject_prompt: + prompt = "" + else: + prompt = "The following are multiple choice questions (with answers) about {}.\n\n".format( + " ".join(test_example["subject"].split("_")) + ) + for i in range(few_shots): + prompt += format_example(dev_examples[i]) + prompt += format_example(test_example, include_answer=False) + return prompt + + +if __name__ == "__main__": + initialize_megatron( + extra_args_provider=add_mmlu_args, + args_defaults={ + 'tokenizer_type': 'HuggingFaceTokenizer', + 'no_load_rng': True, + 'no_load_optim': True, + }, + ) + + args = get_args() + cache = Cache(args.cache_dir) + # Meta device initialization for ParallelLinear only works if using cpu initialization. + # Meta device initialization is used such that models can be materialized in low-precision + # directly when ModelOpt real quant is used. Otherwise, the model is first initialized + # as BF16 in memory which may result in OOM and defeat the purpose of real quant. + if args.init_model_with_meta_device: + args.use_cpu_initialization = True + else: + warnings.warn( + "--init-model-with-meta-device is not set. If you would like to resume the " + "model in low-bit directly (low-memory initialization and skipping 16-bit), " + "--init-model-with-meta-device must be set.", + UserWarning, + ) + + model = get_model(functools.partial(model_provider, modelopt_gpt_mamba_builder), wrap_with_ddp=False) + report_current_memory_info() + + # Materialize the model from meta device to gpu before loading the checkpoint. + unwrapped_model = unwrap_model(model)[0] + unwrapped_model.eval() + unwrapped_model.to_empty(device="cuda") + report_current_memory_info() + + disable_tqdm = args.disable_tqdm or torch.distributed.get_rank() > 0 + + tokenizer = get_hf_tokenizer() + + if args.load is not None: + load_modelopt_checkpoint(model, strict=not args.untie_embeddings_and_output_weights) + print_rank_0("Done loading checkpoint") + + # Fold the scalars into weight for speedup. + # [TODO]: fold_weight current assumes all weight_quantizer has weight allocated; + # however, this is not the case when share_embeddings_and_output_weights is False. + # [TODO]: fold_weight does not support TEGroupedMLP (QuantTEColumnParallelGroupedLinear) + # which stores per-expert weights as weight0, weight1, etc. instead of a single weight. + has_grouped_mlp = any("TEGroupedMLP" in type(m).__name__ for m in unwrapped_model.modules()) + if not getattr(unwrapped_model, "share_embeddings_and_output_weights", False) and not has_grouped_mlp: + mtq.fold_weight(unwrapped_model) + + all_subjects = get_all_subjects() + + all_correct = {} + + for subject in all_subjects: + test_data = datasets.load_dataset(args.mmlu_dataset, subject, split="test") + dev_data = datasets.load_dataset(args.mmlu_dataset, subject, split="dev") + + correct = [] + for idx, test_example in enumerate(test_data): + if idx > args.fraction * len(test_data): + break + label = ["A", "B", "C", "D"][test_example["answer"]] + prompt = generate_prompt(test_example, dev_data, few_shots=0, no_subject_prompt=args.no_subject_prompt) + cache_key = f"{args.load}_{subject}_{prompt}" # model name, subject, prompt + + if cache_key in cache: + predict = cache[cache_key] + if dist.get_rank() == 0: + logger.debug(f"Cache hit for {args.load}_{subject}") + else: + tokens = tokenizer(prompt, return_tensors="pt") + with torch.no_grad(): + generated_ids = simple_generate( + unwrapped_model, tokens.input_ids.cuda(), osl=2, disable_tqdm=disable_tqdm + ) + predict = tokenizer.batch_decode(generated_ids)[0].strip() + if torch.distributed.get_rank() == 0: + cache.add(cache_key, predict) + + correct += [True] if predict.startswith(label) else [False] + all_correct[subject] = correct + + if torch.distributed.get_rank() == 0: + print( + "{:48}| {:.3f} | {:5}/{:5}".format( + subject, sum(correct) / len(correct), sum(correct), len(correct) + ), + flush=True, + ) + + avg_correct = [] + + for subject, correct in all_correct.items(): + avg_correct += correct + + if torch.distributed.get_rank() == 0: + print( + "{:48}| {:.3f} | {:5}/{:5}".format( + "average", sum(avg_correct) / len(avg_correct), sum(avg_correct), len(avg_correct) + ), + flush=True, + ) + + if args.lower_bound is not None: + assert sum(avg_correct) / len(avg_correct) > args.lower_bound diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/mmlu.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/mmlu.sh new file mode 100644 index 0000000000000000000000000000000000000000..36918b89df29c5e3dd0f3c4a42bc4e4fd1d43daa --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/mmlu.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" + +# Common arguments and base model specific arguments +source "${SCRIPT_DIR}/conf/arguments.sh" + +# Extra arguments of this script +MLM_DEFAULT_ARGS="--finetune --auto-detect-ckpt-format --export-te-mcore-model --sequence-parallel" + +${LAUNCH_SCRIPT} ${SCRIPT_DIR}/mmlu.py \ + ${MODEL_ARGS} \ + --tensor-model-parallel-size ${TP} \ + --expert-tensor-parallel-size ${ETP} \ + --expert-model-parallel-size ${EP} \ + --pipeline-model-parallel-size ${PP} \ + --tokenizer-model ${TOKENIZER_MODEL} \ + --load ${MLM_MODEL_CKPT} \ + ${MLM_DEFAULT_ARGS} ${MLM_EXTRA_ARGS} diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/offline_feature_extract.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/offline_feature_extract.py new file mode 100644 index 0000000000000000000000000000000000000000..80207faf2b2e3b72b8ec02bb6902ccdef3426e2a --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/offline_feature_extract.py @@ -0,0 +1,78 @@ +# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. + +"""Supervised Finetuning GPT.""" +import functools +import os +import sys + +import torch + +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))) + + +from examples.post_training.modelopt.finetune import SFTDataset +from megatron.core import mpu +from megatron.post_training.arguments import add_modelopt_args +from megatron.post_training.checkpointing import load_modelopt_checkpoint +from megatron.post_training.model_builder import modelopt_gpt_mamba_builder +from megatron.training import get_args, get_model, get_tokenizer, initialize_megatron +from megatron.training.utils import print_rank_0, unwrap_model +from model_provider import model_provider + + +def add_extract_args(parser): + """Add additional arguments for feature extraction.""" + group = parser.add_argument_group(title='Feature extraction') + group.add_argument("--num-samples", type=int, default=128000, help="Number of samples.") + group.add_argument("--output-dir", type=str, help="Path to the output directory.") + + add_modelopt_args(parser) + return parser + +def extract_feature(dataset, model, output_dir, idx_start, idx_end): + os.makedirs(output_dir, exist_ok=True) + for i in range(idx_start + mpu.get_expert_data_parallel_rank(), idx_end, mpu.get_expert_data_parallel_world_size()): + file_name = "{:08d}.pt".format(i - idx_start) + file_path = os.path.join(output_dir, file_name) + if not os.path.exists(file_path): + input_ids = dataset[i]["input_ids"][:dataset.seq_length].unsqueeze(0).to(torch.cuda.current_device()) + output = model(input_ids, return_eagle_inputs=True) + if mpu.get_tensor_model_parallel_rank() == 0 and mpu.get_expert_model_parallel_rank() == 0: + torch.save(output, file_path) + torch.distributed.barrier() + +if __name__ == "__main__": + initialize_megatron( + extra_args_provider=add_extract_args, + args_defaults={ + 'tokenizer_type': 'HuggingFaceTokenizer', + 'no_load_rng': True, + 'no_load_optim': True, + }, + ) + + args = get_args() + tokenizer = get_tokenizer() + model = get_model(functools.partial(model_provider, modelopt_gpt_mamba_builder), wrap_with_ddp=False) + + load_modelopt_checkpoint(model, strict=not args.untie_embeddings_and_output_weights) + print_rank_0("Done loading checkpoint") + + unwrapped_model = unwrap_model(model)[0] + unwrapped_model.eval() + + kwargs = { + "tokenizer": tokenizer._tokenizer, + "seq_length": args.seq_length, + # Optional kwargs + "hf_dataset": args.finetune_hf_dataset, + "num_shards": mpu.get_expert_data_parallel_world_size(), + "shard_index": mpu.get_expert_data_parallel_rank(), + } + sft_dataset = SFTDataset(args.num_samples, None, **kwargs) + + extract_feature(sft_dataset, unwrapped_model, os.path.join(args.output_dir, "train"), 0, int(args.num_samples * 0.98)) + extract_feature(sft_dataset, unwrapped_model, os.path.join(args.output_dir, "valid"), int(args.num_samples * 0.98), int(args.num_samples * 0.99)) + extract_feature(sft_dataset, unwrapped_model, os.path.join(args.output_dir, "test"), int(args.num_samples * 0.99), args.num_samples) + + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/offline_feature_extract.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/offline_feature_extract.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ab7a0fcc850bac85b0063605990195c2e1466bf --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/offline_feature_extract.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" + +# Common arguments and base model specific arguments +source "${SCRIPT_DIR}/conf/arguments.sh" + + +# Set up cache dir for HF to avoid out of space error +export HF_DATASETS_CACHE="/tmp/hf_datasets_cache" + +# Extra arguments of this script +MLM_DEFAULT_ARGS=" \ + --distributed-timeout-minutes 30 \ + --auto-detect-ckpt-format \ + --export-te-mcore-model \ + --finetune \ +" + + +if [ -z ${MLM_DATA_ARGS} ]; then + MLM_DATA_ARGS=" \ + --num-samples 128000 \ + --finetune-hf-dataset nvidia/Daring-Anteater \ + " +fi + + +${LAUNCH_SCRIPT} ${SCRIPT_DIR}/offline_feature_extract.py \ + ${MODEL_ARGS} \ + --tensor-model-parallel-size ${TP} \ + --expert-tensor-parallel-size ${ETP} \ + --expert-model-parallel-size ${EP} \ + --pipeline-model-parallel-size ${PP} \ + --tokenizer-model ${TOKENIZER_MODEL} \ + --load ${MLM_MODEL_CKPT} \ + ${MLM_DATA_ARGS} \ + ${MLM_DEFAULT_ARGS} ${MLM_EXTRA_ARGS} diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/prune.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/prune.py new file mode 100644 index 0000000000000000000000000000000000000000..56bbffa0cd0ec0a443cc2ceed7a9fe26e3dbcbd6 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/prune.py @@ -0,0 +1,241 @@ +# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. + +"""Example script for pruning a GPT / Mamba model using Model Optimizer (ModelOpt). + +Read more about ModelOpt pruning at https://github.com/NVIDIA/Model-Optimizer/tree/main/examples/pruning +""" + +import functools +import inspect +import os +import sys +import warnings + +import torch +from datasets import load_dataset +from tqdm import tqdm + +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))) +import modelopt.torch.opt as mto +import modelopt.torch.prune as mtp +from modelopt.torch.export import import_mcore_gpt_from_hf +from modelopt.torch.prune.plugins.mcore_minitron import SUPPORTED_HPARAMS + +from megatron.core.parallel_state import ( + get_pipeline_model_parallel_group, + get_tensor_model_parallel_group, +) +from megatron.post_training.arguments import add_modelopt_args +from megatron.post_training.checkpointing import load_modelopt_checkpoint +from megatron.post_training.generate import simple_generate +from megatron.post_training.model_builder import modelopt_gpt_mamba_builder +from megatron.post_training.utils import ( + report_current_memory_info, +) +from megatron.training import get_args, get_model, initialize_megatron +from utils import get_hf_tokenizer +from megatron.training.checkpointing import save_checkpoint +from megatron.training.utils import print_rank_0, unwrap_model +from model_provider import model_provider + +warnings.filterwarnings("ignore") + + +def add_prune_args(parser): + """Add additional arguments for ModelOpt pruning.""" + group = parser.add_argument_group(title="ModelOpt pruning") + group.add_argument( + "--calib-size", type=int, default=1024, help="Samples to use for pruning calibration." + ) + group.add_argument( + "--prompts", + type=str, + default=("Hello!|Born in California, Soyer trained as a"), + help="Input texts. Please use | to separate different batches.", + ) + group.add_argument( + "--references", + type=str, + default="", + help="Reference texts. Please use | to separate different batches.", + ) + group.add_argument( + "--pretrained-model-path", type=str, default=None, help="HuggingFace pretrained model" + ) + # Pruning parameters + group.add_argument( + "--target-ffn-hidden-size", type=int, help="Prune MLP FFN hidden size to this value" + ) + group.add_argument( + "--target-hidden-size", type=int, help="Prune hidden size (embedding dim) to this value" + ) + group.add_argument( + "--target-num-attention-heads", + type=int, + help="Prune number of attention heads to this value. Must be supplied with --target-num-query-groups", + ) + group.add_argument( + "--target-num-query-groups", + type=int, + help="Prune number of query groups to this value. Must be supplied with --target-num-attention-heads", + ) + group.add_argument( + "--target-mamba-num-heads", + type=int, + help="Prune number of Mamba attention heads to this value", + ) + group.add_argument( + "--target-mamba-head-dim", + type=int, + help="Prune dimension of Mamba attention heads to this value", + ) + group.add_argument( + "--target-num-moe-experts", type=int, help="Prune number of MoE experts to this value" + ) + group.add_argument( + "--target-moe-ffn-hidden-size", type=int, help="Prune MoE FFN hidden size to this value" + ) + group.add_argument( + "--target-moe-shared-expert-intermediate-size", + type=int, + help="Prune MoE shared expert intermediate size to this value", + ) + group.add_argument( + "--target-num-layers", + type=int, + help="Prune number of transformer layers to this value based on " + "Block Influence metric (cosine similarity) as per https://arxiv.org/abs/2403.03853", + ) + group.add_argument( + "--layers-to-drop", + type=int, + metavar="N", + nargs="*", + help="Drop specific model layers (1-indexed). Cannot be used with rest of the pruning options", + ) + group.add_argument( + "--pruning-scores-path", + type=str, + default=None, + help="Path to the cache and reuse pruning scores for pruning again to different params", + ) + add_modelopt_args(parser) + return parser + + +def check_arguments(args): + """Checking user arguments.""" + if args.layers_to_drop: + if any(getattr(args, f"target_{k}", None) is not None for k in SUPPORTED_HPARAMS): + raise ValueError("--layers_to_drop cannot be used with other pruning parameters") + + +def get_calib_dataloader(calib_size=1024, max_sequence_length=512): + """Return a dataloader for calibration.""" + dataset = load_dataset("cnn_dailymail", name="3.0.0", split="train") + text_column = "article" + + calib_size = min(len(dataset), calib_size) + for i in range(calib_size): + yield dataset[i][text_column][:max_sequence_length] + + +def get_params(model): + params = sum(p.numel() for p in model.parameters()) + reduced_params = torch.Tensor([params]).to(device=next(model.parameters()).device) + torch.distributed.all_reduce(reduced_params, group=get_pipeline_model_parallel_group()) + torch.distributed.all_reduce(reduced_params, group=get_tensor_model_parallel_group()) + return reduced_params.item() + + +if __name__ == "__main__": + initialize_megatron( + extra_args_provider=add_prune_args, + args_defaults={ + "tokenizer_type": "HuggingFaceTokenizer", + "no_load_rng": True, + "no_load_optim": True, + }, + ) + + args = get_args() + check_arguments(args) + + tokenizer = get_hf_tokenizer() + model = get_model( + functools.partial(model_provider, modelopt_gpt_mamba_builder), wrap_with_ddp=False + ) + unwrapped_model = unwrap_model(model)[0] + + report_current_memory_info() + + if args.load is not None: + load_modelopt_checkpoint(model, strict=not args.untie_embeddings_and_output_weights) + print_rank_0("Done loading checkpoint") + + if args.pretrained_model_path is not None: + import_dtype = torch.float16 if args.fp16 else torch.bfloat16 + workspace_dir = os.environ.get("MLM_WORK_DIR", "/tmp") + import_kwargs = {"dtype": import_dtype} + if "trust_remote_code" in inspect.signature(import_mcore_gpt_from_hf).parameters: + import_kwargs.update({"trust_remote_code": args.trust_remote_code}) + import_mcore_gpt_from_hf( + unwrapped_model, args.pretrained_model_path, workspace_dir, **import_kwargs + ) + + def _custom_prompt_forward_loop_func(model): + all_prompts = args.prompts.split("|") + if args.references == "": + all_references = [None] * len(all_prompts) + else: + all_references = args.references.split("|") + + for idx, prompt in tqdm(enumerate(all_prompts), disable=torch.distributed.get_rank()): + tokens = tokenizer(prompt, return_tensors="pt") + generated_ids = simple_generate(model, tokens.input_ids.cuda(), osl=32) + generated_texts = tokenizer.batch_decode(generated_ids) + print_rank_0("{}".format(generated_texts)) + if all_references[idx] is not None: + assert all_references[idx] == generated_texts[0], all_references[idx] + + def _hf_dataset_forword_loop_func(model): + dataloader = get_calib_dataloader(args.calib_size) + + for prompt in tqdm(dataloader, total=args.calib_size, disable=torch.distributed.get_rank()): + tokens = tokenizer(prompt, return_tensors="pt") + simple_generate(model, tokens.input_ids.cuda(), osl=1) + + if args.layers_to_drop: + mtp.mcore_minitron.drop_mcore_language_model_layers( + model, layers_to_drop=args.layers_to_drop + ) + else: + print_rank_0("Pruning model...") + export_config = { + k: getattr(args, f"target_{k}") + for k in SUPPORTED_HPARAMS + if getattr(args, f"target_{k}", None) is not None + } + config = {"forward_loop": _hf_dataset_forword_loop_func} + if args.pruning_scores_path is not None: + config["scores_path"] = args.pruning_scores_path + mtp.prune( + unwrapped_model, + mode="mcore_minitron", + constraints={"export_config": export_config}, + dummy_input=None, # Not used + config=config, + ) + # [WAR till modelopt 0.39]: Remove prune state to avoid converting again on restore which forces TP=1. + if mto.ModeloptStateManager.has_state_for_mode_type("prune", model=unwrapped_model): + mto.ModeloptStateManager.remove_state(unwrapped_model) + + print_rank_0(f"Pruned Model:\n {unwrapped_model}") + print_rank_0(f"Pruned Model Params: {get_params(unwrapped_model)/1e9:.2f}B") + + _custom_prompt_forward_loop_func(unwrapped_model) + + if args.save is not None: + save_checkpoint(1, model, None, None, 0) + + print_rank_0("Done") diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/prune.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/prune.sh new file mode 100644 index 0000000000000000000000000000000000000000..33f3e615e96c620e13576dc2c8b74eb2003b82d5 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/prune.sh @@ -0,0 +1,78 @@ +#!/bin/bash + +SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" + +# Common arguments and base model specific arguments +source "${SCRIPT_DIR}/conf/arguments.sh" + +if [ ${TP} -ne 1 ]; then + printf "${MLM_ERROR} TP must be 1. Only PP>=1 is supported for pruning.\n" + exit 1 +fi + +# Extra arguments of this script +MLM_DEFAULT_ARGS=" + --distributed-timeout-minutes 30 \ + --finetune --auto-detect-ckpt-format \ + --no-gradient-accumulation-fusion \ + --export-te-mcore-model +" + +# Pruning target arguments - set these environment variables to enable pruning +# Example: export TARGET_HIDDEN_SIZE=3072 TARGET_FFN_HIDDEN_SIZE=9216 +# Example: export LAYERS_TO_DROP="1 5 10" + +# Define pruning argument mappings: "env_var:cli_arg" +# List of environment variables we want to check for pruning CLI args +PRUNE_ENV_VARS=( + TARGET_FFN_HIDDEN_SIZE + TARGET_HIDDEN_SIZE + TARGET_NUM_ATTENTION_HEADS + TARGET_NUM_QUERY_GROUPS + TARGET_MAMBA_NUM_HEADS + TARGET_MAMBA_HEAD_DIM + TARGET_NUM_MOE_EXPERTS + TARGET_MOE_FFN_HIDDEN_SIZE + TARGET_MOE_SHARED_EXPERT_INTERMEDIATE_SIZE + TARGET_NUM_LAYERS + LAYERS_TO_DROP +) + +# Build arguments from environment variables (TARGET_NUM_LAYERS -> --target-num-layers, etc.) +PRUNE_ARGS=${PRUNE_ARGS:-""} +for env_var in "${PRUNE_ENV_VARS[@]}"; do + if [ ! -z "${!env_var}" ]; then + # prepend --, convert to lowercase, replace _ with - + cli_arg="--$(echo "${env_var}" | tr '[:upper:]' '[:lower:]' | tr '_' '-')" + PRUNE_ARGS="${PRUNE_ARGS} ${cli_arg} ${!env_var}" + fi +done + +if [ -z "${PRUNE_ARGS}" ]; then + printf "${MLM_WARNING} No pruning arguments specified. Set TARGET_* or LAYERS_TO_DROP environment variables.\n" +fi + +if [ -z ${MLM_MODEL_SAVE} ]; then + MLM_MODEL_SAVE=${MLM_WORK_DIR}/${MLM_MODEL_CFG}_pruned + printf "${MLM_WARNING} Variable ${PURPLE}MLM_MODEL_SAVE${WHITE} is not set (default: ${MLM_MODEL_SAVE})!\n" +fi + +if [ -z ${MLM_MODEL_CKPT} ]; then + LOAD_ARGS="--pretrained-model-path ${HF_MODEL_CKPT}" +else + LOAD_ARGS="--load ${MLM_MODEL_CKPT}" +fi + + +set -ex + +${LAUNCH_SCRIPT} ${SCRIPT_DIR}/prune.py \ + ${MODEL_ARGS} \ + ${LOAD_ARGS} \ + --pipeline-model-parallel-size ${PP} \ + --tensor-model-parallel-size ${TP} \ + --tokenizer-model ${TOKENIZER_MODEL} \ + --save ${MLM_MODEL_SAVE} \ + --references "${MLM_REF_LABEL}" \ + ${PRUNE_ARGS} \ + ${MLM_DEFAULT_ARGS} ${MLM_EXTRA_ARGS} diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/quantize.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/quantize.py new file mode 100644 index 0000000000000000000000000000000000000000..dc4947038e54256ab8a81488c6cf842b32c1af13 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/quantize.py @@ -0,0 +1,456 @@ +# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. + +"""Sample Generate GPT.""" + +import copy +import functools +import inspect +import json +import os +import random +import sys +import warnings + +import torch +import torch.distributed +from tqdm import tqdm + +# NOTE: Needs to be before modelopt imports in case megatron.core is not installed. +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))) + +import modelopt.torch.quantization as mtq +from modelopt.torch.export import import_mcore_gpt_from_hf +from modelopt.torch.utils.dataset_utils import get_dataset_dataloader + +try: + import modelopt.torch.quantization.plugins.psx_formats as mtq_psx +except ImportError: + mtq_psx = None + warnings.warn( + "psx_formats is not installed. PSX formats quantization configs will not be available." + ) +try: + import modelopt.torch.quantization.plugins.luts as mtq_luts +except ImportError: + mtq_luts = None + warnings.warn("luts is not installed. LUTs quantization configs will not be available.") + +from megatron.core.utils import get_batch_on_this_cp_rank +from megatron.post_training.arguments import add_modelopt_args +from megatron.post_training.checkpointing import load_modelopt_checkpoint +from megatron.post_training.generate import simple_generate +from megatron.post_training.model_builder import modelopt_gpt_mamba_builder +from megatron.post_training.utils import ( + print_distributed_quant_summary, + report_current_memory_info, +) +from megatron.training import get_args, get_model, initialize_megatron +from utils import get_hf_tokenizer +from megatron.training.checkpointing import save_checkpoint +from megatron.training.utils import print_rank_0, unwrap_model +from model_provider import model_provider + +warnings.filterwarnings("ignore") + +QUANT_CFG_CHOICES = {} + +# Auto-load all quant configs by full name +for k in mtq.config.choices: + QUANT_CFG_CHOICES[k] = getattr(mtq, k) + +KV_QUANT_CFG_CHOICES = { + "none": "none", + "fp8": "FP8_KV_CFG", + "fp8_affine": "FP8_AFFINE_KV_CFG", + "nvfp4": "NVFP4_KV_CFG", + "nvfp4_affine": "NVFP4_AFFINE_KV_CFG", + "nvfp4_rotate": "NVFP4_KV_ROTATE_CFG", +} + +if mtq_psx is not None: + QUANT_CFG_CHOICES.update({k: getattr(mtq_psx, k) for k in mtq_psx.choices}) + +if mtq_luts is not None: + QUANT_CFG_CHOICES.update({k: getattr(mtq_luts, k) for k in mtq_luts.choices}) + + +def add_text_generate_ptq_args(parser): + """Add additional arguments for ModelOpt text generation PTQ.""" + group = parser.add_argument_group(title="ModelOpt text generation ptq") + group.add_argument( + "--calib-size", type=int, default=512, help="Number of samples to use for ptq calibration." + ) + group.add_argument( + "--calib-dataset-path-or-name", + type=str, + default="cnn_dailymail", + help="Path to local calibration dataset file (.jsonl) or HuggingFace dataset name.", + ) + group.add_argument( + "--calib-max-sequence-length", + type=int, + default=512, + help="Maximum sequence length for calibration.", + ) + group.add_argument( + "--calib-use-random-offset", + action="store_true", + help="Use random offsets when slicing sequences for calibration. (Only for local files)", + ) + group.add_argument( + "--calib-batch-size", type=int, default=1, help="Batch size for calibration." + ) + group.add_argument( + "--prompts", + type=str, + default=("Hello!|Born in California, Soyer trained as a"), + help="Input texts. Please use | to separate different batches.", + ) + group.add_argument( + "--skip-generate", + action="store_true", + default=False, + help="Skip the post-quantization generate/validation step.", + ) + group.add_argument( + "--references", + type=str, + default="", + help="Reference texts. Please use | to separate different batches.", + ) + group.add_argument( + "--pretrained-model-path", type=str, default=None, help="HuggingFace pretrained model" + ) + group.add_argument("--compress", action="store_true", help="Enable real low-bit quantization.") + group.add_argument( + "--disable-qkv-quant", + action="store_true", + help="Disable q, k, v linear from being quantized.", + ) + group.add_argument("--weight-only", action="store_true", help="Disable input quantization.") + group.add_argument( + "--force-all-expert-routing", + action="store_true", + help="Forcing all experts to be routed during the calibration.", + ) + group.add_argument( + "--num-first-layers-to-skip-quant", + type=int, + default=None, + help="Number of first layers to skip quantization.", + ) + group.add_argument( + "--num-last-layers-to-skip-quant", + type=int, + default=None, + help="Number of last layers to skip quantization.", + ) + add_modelopt_args(parser) + return parser + + +def check_arguments(): + """Checking user arguments.""" + args = get_args() + if args.num_layers_per_virtual_pipeline_stage is not None: + print_rank_0("Interleaved pipeline schedule is not yet supported for text generation.") + exit() + + if hasattr(args, "moe_grouped_gemm") and args.moe_grouped_gemm == True: + print_rank_0("WARNING: Forcing moe_grouped_gemm to False for PTQ and export.") + args.moe_grouped_gemm = False + + +def _is_first_layers(name: str, num_layers: int = 1, num_layers_to_disable: int = 1) -> bool: + if "layers." not in name: + return False + try: + layer_idx = int(name.split("layers.")[-1].split(".")[0]) + except ValueError: + return False + return layer_idx < num_layers_to_disable + + +def _is_last_layers(name: str, num_layers: int = 1, num_layers_to_disable: int = 1) -> bool: + if "layers." not in name: + return False + try: + layer_idx = int(name.split("layers.")[-1].split(".")[0]) + except ValueError: + return False + return layer_idx >= num_layers - num_layers_to_disable + + +def get_first_layers_disabled_config(config, num_layers: int = 1, num_layers_to_disable: int = 1): + """Get a config for `mtq.quantize` with first & last `num_layers_to_disable` layers disabled. + + The layers to disable are the first & last `num_layers_to_disable` layers. + """ + config = copy.deepcopy(config) + quant_cfg = config.get("quant_cfg", {}) + quant_cfg.update( + { + functools.partial( + _is_first_layers, num_layers=num_layers, num_layers_to_disable=num_layers_to_disable + ): {"enable": False} + } + ) + config["quant_cfg"] = quant_cfg + return config + + +def get_last_layers_disabled_config(config, num_layers: int = 1, num_layers_to_disable: int = 1): + """Get a config for `mtq.quantize` with last `num_layers_to_disable` layers disabled. + + The layers to disable are the last `num_layers_to_disable` layers. + """ + config = copy.deepcopy(config) + quant_cfg = config.get("quant_cfg", {}) + quant_cfg.update( + { + functools.partial( + _is_last_layers, num_layers=num_layers, num_layers_to_disable=num_layers_to_disable + ): {"enable": False} + } + ) + config["quant_cfg"] = quant_cfg + return config + + +def get_modelopt_torch_quantization_config(): + """Return a quantization config.""" + args = get_args() + if args.export_quant_cfg not in QUANT_CFG_CHOICES: + raise ValueError(f"Unsupported quantization config {args.export_quant_cfg}.") + mtq_config = QUANT_CFG_CHOICES[args.export_quant_cfg] + + fp8_config = {"enable": True, "num_bits": (4, 3), "axis": None} + fp4_config = { + "num_bits": (2, 1), + "block_sizes": {-1: 16, "type": "dynamic", "scale_bits": (4, 3)}, + "axis": None, + "enable": True, + } + if args.export_quant_cfg == "FP8_DEFAULT_CFG": + # Enable Medusa heads and kv-cache quantization + mtq_config["quant_cfg"]["*medusa_heads**"] = fp8_config + if "FP4" in args.export_quant_cfg: + # Enable Medusa heads and kv-cache quantization + mtq_config["quant_cfg"]["*medusa_heads**"] = fp4_config + if "AWQ" in args.export_quant_cfg: + weight_quantizer = mtq_config["quant_cfg"]["*weight_quantizer"] # type: ignore + if isinstance(weight_quantizer, list): + weight_quantizer = weight_quantizer[0] + weight_quantizer["block_sizes"][-1] = 128 + + # Customization + if args.disable_qkv_quant: + mtq_config["quant_cfg"]["*self_attention*"] = {"enable": False} + + # KV Cache Quantization + enable_quant_kv_cache = args.export_kv_cache_quant != "none" + if enable_quant_kv_cache and not args.compress: + kv_cache_quant_cfg = getattr(mtq, KV_QUANT_CFG_CHOICES[args.export_kv_cache_quant])[ + "quant_cfg" + ] + mtq_config = mtq.utils.update_quant_cfg_with_kv_cache_quant(mtq_config, kv_cache_quant_cfg) + + # Weight Only Quantization + if args.weight_only: + mtq_config["quant_cfg"]["*input_quantizer"] = {"enable": False} + if args.num_first_layers_to_skip_quant is not None: + mtq_config = get_first_layers_disabled_config( + mtq_config, + num_layers=args.num_layers, + num_layers_to_disable=args.num_first_layers_to_skip_quant, + ) + if args.num_last_layers_to_skip_quant is not None: + mtq_config = get_last_layers_disabled_config( + mtq_config, + num_layers=args.num_layers, + num_layers_to_disable=args.num_last_layers_to_skip_quant, + ) + + return mtq_config + + +def get_calib_dataloader( + dataset_path_or_name, + tokenizer, + calib_size=512, + max_sequence_length=512, + use_random_offset=False, + batch_size=1, +): + """Return a dataloader/iterator for calibration using SFT or HF datasets. + + Supports either a local path (.jsonl) or a HuggingFace dataset name. + """ + if os.path.isfile(dataset_path_or_name): + # Local file + print_rank_0(f"Loading calibration dataset from local file: {dataset_path_or_name}") + all_texts = [] + with open(dataset_path_or_name) as f: + for i, line in enumerate(f): + if len(all_texts) == calib_size: + break + sample = json.loads(line) + + # Extract text field from various possible keys + if isinstance(sample, dict) and "text" in sample: + if not sample["text"]: + warnings.warn(f"Sample {i} has empty text, skipping") + continue + full_text = sample["text"] + elif isinstance(sample, dict) and "messages" in sample: + conversations = sample["messages"] + assert "role" in conversations[0] and "content" in conversations[0] + full_text = "".join([f"{msg['role']}: {msg['content']}" for msg in conversations]) + elif isinstance(sample, list) and isinstance(sample[0], dict): + assert "role" in sample[0] and "content" in sample[0] + full_text = "".join([f"{msg['role']}: {msg['content']}" for msg in sample]) + else: + raise ValueError(f"Sample {i} has unexpected format") + + # Slice text + max_text_length = int(max_sequence_length / 0.75) # tokenized text is roughtly ~75% length of original + start_idx = 0 + if use_random_offset and len(full_text) > max_text_length: + start_idx = random.randint(0, len(full_text) - max_text_length) + text = full_text[start_idx : start_idx + max_text_length] + all_texts.append(text) + + print_rank_0(f"Loaded calibration dataset ({dataset_path_or_name}) with {len(all_texts)} samples") + print_rank_0(f"Actual num samples: {len(all_texts)}, max seq length: {max_sequence_length}") + print_rank_0(f"Sampling Strategy: {'Random Index' if use_random_offset else 'From Beginning'}") + + # Tokenize all texts at once and move to device + tokens = tokenizer( + all_texts, return_tensors="pt", padding="max_length", max_length=max_sequence_length, truncation=True + ) + all_input_ids = tokens.input_ids.cuda() + return [{"input_ids": all_input_ids[i:i+batch_size]} for i in range(0, len(all_input_ids), batch_size)] + else: + # HuggingFace dataset + if use_random_offset: + warnings.warn("Random offset is not supported for HuggingFace datasets.") + print_rank_0(f"Loading calibration dataset from HuggingFace: {dataset_path_or_name}") + return get_dataset_dataloader( + dataset_name=dataset_path_or_name, + tokenizer=tokenizer, + num_samples=calib_size, + max_sample_length=max_sequence_length, + batch_size=batch_size, + device="cuda", + ) + + +if __name__ == "__main__": + initialize_megatron( + extra_args_provider=add_text_generate_ptq_args, + args_defaults={ + "tokenizer_type": "HuggingFaceTokenizer", + "no_load_rng": True, + "no_load_optim": True, + }, + ) + + check_arguments() + + args = get_args() + + tokenizer = get_hf_tokenizer() + + model = get_model( + functools.partial(model_provider, modelopt_gpt_mamba_builder), wrap_with_ddp=False + ) + + report_current_memory_info() + + if args.load is not None: + load_modelopt_checkpoint(model, strict=not args.untie_embeddings_and_output_weights) + print_rank_0("Done loading checkpoint") + + if args.pretrained_model_path is not None: + from modelopt.torch.export import import_mcore_gpt_from_hf + + import_dtype = torch.float16 if args.fp16 else torch.bfloat16 + unwrapped_model = unwrap_model(model)[0] + workspace_dir = os.environ.get("MLM_WORK_DIR", "/tmp") + + import_kwargs = {"dtype": import_dtype} + if "trust_remote_code" in inspect.signature(import_mcore_gpt_from_hf).parameters: + import_kwargs.update({"trust_remote_code": args.trust_remote_code}) + import_mcore_gpt_from_hf( + unwrapped_model, args.pretrained_model_path, workspace_dir, **import_kwargs + ) + + def _custom_prompt_forward_loop_func(model): + all_prompts = args.prompts.split("|") + if args.references == "": + all_references = [None] * len(all_prompts) + else: + all_references = args.references.split("|") + + for idx, prompt in tqdm(enumerate(all_prompts), disable=torch.distributed.get_rank()): + tokens = tokenizer(prompt, return_tensors="pt") + generated_ids = simple_generate(model, tokens.input_ids.cuda(), osl=32) + generated_texts = tokenizer.batch_decode(generated_ids) + print_rank_0("{}".format(generated_texts)) + if all_references[idx] is not None: + assert all_references[idx] == generated_texts[0], all_references[idx] + + def _dataset_forward_loop_func(model): + dataloader = get_calib_dataloader( + dataset_path_or_name=args.calib_dataset_path_or_name, + tokenizer=tokenizer, + calib_size=args.calib_size, + max_sequence_length=args.calib_max_sequence_length, + use_random_offset=args.calib_use_random_offset, + batch_size=args.calib_batch_size, + ) + for sample in tqdm(dataloader, disable=torch.distributed.get_rank()): + sample = get_batch_on_this_cp_rank(sample) + simple_generate(model, sample["input_ids"], osl=1, calibration_mode=True) + + unwrapped_model = unwrap_model(model)[0] + + if args.force_all_expert_routing: + warnings.warn( + "--force-all-expert-routing will be deprecated in the next release and is no longer needed." + ) + + if args.export_quant_cfg is not None: + print_rank_0("Quantizing the model...") + mtq_config = get_modelopt_torch_quantization_config() + + if not hasattr(tokenizer, "pad_token") or tokenizer.pad_token is None: + tokenizer.pad_token = tokenizer.eos_token + tokenizer.padding_side = "left" # better for calibration + + if args.weight_only: + mtq.quantize(unwrapped_model, mtq_config) + elif hasattr(unwrapped_model, "calibration_mode"): + unwrapped_model.calibration_mode = True + mtq.quantize(unwrapped_model, mtq_config, _dataset_forward_loop_func) + unwrapped_model.calibration_mode = False + else: + mtq.quantize(unwrapped_model, mtq_config, _dataset_forward_loop_func) + + if args.compress: + mtq.compress(unwrapped_model) + print_rank_0("Weights are now compressed to low-bit!") + + print_distributed_quant_summary(model, "Quantized Model:") + + if args.save is not None: + save_checkpoint(1, model, None, None, 0, release=True) + + # Free calibration/quantization memory before generate + import gc + gc.collect() + torch.cuda.empty_cache() + + # Do this after saving in case it causes issues + if not args.skip_generate: + _custom_prompt_forward_loop_func(unwrapped_model) diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/quantize.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/quantize.sh new file mode 100644 index 0000000000000000000000000000000000000000..9119ff4ae76ec58e483f4616312dfffe6327f835 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/quantize.sh @@ -0,0 +1,61 @@ +#!/bin/bash + +SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" + +# Common arguments and base model specific arguments +source "${SCRIPT_DIR}/conf/arguments.sh" + +# Extra arguments of this script +MLM_DEFAULT_ARGS=" + --distributed-timeout-minutes 30 \ + --finetune --auto-detect-ckpt-format \ + --export-te-mcore-model \ + --sequence-parallel \ +" + +QUANT_CFG=$2 + +if [ -z ${QUANT_CFG} ]; then + QUANT_CFG='FP8_DEFAULT_CFG' + printf "${MLM_WARNING} Variable ${PURPLE}QUANT_CFG${WHITE} is not set (default: ${QUANT_CFG})!\n" +fi + +if [ -z ${MLM_MODEL_SAVE} ]; then + MLM_MODEL_SAVE=${MLM_WORK_DIR}/${MLM_MODEL_CFG}_quant + printf "${MLM_WARNING} Variable ${PURPLE}MLM_MODEL_SAVE${WHITE} is not set (default: ${MLM_MODEL_SAVE})!\n" +fi + +EXTRA_ARGS=(${MLM_DEFAULT_ARGS} ${MLM_EXTRA_ARGS}) +if [ -n "${MLM_PROMPTS}" ]; then + EXTRA_ARGS+=(--prompts "${MLM_PROMPTS}") +fi + +if [ -z ${MLM_MODEL_CKPT} ]; then + ${LAUNCH_SCRIPT} ${SCRIPT_DIR}/quantize.py \ + ${MODEL_ARGS} \ + --tensor-model-parallel-size ${TP} \ + --expert-tensor-parallel-size ${ETP} \ + --expert-model-parallel-size ${EP} \ + --pipeline-model-parallel-size ${PP} \ + --context-parallel-size ${CP} \ + --tokenizer-model ${TOKENIZER_MODEL} \ + --pretrained-model-path ${HF_MODEL_CKPT} \ + --save ${MLM_MODEL_SAVE} \ + --export-quant-cfg ${QUANT_CFG} \ + --references "${MLM_REF_LABEL}" \ + "${EXTRA_ARGS[@]}" +else + ${LAUNCH_SCRIPT} ${SCRIPT_DIR}/quantize.py \ + ${MODEL_ARGS} \ + --tensor-model-parallel-size ${TP} \ + --expert-tensor-parallel-size ${ETP} \ + --expert-model-parallel-size ${EP} \ + --pipeline-model-parallel-size ${PP} \ + --context-parallel-size ${CP} \ + --tokenizer-model ${TOKENIZER_MODEL} \ + --load ${MLM_MODEL_CKPT} \ + --save ${MLM_MODEL_SAVE} \ + --export-quant-cfg ${QUANT_CFG} \ + --references "${MLM_REF_LABEL}" \ + "${EXTRA_ARGS[@]}" +fi diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/requirements.txt b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..3c763e01cc11af036deecdc2ac27735ab6b21e3e --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/requirements.txt @@ -0,0 +1,6 @@ +diskcache +datasets +nvidia-modelopt +omegaconf +tensorstore!=0.1.46,!=0.1.72 +transformers diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/requirements_ssm.txt b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/requirements_ssm.txt new file mode 100644 index 0000000000000000000000000000000000000000..b57ae4d410428a9bf938890e0018dc604459012c --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/requirements_ssm.txt @@ -0,0 +1,2 @@ +mamba-ssm>=2.2.5 +causal-conv1d @ git+https://github.com/Dao-AILab/causal-conv1d diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/slurm/env_setup_template.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/slurm/env_setup_template.sh new file mode 100644 index 0000000000000000000000000000000000000000..12b59f06eedab70062ae9a88daa3979e880a3109 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/slurm/env_setup_template.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +HF_MODEL_CKPT=/workspace/scratch/meta-llama/Llama-3.2-1B-Instruct +TP=1 +ETP=1 +EP=1 +PP=1 diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/slurm/sbatch.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/slurm/sbatch.sh new file mode 100644 index 0000000000000000000000000000000000000000..3916c5de2b501f70911c597693e55edd7b73950d --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/slurm/sbatch.sh @@ -0,0 +1,63 @@ +#!/bin/bash + +#SBATCH -A +#SBATCH -p +#SBATCH --job-name= +#SBATCH --nodes=1 --ntasks-per-node=8 --gpus-per-node=8 +#SBATCH -t 04:00:00 +#SBATCH --exclusive --mem=0 --overcommit + +# Bash coloring +RED='\033[0;31m' +YELLOW='\033[0;33m' +GREEN='\033[0;32m' +BLUE='\033[0;34m' +PURPLE='\033[0;35m' +WHITE='\033[0;37m' + +# Predefined logging +MLM_ERROR="${RED}ERROR: ${WHITE}" +MLM_WARNING="${YELLOW}WARNING:${WHITE}" + +# CHANGE THE FOLLOWING TO YOUR DATA, MEGATRON, and CHECKPOINT DIR +if [[ -z ${USER_FSW} ]]; then + printf "${MLM_ERROR} Variable USER_FSW (read/write scratch space) must be set!\n" + exit 1 +fi + +if [ -z ${SANDBOX_DIR} ]; then + SANDBOX_DIR="$(pwd)" + printf "${MLM_WARNING} Variable SANDBOX_DIR not set! (default: ${SANDBOX_DIR})\n" +fi + +if [ -z ${SANDBOX_ENV_SETUP} ]; then + SANDBOX_ENV_SETUP=./env_setup_template.sh + printf "${MLM_WARNING} Variable SANDBOX_ENV_SETUP not set! (default: ${SANDBOX_ENV_SETUP})\n" +fi + +if [ -z ${CONTAINER_IMAGE} ]; then + CONTAINER_IMAGE="nvidia-modelopt-megatron:latest" + printf "${MLM_WARNING} Variable CONTAINER_IMAGE not set! (default: ${CONTAINER_IMAGE})\n" +fi + +if [ -z ${LAUNCH_SCRIPT} ]; then + LAUNCH_SCRIPT="python" + printf "${MLM_WARNING} Variable LAUNCH_SCRIPT not set! (default: ${LAUNCH_SCRIPT})\n" +fi + +# DO NOT MODIFY THE VALUES BELOW UNLESS YOU KNOW WHAT YOU ARE DOING!!! +DATETIME=`date +'date_%y-%m-%d_time_%H-%M-%S'` + +CONTAINER_MOUNT="${SANDBOX_DIR}:/workspace/nmm-sandbox,${USER_FSW}:/workspace/scratch" + +srun -l \ + --mpi=pmix \ + --output=%x_%j_$DATETIME.log \ + --container-image ${CONTAINER_IMAGE} \ + --container-workdir "/workspace/nmm-sandbox" \ + --container-mounts ${CONTAINER_MOUNT} \ + --export "HF_MODEL_CKPT=${HF_MODEL_CKPT},SANDBOX_ENV_SETUP=${SANDBOX_ENV_SETUP},LAUNCH_SCRIPT=${LAUNCH_SCRIPT}" \ + bash ${1} + +set +x + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/speculative.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/speculative.md new file mode 100644 index 0000000000000000000000000000000000000000..6ea9dea94783dcf59d46e4438a8336de79d04fd3 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/speculative.md @@ -0,0 +1,105 @@ +
+ +# Speculative Decoding + +
+ +[Medusa](https://arxiv.org/abs/2401.10774) and [EAGLE](https://arxiv.org/pdf/2401.15077) +training and model export are supported (fast decoding is supported through TensorRT-LLM). + +Medusa head top-1 accuracy is reported per step (**NOTE:** the accuracy here does not +translate to the acceptance rate described in the writeup. The top-1 of the 1st head +can however signal whether the training is converged). + + +## Training and Export Workflow + +In practice, speculative decoding should be combined with quantization (weights and kv-cache) +to achieve the the highest tokens-per-second-per-user (or TPS) without changing the quality of +the model. We provide quantization-aware training (QAT) receipt with self-distillation in the following. + + +### Model Convertion + +To ensure no quality degredation, base model is frozen and the draft model is attached as a +transformation. For Medusa, set `--export-algorithm medusa` and provide `--export-num-medusa-heads`. +For EAGLE, set `--export-algorithm eagle` and provide `--export-eagle-algorithm`. +the resulting model stored in `${MLM_MODEL_SAVE}` will have randomly initialized draft model weights. + +``` +python examples/post_training/modelopt/convert_model.py \ + --export-algorithm eagle \ + --export-eagle-algorithm eagle3 \ + --load ${MLM_MODEL_CKPT} --save ${MLM_MODEL_SAVE} ${MLM_EXTRA_ARGS} +``` + + +### Synthetic Data Generation + +Rather than learning the language and syntax, the draft model is trained to mimic the base +model output. As a result, self-synthesized data is crucial for the draft model accuracy +and acceptance rate (AR). + +For simplicity and efficiency, we use `vllm serve --quantization modelopt` to host an quantized +endpoint and we feed multi-turn conversation data to synthesize the assistant output. +See ModelOpt's example (https://github.com/NVIDIA/Model-Optimizer/tree/main/speculative_decoding) +for more details. The final output is stored as `jsonlines` in an OpenAI chat completion format. + + +### Quantization-Aware Training (QAT) + +For quantize-aware training (QAT), the process is `bf16 training`, `fake quantization`, `qat`. +Since the base model weights are frozen, the initial training is mainly to get an more accurate +range of the draft model activation and weights. We store a new checkpoint where the model +now has additional quantization scalars for both the base and draft models. We launch the +finetuning again to continue the training with fake quantization until convergence. + +```sh +python examples/post_training/modelopt/finetune.py \ + --load ${MLM_MODEL_SAVE} --save ${MLM_MODEL_SAVE} ${MLM_EXTRA_ARGS} +python examples/post_training/modelopt/quantize.py \ + --export-quant-cfg fp8 \ + --load ${MLM_MODEL_SAVE} --save ${MLM_QUANT_SAVE} ${MLM_EXTRA_ARGS} +python examples/post_training/modelopt/finetune.py \ + --load ${MLM_QUANT_SAVE} --save ${MLM_QUANT_SAVE} ${MLM_EXTRA_ARGS} +``` + +### Export Checkpoint + +Last, we export the Medusa heads or EAGLE module so that it can be deployed on runtime framework (i.e., TensorRT-LLM). + +```sh +python examples/post_training/modelopt/export.py \ + --export-dir ${CKPT_DIR} \ + -export-extra-modules \ + --load ${MLM_QUANT_SAVE} ${MLM_EXTRA_ARGS} +``` + +### TensorRT-LLM Deployment + +To serve the exported checkpoint with [TensorRT-LLM](https://github.com/NVIDIA/TensorRT-LLM), follow the sample commands below with the TensorRT-LLM GitHub repo: + +```sh +trtllm-serve --host 0.0.0.0 --port 8000 --backend pytorch --max_batch_size 32 --max_num_tokens 8192 --max_seq_len 8192 --tp_size 8 --extra_llm_api_options extra-llm-api-config.yml +``` + +`extra-llm-api-config.yml` is like this +```sh +enable_attention_dp: false +disable_overlap_scheduler: true +enable_autotuner: false + +cuda_graph_config: + max_batch_size: 1 + +speculative_config: + decoding_type: Eagle + max_draft_len: 3 + speculative_model_dir: + +kv_cache_config: + enable_block_reuse: false +``` + + + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/train.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/train.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ebb8bf3d76edeaf425ec352e6f9c9469cb78b71 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/train.sh @@ -0,0 +1,93 @@ +#!/bin/bash + +SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" + +# Common arguments and base model specific arguments +source "${SCRIPT_DIR}/conf/arguments.sh" + + +# Set up cache dir for HF to avoid out of space error +export HF_DATASETS_CACHE="/tmp/hf_datasets_cache" + +# Extra arguments of this script +MLM_DEFAULT_ARGS=" \ + --modelopt-enabled \ + --distributed-timeout-minutes 60 \ + --auto-detect-ckpt-format \ + --export-te-mcore-model \ +" + + +if [ -z ${MLM_MODEL_SAVE} ]; then + MLM_MODEL_SAVE=${MLM_MODEL_CKPT} + printf "${MLM_WARNING} Variable ${PURPLE}MLM_MODEL_SAVE${WHITE} is not set (default: ${MLM_MODEL_CKPT})!\n" +fi + +if [ -z ${MLM_DATA_ARGS} ]; then + MLM_DATA_ARGS=" \ + --train-samples 128000 \ + --lr-decay-samples 128000 \ + --lr-warmup-samples 0 \ + --sft \ + --tokenizer-type SFTTokenizer \ + --per-split-data-args-path ${BLEND_PATH} \ + " +fi + +if [ -z ${MLM_TRAIN_ARGS} ]; then + MLM_TRAIN_ARGS=" \ + --no-gradient-accumulation-fusion \ + --micro-batch-size 1 \ + --attention-dropout 0.0 \ + --hidden-dropout 0.0 \ + --no-check-for-nan-in-loss-and-grad \ + " +fi + +if [ -z ${MLM_OPTIM_ARGS} ]; then + MLM_OPTIM_ARGS=" \ + --lr 5.0e-5 \ + --min-lr 1.0e-7 \ + --lr-decay-style cosine \ + --clip-grad 1.0 \ + --weight-decay 0.0 \ + --adam-beta1 0.9 \ + --adam-beta2 0.95 \ + --init-method-std 0.010 \ + --use-distributed-optimizer \ + " +fi + +if [ -z ${MLM_EVAL_ARGS} ]; then + MLM_EVAL_ARGS=" \ + --eval-iters 1 \ + --eval-interval 1000 \ + --save-interval 1000 \ + --log-interval 100 \ + " +fi + +export HF_TOKEN=${HF_TOKEN} + +if [[ ${MODEL_ARGS} == *"MambaModel"* ]]; then + PRETRAIN_EXE=${SCRIPT_DIR}/../../../pretrain_mamba.py +else + PRETRAIN_EXE=${SCRIPT_DIR}/../../../pretrain_gpt.py +fi + +${LAUNCH_SCRIPT} ${PRETRAIN_EXE} \ + ${MODEL_ARGS} \ + --tensor-model-parallel-size ${TP} \ + --expert-tensor-parallel-size ${ETP} \ + --expert-model-parallel-size ${EP} \ + --pipeline-model-parallel-size ${PP} \ + --context-parallel-size ${CP} \ + --tokenizer-model ${TOKENIZER_MODEL} \ + --load ${MLM_MODEL_CKPT} \ + --save ${MLM_MODEL_SAVE} \ + ${MLM_DATA_ARGS} \ + ${MLM_OPTIM_ARGS} \ + ${MLM_TRAIN_ARGS} \ + ${MLM_EVAL_ARGS} \ + ${MLM_RESUME_ARGS} \ + ${MLM_DEFAULT_ARGS} ${MLM_EXTRA_ARGS} diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/utils.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fd554caa6d8175ba8de324c16a73fbc8d6f0050f --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/utils.py @@ -0,0 +1,25 @@ +# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. + +"""Shared utilities for modelopt post-training scripts.""" +import os +import sys + +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))) + +from megatron.training import get_tokenizer + + +def get_hf_tokenizer(): + """Return the underlying HuggingFace tokenizer, unwrapping Megatron-Core nesting. + + Megatron-Core tokenizers are nested (e.g. get_tokenizer()._tokenizer may itself + have a .tokenizer or ._tokenizer attribute holding the actual HF tokenizer). + This helper unwraps one level of that nesting. + """ + tokenizer = get_tokenizer()._tokenizer + tok_attrs = ["tokenizer", "_tokenizer"] + for attr in tok_attrs: + if hasattr(tokenizer, attr): + tokenizer = getattr(tokenizer, attr) + break + return tokenizer diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/validate.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/validate.py new file mode 100644 index 0000000000000000000000000000000000000000..8b8f1ffc9dda53484bacfc3240599a71a8db0ed7 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/validate.py @@ -0,0 +1,142 @@ +# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. + +"""Sample Generate GPT.""" +import functools +import json +import os +import sys +import warnings + +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))) + +import torch +from modelopt.torch.speculative.plugins.megatron_eagle import MegatronARValidation + +from megatron.post_training.arguments import add_modelopt_args +from megatron.post_training.checkpointing import load_modelopt_checkpoint +from megatron.post_training.model_builder import modelopt_gpt_mamba_builder +from megatron.post_training.utils import get_mtbench_chat_data +from megatron.training import get_args, get_model, initialize_megatron +from utils import get_hf_tokenizer +from megatron.training.utils import print_rank_0, unwrap_model +from model_provider import model_provider + +warnings.filterwarnings('ignore') + + + +def add_ar_validation_args(parser): + """Add additional arguments for ModelOpt acceptance rate validation.""" + group = parser.add_argument_group(title='ModelOpt ar validation') + group.add_argument( + "--osl", type=int, default=64, help="Output sequence length." + ) + parser.add_argument( + "--prompts-path", + type=str, + default=None, + help="Path to the prompts json file. If not provided, MTBench will be used.", + ) + parser.add_argument( + "--ground-truth-path", + type=str, + default=None, + help="Path to the ground truth pt file.", + ) + parser.add_argument( + "--steps", type=int, default=1, help="Only used in EAGLE." + ) + parser.add_argument( + "--save-ground-truth-path", + type=str, + default=None, + help="Save path for the ground truth pt file.", + ) + + add_modelopt_args(parser) + return parser + + +def check_arguments(): + """Checking user arguments.""" + args = get_args() + if args.num_layers_per_virtual_pipeline_stage is not None: + print_rank_0("Interleaved pipeline schedule is not yet supported for text generation.") + exit() + + if hasattr(args, 'moe_grouped_gemm') and args.moe_grouped_gemm == True: + print_rank_0("WARNING: Forcing moe_grouped_gemm to False for PTQ and export.") + args.moe_grouped_gemm = False + + +def get_current_memory_info(): + remaining_mem, total_mem = torch.cuda.mem_get_info() + info = "rank {:02} memory remaining {:03}% ({}/{} MB) ".format( + torch.distributed.get_rank(), + int(remaining_mem * 100 / total_mem), + remaining_mem // 1048576, + total_mem // 1048576, + ) + return info + + +def report_current_memory_info(): + """Report current memory usage.""" + print(get_current_memory_info(), flush=True) + torch.distributed.barrier() + + + + +if __name__ == "__main__": + initialize_megatron( + extra_args_provider=add_ar_validation_args, + args_defaults={ + 'tokenizer_type': 'HuggingFaceTokenizer', + 'no_load_rng': True, + 'no_load_optim': True, + }, + ) + + check_arguments() + + args = get_args() + + if not args.prompts_path: + dataset = get_mtbench_chat_data() + prompts = [[sample["conversations"][0]] for sample in dataset] + else: + with open(args.prompts_path, "r") as f: + prompts = [json.loads(line) for line in f] + + if args.ground_truth_path is not None: + ground_truth = torch.load(args.ground_truth_path) + ground_truth = [gt.to(torch.cuda.current_device()) for gt in ground_truth] + else: + ground_truth = [None for _ in range(len(prompts))] + + tokenizer = get_hf_tokenizer() + model = get_model(functools.partial(model_provider, modelopt_gpt_mamba_builder), wrap_with_ddp=False) + + report_current_memory_info() + + if args.load is not None: + load_modelopt_checkpoint(model, strict=not args.untie_embeddings_and_output_weights) + print_rank_0("Done loading checkpoint") + + + unwrapped_model = unwrap_model(model)[0] + unwrapped_model.eval() + + validator = MegatronARValidation(unwrapped_model, tokenizer) + gt = [] + ar = [] + for prompt, truth in zip(prompts, ground_truth): + output = validator.validate(args.osl, prompt, ground_truth=truth, steps=args.steps) + gt.append(output[0]) + ar.append(output[1]) + print_rank_0("Acceptance Rate: " + str(ar)) + print_rank_0("Average: " + str(sum(ar)/len(ar))) + + if args.save_ground_truth_path is not None: + torch.save(gt, args.save_ground_truth_path) diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/validate.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/validate.sh new file mode 100644 index 0000000000000000000000000000000000000000..796231e508e1897675a4d25b05f09d48156a3575 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/post_training/modelopt/validate.sh @@ -0,0 +1,60 @@ +#!/bin/bash + +SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" + +# Common arguments and base model specific arguments +source "${SCRIPT_DIR}/conf/arguments.sh" + +# Extra arguments of this script +MLM_DEFAULT_ARGS="--finetune --auto-detect-ckpt-format --export-te-mcore-model" +MLM_EXTRA_ARGS="--sequence-parallel" + + +if [ -z ${MLM_MODEL_CKPT} ]; then + printf "${MLM_ERROR} Variable ${PURPLE}MLM_MODEL_CKPT${WHITE} must be set!\n" + exit 1 +fi + +if [ -z ${PROMPTS_PATH} ]; then + PROMPT_ARGS="" +else + PROMPT_ARGS="--prompts-path ${PROMPTS_PATH}" +fi + +if [ -z ${STEPS} ]; then + STEPS=1 +fi + +if [ -z ${SAVE_GT_PATH} ]; then + SAVE_ARGS="" +else + SAVE_ARGS="--save-ground-truth-path ${SAVE_GT_PATH}" +fi + +if [ -z ${GT_PATH}]; then + GT_ARGS="" +else + GT_ARGS="--ground-truth-path ${GT_PATH}" +fi + +if [ -z ${OSL} ]; then + STEPS=64 +fi + +export HF_TOKEN=${HF_TOKEN} + +${LAUNCH_SCRIPT} ${SCRIPT_DIR}/validate.py \ + ${MODEL_ARGS} \ + --tensor-model-parallel-size ${TP} \ + --expert-tensor-parallel-size ${ETP} \ + --expert-model-parallel-size ${EP} \ + --pipeline-model-parallel-size ${PP} \ + --tokenizer-model ${TOKENIZER_MODEL} \ + --load ${MLM_MODEL_CKPT} \ + --steps ${STEPS} \ + --osl ${OSL} \ + ${PROMPT_ARGS} \ + ${GT_ARGS} \ + ${SAVE_ARGS} \ + ${MLM_DEFAULT_ARGS} ${MLM_EXTRA_ARGS} + diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/run_simple_mcore_train_loop.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/run_simple_mcore_train_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..24aea52b2b21ab68e9cb4103b299e68d48cd1e49 --- /dev/null +++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/run_simple_mcore_train_loop.py @@ -0,0 +1,270 @@ +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. + +import os +import torch +from torch.optim import Adam +from torch.utils.data import DataLoader +from functools import partial +from pathlib import Path +from typing import Any, Callable, Dict, Tuple, Iterator + +from megatron.core import parallel_state +from megatron.core import dist_checkpointing +from megatron.core.pipeline_parallel.schedules import get_forward_backward_func +from megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seed +from megatron.core.transformer.transformer_config import TransformerConfig +from megatron.core.models.gpt.gpt_model import GPTModel +from megatron.core.models.gpt.gpt_layer_specs import get_gpt_layer_local_spec +from megatron.core.datasets.utils import compile_helpers +from megatron.core.datasets.blended_megatron_dataset_builder import ( + BlendedMegatronDatasetBuilder, +) +from megatron.core.datasets.gpt_dataset import GPTDatasetConfig, MockGPTDataset +from megatron.core.distributed import DistributedDataParallel +from megatron.core.distributed import DistributedDataParallelConfig +from megatron.core.distributed.finalize_model_grads import finalize_model_grads +from megatron.core.tokenizers import MegatronTokenizer + + +_SEQUENCE_LENGTH: int = 64 + + +def initialize_distributed( + tensor_model_parallel_size: int = 1, pipeline_model_parallel_size: int = 1 +) -> None: + """ + Initialize torch.distributed and Megatron-Core model parallel groups. + + Args: + tensor_model_parallel_size: Number of GPUs for tensor model parallelism. + pipeline_model_parallel_size: Number of GPUs for pipeline model parallelism. + """ + parallel_state.destroy_model_parallel() + + # Torch setup for distributed training + rank: int = int(os.environ["RANK"]) + world_size: int = int(os.environ["WORLD_SIZE"]) + local_rank: int = int(os.environ["LOCAL_RANK"]) + + torch.cuda.set_device(local_rank) + torch.distributed.init_process_group( + backend="nccl", rank=rank, world_size=world_size + ) + + # Megatron core distributed training initialization + parallel_state.initialize_model_parallel( + tensor_model_parallel_size, pipeline_model_parallel_size + ) + + +def model_provider() -> GPTModel: + """ + Build and return a simple GPT model for demonstration. + + Returns: + GPTModel: A small GPT model with 2 layers for testing. + """ + transformer_config: TransformerConfig = TransformerConfig( + num_layers=2, + hidden_size=12, + num_attention_heads=4, + use_cpu_initialization=True, + pipeline_dtype=torch.float32, + ) + + gpt_model: GPTModel = GPTModel( + config=transformer_config, + transformer_layer_spec=get_gpt_layer_local_spec(), + vocab_size=100, + max_sequence_length=_SEQUENCE_LENGTH, + ) + + return gpt_model + + +def get_train_data_iterator() -> Iterator: + """ + Create a mock dataset and return a data iterator. + + Returns: + Iterator: Data iterator for training batches. + """ + if torch.distributed.is_available() and torch.distributed.is_initialized(): + if torch.distributed.get_rank() == 0: + compile_helpers() + torch.distributed.barrier() + else: + compile_helpers() + + config: GPTDatasetConfig = GPTDatasetConfig( + random_seed=0, + sequence_length=_SEQUENCE_LENGTH, + reset_position_ids=False, + reset_attention_mask=False, + eod_mask_loss=False, + tokenizer=MegatronTokenizer.from_pretrained( + metadata_path={"library": "null-text"}, + vocab_size=_SEQUENCE_LENGTH, + ), + mid_level_dataset_surplus=0.005, + ) + + datasets = BlendedMegatronDatasetBuilder( + MockGPTDataset, [1000, None, None], lambda: True, config + ).build() + + train_dataloader: DataLoader = DataLoader(datasets[0], batch_size=8, shuffle=True) + + train_iterator: Iterator = iter(train_dataloader) + + return train_iterator + + +def forward_step_func( + data_iterator: Iterator, model: torch.nn.Module +) -> Tuple[torch.Tensor, Callable]: + """ + Forward step function that computes model output and returns loss function. + + Args: + data_iterator: Iterator providing training batches. + model: The GPT model to train. + + Returns: + Tuple of (output_tensor, loss_function) where loss_function is a partial + function that will compute the final loss when called. + """ + + def loss_func( + loss_mask: torch.Tensor, output_tensor: torch.Tensor + ) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]: + losses: torch.Tensor = output_tensor.float() + loss_mask = loss_mask.view(-1).float() + loss: torch.Tensor = torch.sum(losses.view(-1) * loss_mask) / loss_mask.sum() + # If you have data parallel reduce loss across data parallel groups. + # If pipeline parallel, loss computation is done only in last stage. + + return loss, {"lm loss": loss} + + data: Dict[str, torch.Tensor] = next(data_iterator) + tokens: torch.Tensor = data["tokens"].to(device) + attention_mask: torch.Tensor = data["attention_mask"].to(device) + position_ids: torch.Tensor = data["position_ids"].to(device) + labels: torch.Tensor = data["labels"].to(device) + loss_mask: torch.Tensor = data["loss_mask"].to(device) + + output_tensor: torch.Tensor = model( + tokens, position_ids, attention_mask, labels=labels + ) + + return output_tensor, partial(loss_func, loss_mask) + + +def save_distributed_checkpoint( + checkpoint_path: str, gpt_model: torch.nn.Module +) -> None: + """ + Save model checkpoint using Megatron-Core distributed checkpointing. + + Args: + checkpoint_path: Directory path to save checkpoint. + gpt_model: The model to checkpoint (may be wrapped with DDP). + """ + # Access underlying model if wrapped with DDP + model: torch.nn.Module = ( + gpt_model.module if hasattr(gpt_model, "module") else gpt_model + ) + sharded_state_dict: Dict = model.sharded_state_dict(prefix="") + dist_checkpointing.save( + sharded_state_dict=sharded_state_dict, checkpoint_dir=checkpoint_path + ) + + +def load_distributed_checkpoint( + checkpoint_path: str, gpt_model: torch.nn.Module +) -> torch.nn.Module: + """ + Load model checkpoint using Megatron-Core distributed checkpointing. + + Args: + checkpoint_path: Directory path to load checkpoint from. + gpt_model: The model to load into (may be wrapped with DDP). + + Returns: + The model with loaded checkpoint weights. + """ + # Access underlying model if wrapped with DDP + model: torch.nn.Module = ( + gpt_model.module if hasattr(gpt_model, "module") else gpt_model + ) + sharded_state_dict: Dict = model.sharded_state_dict(prefix="") + checkpoint: Dict = dist_checkpointing.load( + sharded_state_dict=sharded_state_dict, checkpoint_dir=checkpoint_path + ) + model.load_state_dict(checkpoint) + return gpt_model + + +if __name__ == "__main__": + initialize_distributed(tensor_model_parallel_size=2, pipeline_model_parallel_size=1) + model_parallel_cuda_manual_seed(123) + + gpt_model: GPTModel = model_provider() + device: torch.device = torch.device("cuda") + gpt_model.to(device) + + # Wrap model with DistributedDataParallel for proper gradient synchronization. + # This provides the finish_grad_sync() method required by finalize_model_grads(). + config: TransformerConfig = gpt_model.config + ddp_config: DistributedDataParallelConfig = DistributedDataParallelConfig( + grad_reduce_in_fp32=False, + overlap_grad_reduce=False, + use_distributed_optimizer=False, + ) + gpt_model = DistributedDataParallel( + config=config, + ddp_config=ddp_config, + module=gpt_model, + ) + + optim: Adam = Adam(gpt_model.parameters()) + + train_iterator: Iterator = get_train_data_iterator() + + forward_backward_func: Callable[..., Dict[str, Any]] = get_forward_backward_func() + + # Running the model for 5 iterations + for iteration in range(5): + optim.zero_grad() + + losses_reduced: Dict[str, Any] = forward_backward_func( + forward_step_func=forward_step_func, + data_iterator=train_iterator, + model=gpt_model, + num_microbatches=1, + seq_length=_SEQUENCE_LENGTH, + micro_batch_size=8, + decoder_seq_length=_SEQUENCE_LENGTH, + forward_only=False, + ) + + # Finalize model gradients: all-reduce across DP and TP groups. + # This synchronizes gradients for non-tensor-parallel parameters (e.g., LayerNorm) + # across tensor parallel ranks and all gradients across data parallel ranks. + finalize_model_grads([gpt_model]) + + optim.step() + + print(f"Iteration {iteration}: Losses reduced: {losses_reduced}") + + # Saving the model + ckpt_path: str = os.getcwd() + "/ckpt" + Path(ckpt_path).mkdir(exist_ok=True) + save_distributed_checkpoint(gpt_model=gpt_model, checkpoint_path=ckpt_path) + + # Loading the model + gpt_model = load_distributed_checkpoint( + gpt_model=gpt_model, checkpoint_path=ckpt_path + ) + gpt_model.to(device) + print("Successfully loaded the model")