hyttyh111222333 commited on
Commit
0e9b802
·
verified ·
1 Parent(s): eff6ef2

Upload FAI-Bench task files batch 62

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/datasets.md +13 -0
  2. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/dist_checkpointing.md +133 -0
  3. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/dist_checkpointing.strategies.md +16 -0
  4. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/distributed.md +19 -0
  5. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/fusions.md +20 -0
  6. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/index.md +25 -0
  7. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/pipeline_parallel.md +16 -0
  8. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/tensor_parallel.md +17 -0
  9. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/transformer.md +19 -0
  10. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/index.md +20 -0
  11. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/internal/index.md +19 -0
  12. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/internal/num_microbatches_calculator.md +13 -0
  13. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/internal/optimizer_param_scheduler.md +13 -0
  14. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/index.md +21 -0
  15. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.bert.md +13 -0
  16. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.gpt.md +13 -0
  17. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.md +23 -0
  18. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.t5.md +11 -0
  19. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/router_replay.md +186 -0
  20. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/install.md +123 -0
  21. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/overview.md +93 -0
  22. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/quickstart.md +68 -0
  23. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/releasenotes.md +19 -0
  24. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/models/index.md +26 -0
  25. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/models/llms.md +59 -0
  26. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/models/multimodal.md +70 -0
  27. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/custom_fsdp.md +195 -0
  28. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/index.md +27 -0
  29. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/megatron_rl.md +55 -0
  30. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/moe.md +22 -0
  31. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/multi_latent_attention.md +21 -0
  32. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/pipeline_parallel_layout.md +35 -0
  33. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/__init__.py +1 -0
  34. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/README.md +112 -0
  35. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/annotations/filter-selfgeneration.py +75 -0
  36. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/annotations/perspective_api_annotate.py +182 -0
  37. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/annotations/preprocess.sh +14 -0
  38. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/finetune_gpt.py +159 -0
  39. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/finetune_gpt_distributed-1.3b.sh +63 -0
  40. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/generate-1.3b.sh +41 -0
  41. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/generate_samples_gpt.py +260 -0
  42. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/perspective_api.py +170 -0
  43. 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 +42 -0
  44. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/README.md +5 -0
  45. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/data_processing.sh +83 -0
  46. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/eval_knwl_generation.sh +43 -0
  47. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/eval_resp_generation.sh +64 -0
  48. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/prep_resp_gen.sh +18 -0
  49. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/prompt_knwl_gen.sh +46 -0
  50. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/prompt_resp_gen.sh +46 -0
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/datasets.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # datasets package
11
+
12
+ ```{include} ../../../megatron/core/datasets/readme.md
13
+ ```
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/dist_checkpointing.md ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # dist_checkpointing package
11
+
12
+ A library for saving and loading the distributed checkpoints.
13
+ A *distributed checkpoint* in Megatron Core uses the ``torch_dist`` format,
14
+ a custom checkpointing mechanism built on top of PyTorch's native
15
+ checkpointing capabilities.
16
+
17
+ A key property of distributed checkpoints is that a checkpoint saved under one
18
+ parallel configuration (tensor, pipeline, or data parallelism) can be loaded
19
+ under a different parallel configuration. This enables flexible scaling and
20
+ resharding of models across heterogeneous training setups.
21
+
22
+ Using the library requires defining sharded state_dict dictionaries with functions from *mapping* and *optimizer* modules.
23
+ Those state dicts can be saved or loaded with a *serialization* module using strategies from *strategies* module.
24
+
25
+ ## Safe Checkpoint Loading
26
+
27
+ Since **PyTorch 2.6**, the default behavior of `torch.load` is `weights_only=True`.
28
+ This ensures that only tensors and allow-listed classes are loaded, reducing the risk of arbitrary code execution.
29
+
30
+ If you encounter an error such as:
31
+
32
+ ```bash
33
+ WeightsUnpickler error: Unsupported global: GLOBAL argparse.Namespace was not an allowed global by default.
34
+ ```
35
+
36
+ you can fix it by explicitly allow-listing the missing class in your script:
37
+
38
+ ```python
39
+ import torch, argparse
40
+
41
+ torch.serialization.add_safe_globals([argparse.Namespace])
42
+ ```
43
+
44
+ ## Checkpointing Distributed Optimizer
45
+
46
+ ### Checkpoint Compatibility and Optimizer State Formats
47
+
48
+ Beginning with **mcore v0.14**, the ``flattened_range`` attribute was removed from ``dist_checkpointing``. As a result:
49
+
50
+ - 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.
51
+ - 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.
52
+
53
+ ### Workaround: Loading legacy optimizer states with ToT MCore
54
+
55
+ **Step 1: Convert the legacy checkpoint using mcore v0.15.0**
56
+
57
+ Run a dummy training job with mcore v0.15.0 to re-save the checkpoint with new optimizer states format.
58
+
59
+ ```bash
60
+ MODEL_TRAIN_PARAMS=(
61
+ # Define model architecture and training parameters here
62
+ )
63
+ OLD_CKPT=/workspace/mcore_ckpt_old
64
+ CONVERTED_CKPT=/workspace/mcore_ckpt_0.15.0
65
+
66
+ torchrun --nproc_per_node=8 /opt/megatron-lm/pretrain_gpt.py \
67
+ --save-interval 1 \
68
+ --eval-interval 1 \
69
+ --exit-interval 1 \
70
+ --eval-iters 1 \
71
+ --use-distributed-optimizer \
72
+ --save ${CONVERTED_CKPT} \
73
+ --load ${OLD_CKPT} \
74
+ --ckpt-format torch_dist \
75
+ "${MODEL_TRAIN_PARAMS[@]}"
76
+ ```
77
+
78
+ **Step 2: Load the converted checkpoint with ToT MCore**
79
+
80
+ Use the converted checkpoint as the input for continued training with ToT MCore.
81
+
82
+ ```bash
83
+ MODEL_TRAIN_PARAMS=(
84
+ # Define model architecture and training parameters here
85
+ )
86
+ NEW_CKPT=/workspace/mcore_ckpt_new
87
+ CONVERTED_CKPT=/workspace/mcore_ckpt_0.15.0
88
+
89
+ torchrun --nproc_per_node=8 /opt/megatron-lm/pretrain_gpt.py \
90
+ --use-distributed-optimizer \
91
+ --save ${NEW_CKPT} \
92
+ --load ${CONVERTED_CKPT} \
93
+ --ckpt-format torch_dist \
94
+ "${MODEL_TRAIN_PARAMS[@]}"
95
+ ```
96
+
97
+ After this step, training can proceed normally using ToT MCore with fully supported optimizer state loading.
98
+
99
+ ## Distributed Optimizer Checkpoint Formats
100
+
101
+ The refactor of the Distributed Optimizer introduces **two checkpoint formats**:
102
+
103
+ - dp_reshardable (Default)
104
+ - Fast save/load performance.
105
+ - Not reshardable — not possible to change model parallelism when using this format.
106
+ - Recommended for general training when model parallelism changes are not needed.
107
+ - fully_reshardable
108
+ - Fully reshardable — supports arbitrary changes in model parallelism.
109
+ - Slower than dp_reshardable.
110
+ - Enabled via the ``--dist-ckpt-optim-fully-reshardable`` flag.
111
+
112
+ ### Workflow for Changing Model Parallelism
113
+
114
+ You can combine formats to optimize both flexibility and performance:
115
+
116
+ 1. Train using ``dp_reshardable`` (default) for faster checkpointing.
117
+ 2. When you need to change model parallelism:
118
+
119
+ - Stop training.
120
+ - Change model parallelism for train config.
121
+ - Resume training with ``--dist-ckpt-optim-fully-reshardable``.
122
+
123
+ 3. Save at least one checkpoint under the new model parallel configuration.
124
+ 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``.
125
+
126
+ ## Subpackages
127
+
128
+ ```{toctree}
129
+ :maxdepth: 4
130
+
131
+ dist_checkpointing.strategies
132
+ ```
133
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/dist_checkpointing.strategies.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # dist_checkpointing.strategies package
11
+
12
+ Package defining different checkpoint formats (backends) and saving/loading algorithms (strategies).
13
+
14
+ 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.
15
+ Strategies are passed to `dist_checkpointing.load` and `dist_checkpointing.save` functions and control the actual saving/loading procedure.
16
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/distributed.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # distributed package
11
+
12
+ This package contains various utilities to finalize model weight gradients
13
+ on each rank before the optimizer step. This includes a distributed data
14
+ parallelism wrapper to all-reduce or reduce-scatter the gradients across
15
+ data-parallel replicas, and a `finalize_model_grads` method to
16
+ synchronize gradients across different parallelism modes (e.g., 'tied'
17
+ layers on different pipeline stages, or gradients for experts in a MoE on
18
+ different ranks due to expert parallelism).
19
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/fusions.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # fusions package
11
+
12
+ This package provides modules that provide commonly fused
13
+ operations. Fusing operations improves compute efficiency by
14
+ increasing the amount of work done each time a tensor is read from
15
+ memory. To perform the fusion, modules in this either rely on PyTorch
16
+ functionality for doing just-in-time compilation
17
+ (i.e. `torch.jit.script` in older PyTorch versions of `torch.compile`
18
+ in recent versions), or call into custom kernels in external libraries
19
+ such as Apex or TransformerEngine.
20
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/index.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # Core APIs
11
+
12
+ Low-level API reference for core Megatron components.
13
+
14
+ ```{toctree}
15
+ :maxdepth: 2
16
+
17
+ transformer
18
+ tensor_parallel
19
+ pipeline_parallel
20
+ fusions
21
+ distributed
22
+ datasets
23
+ dist_checkpointing
24
+ dist_checkpointing.strategies
25
+ ```
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/pipeline_parallel.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # pipeline_parallel package
11
+
12
+ This package contains implementations for two different pipeline parallelism
13
+ 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)
14
+ for details), and a default no-pipelining schedule. It also contains methods
15
+ for the point-to-point communication that is needed between pipeline stages.
16
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/tensor_parallel.md ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # tensor_parallel package
11
+
12
+ This package contains an implementation for tensor parallelism in transformer
13
+ models (see [Megatron-LM: Training Multi-Billion Parameter Language Models
14
+ Using Model Parallelism](https://arxiv.org/abs/1909.08053) and [Reducing
15
+ Activation Recomputation in Large Transformer Models](https://arxiv.org/abs/2205.05198)
16
+ for details).
17
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/core/transformer.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # transformer package
11
+
12
+ The `transformer` package provides a customizable and configurable
13
+ implementation of the transformer model architecture. Each component
14
+ of a transformer stack, from entire layers down to individual linear
15
+ layers, can be customized by swapping in different PyTorch modules
16
+ using the "spec" parameters. The
17
+ configuration of the transformer (hidden size, number of layers,
18
+ number of attention heads, etc.) is provided via a `TransformerConfig`
19
+ object.
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/index.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # API Guide
11
+
12
+ API reference documentation for Megatron Core components.
13
+
14
+ ```{toctree}
15
+ :maxdepth: 3
16
+
17
+ models/index
18
+ core/index
19
+ internal/index
20
+ ```
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/internal/index.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # Internal Utilities
11
+
12
+ Internal utility APIs.
13
+
14
+ ```{toctree}
15
+ :maxdepth: 2
16
+
17
+ num_microbatches_calculator
18
+ optimizer_param_scheduler
19
+ ```
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/internal/num_microbatches_calculator.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # Microbatches Calculator
11
+
12
+ This api is used to calculate the number of microbatches required to fit a given model on a given batch size.
13
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/internal/optimizer_param_scheduler.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # Optimizer Parameters Scheduler
11
+
12
+ This api is used to calculate the learning rate and weight decay for the optimizer.
13
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/index.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # Model APIs
11
+
12
+ API reference for Megatron Core model implementations.
13
+
14
+ ```{toctree}
15
+ :maxdepth: 2
16
+
17
+ models
18
+ models.gpt
19
+ models.bert
20
+ models.t5
21
+ ```
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.bert.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # models.bert package
11
+
12
+ 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 .
13
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.gpt.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # models.gpt package
11
+
12
+ 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.
13
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # models package
11
+
12
+ 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.
13
+
14
+ ## Subpackages
15
+
16
+ ```{toctree}
17
+ :maxdepth: 4
18
+
19
+ models.gpt
20
+ models.t5
21
+ models.bert
22
+ ```
23
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/models/models.t5.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # models.t5 package
11
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/api-guide/router_replay.md ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # Design Document: MoE Router Replay Feature
11
+
12
+ ## 1. Overview
13
+
14
+ This document provides a detailed description of the "Router Replay" feature implemented within the Megatron-LM Core for Mixture-of-Experts (MoE) models.
15
+
16
+ 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.
17
+
18
+ ## 2. Motivation
19
+
20
+ * **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.
21
+ * **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.
22
+ * **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.
23
+
24
+ ## 3. Design and Architecture
25
+
26
+ 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.
27
+
28
+ * **Core Components**:
29
+ * `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.
30
+ * `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.
31
+
32
+ * **Workflow**:
33
+ The feature supports different modes, such as recording and replaying, controlled by a `RouterReplayAction`.
34
+
35
+ 1. **Enabling the Feature**: The user sets `moe_enable_routing_replay` to `True` in the model configuration.
36
+ 2. **Initialization**: When `moe_enable_routing_replay` is true, each `TopKRouter` creates its own `RouterReplay` instance.
37
+ 3. **Mode Configuration**: The user must programmatically set the desired router replay action (e.g., `record`, `forward_replay`, `backward_replay`) on the `RouterReplay` instances.
38
+ 4. **Execution Flow (within a mini-batch)**:
39
+ * **Forward Pass**:
40
+ * For each micro-batch, the `topk_routing_with_score_function` checks the `router_replay_action`.
41
+ * **In `record` mode**: The dynamically computed `top-k` expert indices are captured and stored.
42
+ * **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.
43
+ * **Backward Pass**:
44
+ * For each micro-batch (processed in reverse order in pipeline parallelism), the `router_replay_action` is checked again.
45
+ * **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.
46
+
47
+ ## 4. Implementation Details
48
+
49
+ The implementation cleanly separates the replay logic from the router's core computation.
50
+
51
+ * **`megatron/core/transformer/transformer_config.py`**:
52
+ * Adds the configuration option `moe_enable_routing_replay: bool = False`.
53
+
54
+ * **`megatron/core/transformer/moe/moe_utils.py`**:
55
+ * Introduces the `RouterReplay` class to manage the state for recording and replaying routing decisions for a single MoE layer.
56
+ * `target_topk_idx`: An attribute holding the expert indices for the current micro-batch during forward replay mode.
57
+ * `recorded_topk_idx`: An attribute for storing the computed expert indices when in record mode.
58
+ * `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.
59
+ * `set_target_indices()`: A method to load the replay indices into `target_topk_idx` for the forward pass.
60
+ * `record_indices()`: A method to save the computed indices.
61
+ * 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.
62
+
63
+ ### Training recompute usage
64
+
65
+ - During forward replay, `set_target_indices()` prepares `replay_backward_list` so each micro-batch’s indices are available for recomputation.
66
+ - During recompute/backward, set action to `REPLAY_BACKWARD` so indices are consumed in FIFO order to mirror the forward sequence.
67
+
68
+ ## 5. Usage Guide
69
+
70
+ 1. **Enable & Instantiate**
71
+ - Create one `RouterReplay` instance per MoE router layer when building the model.
72
+ - Optionally use the global helpers to set/clear actions across all layers.
73
+ 2. **Record Routing Decisions**
74
+ - Set action: `RouterReplay.set_global_router_replay_action(RouterReplayAction.RECORD)`.
75
+ - Run the model; retrieve per-layer indices via `RouterReplay.get_recorded_data()` and persist.
76
+ 3. **Forward Replay**
77
+ - Load indices and distribute: `RouterReplay.set_replay_data(list_of_tensors)`.
78
+ - Set action: `RouterReplay.set_global_router_replay_action(RouterReplayAction.REPLAY_FORWARD)`.
79
+ - Run the model; dynamic top‑k is bypassed and target indices are used.
80
+ 4. **Backward Replay**
81
+ - For training recomputation (activation checkpointing or pipeline recompute), set action: `REPLAY_BACKWARD` during recomputation.
82
+ - Per micro‑batch indices are consumed from `replay_backward_list` in FIFO order.
83
+ 5. **Cleanup**
84
+ - 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.
85
+
86
+ ### Quick usage with `topk_routing_with_score_function`
87
+
88
+ ```python
89
+ import torch
90
+ from megatron.core.transformer.moe.router_replay import RouterReplay, RouterReplayAction
91
+ from megatron.core.transformer.moe.moe_utils import topk_routing_with_score_function
92
+
93
+ rr = RouterReplay()
94
+
95
+ # Record
96
+ RouterReplay.set_global_router_replay_action(RouterReplayAction.RECORD)
97
+ logits = torch.randn(8, 16)
98
+ probs_rec, routing_map_rec = topk_routing_with_score_function(
99
+ logits=logits, topk=2, use_pre_softmax=False, score_function="softmax", router_replay=rr,
100
+ )
101
+ recorded = rr.get_recorded_indices()
102
+ torch.save(recorded, "/tmp/replay.pt")
103
+
104
+ # Forward replay
105
+ rr.clear_router_replay_action()
106
+ rr.set_router_replay_action(RouterReplayAction.REPLAY_FORWARD)
107
+ target = torch.load("/tmp/replay.pt")
108
+ rr.set_target_indices(target)
109
+ probs_rep, routing_map_rep = topk_routing_with_score_function(
110
+ logits=logits, topk=2, use_pre_softmax=False, score_function="softmax", router_replay=rr,
111
+ )
112
+
113
+ RouterReplay.clear_global_router_replay_action()
114
+ RouterReplay.clear_global_indices()
115
+ RouterReplay.clear_global_router_replay_instances()
116
+ ```
117
+
118
+ ## 6. Minimal Demo
119
+
120
+ Here is a minimal code example showing how to use RouterReplay for recording and replaying:
121
+
122
+ ```python
123
+ import torch
124
+ import torch.distributed as dist
125
+ from megatron.core.transformer.transformer_config import TransformerConfig
126
+ from megatron.core.transformer.moe.router import TopKRouter
127
+ from megatron.core.transformer.moe.router_replay import RouterReplay, RouterReplayAction
128
+
129
+
130
+ # Initialize distributed training
131
+ if not dist.is_initialized():
132
+ dist.init_process_group(backend="nccl")
133
+
134
+ # Create a transformer config with RouterReplay enabled
135
+ config = TransformerConfig(
136
+ num_experts=8,
137
+ expert_model_parallel_size=1,
138
+ num_top_k=2,
139
+ moe_enable_routing_replay=True
140
+ )
141
+
142
+ # Create a TopKRouter instance
143
+ router = TopKRouter(config)
144
+
145
+ # Generate sample input (batch_size, sequence_length, hidden_size)
146
+ logits = torch.randn(16, 32, 8).to(torch.cuda.current_device())
147
+
148
+ # -----------------
149
+ # 1. Recording Mode
150
+ # -----------------
151
+ print("=== Recording Mode ===")
152
+ # Set global router replay action to RECORD
153
+ RouterReplay.set_global_router_replay_action(RouterReplayAction.RECORD)
154
+
155
+ # Perform routing
156
+ routing_output = router.forward(logits)
157
+ print(f"Recorded top-k indices shape: {routing_output.top_k_idx.shape}")
158
+
159
+ # -----------------
160
+ # 2. Forward Replay Mode
161
+ # -----------------
162
+ print("\n=== Forward Replay Mode ===")
163
+ # Save recorded indices to a file
164
+ torch.save(routing_output.top_k_idx, "/tmp/replay.pt")
165
+
166
+ # Load indices from file and set as target for replay
167
+ replay_indices = torch.load("/tmp/replay.pt")
168
+ for router_instance in RouterReplay.global_router_replay_instances:
169
+ router_instance.target_topk_idx = replay_indices
170
+
171
+ # Set global router replay action to REPLAY_FORWARD
172
+ RouterReplay.set_global_router_replay_action(RouterReplayAction.REPLAY_FORWARD)
173
+
174
+ # Perform routing again - this will use the replayed indices
175
+ replay_routing_output = router.forward(logits)
176
+ print(f"Replayed top-k indices shape: {replay_routing_output.top_k_idx.shape}")
177
+ print(f"Are indices the same? {torch.equal(routing_output.top_k_idx, replay_routing_output.top_k_idx)}")
178
+
179
+
180
+ # Clean up
181
+ RouterReplay.clear_global_router_replay_action()
182
+ RouterReplay.clear_global_indices()
183
+ RouterReplay.clear_global_router_replay_instances()
184
+ if dist.is_initialized():
185
+ dist.destroy_process_group()
186
+ ```
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/install.md ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # Installation
11
+
12
+ ## System Requirements
13
+
14
+ ### Hardware
15
+
16
+ - **Recommended**: NVIDIA Turing architecture or later
17
+ - **FP8 Support**: Requires NVIDIA Hopper, Ada, or Blackwell GPUs
18
+
19
+ ### Software
20
+
21
+ - **Python**: >= 3.10 (3.12 recommended)
22
+ - **PyTorch**: >= 2.6.0
23
+ - **CUDA Toolkit**: Latest stable version
24
+
25
+
26
+ ## Prerequisites
27
+
28
+ Install [uv](https://docs.astral.sh/uv/), a fast Python package installer:
29
+
30
+ ```bash
31
+ curl -LsSf https://astral.sh/uv/install.sh | sh
32
+ ```
33
+
34
+
35
+ ## Option A: Pip Install (Recommended)
36
+
37
+ Install the latest stable release from PyPI:
38
+
39
+ ```bash
40
+ uv pip install megatron-core
41
+ ```
42
+
43
+ To include optional training dependencies (Weights & Biases, SentencePiece, HF Transformers):
44
+
45
+ ```bash
46
+ uv pip install "megatron-core[training]"
47
+ ```
48
+
49
+ For all extras including [Transformer Engine](https://github.com/NVIDIA/TransformerEngine):
50
+
51
+ ```bash
52
+ uv pip install --group build
53
+ uv pip install --no-build-isolation "megatron-core[training,dev]"
54
+ ```
55
+
56
+ ```{note}
57
+ `--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.
58
+ ```
59
+
60
+ ```{warning}
61
+ 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`).
62
+ ```
63
+
64
+ ```{tip}
65
+ 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.
66
+ ```
67
+
68
+ To clone the repository for examples:
69
+
70
+ ```bash
71
+ git clone https://github.com/NVIDIA/Megatron-LM.git
72
+ ```
73
+
74
+
75
+ ## Option B: Install from Source
76
+
77
+ For development or to run the latest unreleased code:
78
+
79
+ ```bash
80
+ git clone https://github.com/NVIDIA/Megatron-LM.git
81
+ cd Megatron-LM
82
+ uv pip install -e .
83
+ ```
84
+
85
+ To install with all development dependencies (includes Transformer Engine, requires pre-installed build deps):
86
+
87
+ ```bash
88
+ uv pip install --group build
89
+ uv pip install --no-build-isolation -e ".[training,dev]"
90
+ ```
91
+
92
+ ```{tip}
93
+ If the build runs out of memory, limit parallel compilation jobs with `MAX_JOBS=4 uv pip install --no-build-isolation -e ".[training,dev]"`.
94
+ ```
95
+
96
+
97
+ ## Option C: NGC Container
98
+
99
+ 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).
100
+
101
+ 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.
102
+
103
+ ```bash
104
+ docker run --gpus all -it --rm \
105
+ -v /path/to/dataset:/workspace/dataset \
106
+ -v /path/to/checkpoints:/workspace/checkpoints \
107
+ -e PIP_CONSTRAINT= \
108
+ nvcr.io/nvidia/pytorch:26.01-py3
109
+ ```
110
+
111
+ ```{note}
112
+ 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.
113
+ ```
114
+
115
+ Then install Megatron Core inside the container (torch is already available in the NGC image):
116
+
117
+ ```bash
118
+ pip install uv
119
+ uv pip install --no-build-isolation "megatron-core[training,dev]"
120
+ ```
121
+
122
+
123
+ You are now ready to run training. See [Your First Training Run](quickstart.md) for next steps.
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/overview.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # Overview
11
+
12
+ 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.
13
+
14
+ ## Megatron Core
15
+
16
+ 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.
17
+
18
+ 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.
19
+
20
+ Megatron-Core is compatible with all NVIDIA Tensor Core GPUs and popular LLM architectures such as GPT, BERT, T5, and RETRO.
21
+
22
+
23
+ **Composable library** with GPU-optimized building blocks for custom training frameworks.
24
+
25
+ **Best for:**
26
+
27
+ - **Framework developers** building on top of modular and optimized components
28
+ - **Research teams** needing custom training loops, optimizers, or data pipelines
29
+ - **ML engineers** requiring fault-tolerant training pipelines
30
+
31
+ **What you get:**
32
+
33
+ - Composable transformer building blocks (attention, MLP)
34
+ - Advanced parallelism strategies (TP, PP, DP, EP, CP)
35
+ - Pipeline schedules and distributed optimizers
36
+ - Mixed precision support (FP16, BF16, FP8)
37
+ - GPU-optimized kernels and memory management
38
+ - High-performance dataloaders and dataset utilities
39
+ - Model architectures (LLaMA, Qwen, GPT, Mixtral, Mamba)
40
+
41
+ ## Megatron-LM
42
+
43
+ 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.**
44
+
45
+ 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.
46
+
47
+
48
+ **Reference implementation** that includes Megatron Core plus everything needed to train models.
49
+
50
+ **Best for:**
51
+
52
+ - **Training state-of-the-art foundation models** at scale with cutting-edge performance on latest NVIDIA hardware
53
+ - **Research teams** exploring new architectures and training techniques
54
+ - **Learning distributed training** concepts and best practices
55
+ - **Quick experimentation** with proven model configurations
56
+
57
+ **What you get:**
58
+
59
+ - Pre-configured training scripts for GPT, LLaMA, DeepSeek, Qwen, and more.
60
+ - End-to-end examples from data prep to evaluation
61
+ - Research-focused tools and utilities
62
+
63
+
64
+
65
+ ## Megatron Bridge
66
+
67
+ Megatron Bridge provides out-of-the-box bridges and training recipes for models built on top of base model architectures from Megatron Core.
68
+
69
+ 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.
70
+
71
+ After training or modifying a Megatron model, you can convert it again for deployment or sharing.
72
+
73
+ [Megatron Bridge](https://github.com/NVIDIA-NeMo/Megatron-Bridge)
74
+
75
+
76
+
77
+ ## Ecosystem Libraries
78
+
79
+ **Libraries used by Megatron Core:**
80
+
81
+ - **[Megatron Energon](https://github.com/NVIDIA/Megatron-Energon)** - Multi-modal data loader (text, images, video, audio) with distributed loading and dataset blending
82
+ - **[Transformer Engine](https://github.com/NVIDIA/TransformerEngine)** - Optimized kernels and FP8 mixed precision support
83
+ - **[Resiliency Extension (NVRx)](https://github.com/NVIDIA/nvidia-resiliency-ext)** - Fault tolerant training with failure detection and recovery
84
+
85
+ **Libraries using Megatron Core:**
86
+
87
+ - **[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
88
+ - **[NeMo RL](https://github.com/NVIDIA-NeMo/RL)** - Scalable toolkit for efficient reinforcement learning with RLHF, DPO, and other post-training methods
89
+ - **[NeMo Framework](https://docs.nvidia.com/nemo-framework/user-guide/latest/overview.html)** - Enterprise framework with cloud-native support and end-to-end examples
90
+ - **[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).
91
+
92
+ **Compatible with:** [Hugging Face Accelerate](https://github.com/huggingface/accelerate), [Colossal-AI](https://github.com/hpcaitech/ColossalAI), [DeepSpeed](https://github.com/microsoft/DeepSpeed)
93
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/quickstart.md ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # Your First Training Run
11
+
12
+ This guide walks you through running your first training jobs with Megatron Core. Make sure you have completed [installation](install.md) before proceeding.
13
+
14
+ ## Simple Training Example
15
+
16
+ Run a minimal distributed training loop with mock data on 2 GPUs:
17
+
18
+ ```bash
19
+ torchrun --nproc_per_node=2 examples/run_simple_mcore_train_loop.py
20
+ ```
21
+
22
+ ## LLaMA-3 Training Example
23
+
24
+ Train a LLaMA-3 8B model with FP8 precision on 8 GPUs using mock data:
25
+
26
+ ```bash
27
+ ./examples/llama/train_llama3_8b_h100_fp8.sh
28
+ ```
29
+
30
+ ## Data Preparation
31
+
32
+ To train on your own data, Megatron expects preprocessed binary files (`.bin` and `.idx`).
33
+
34
+ ### 1. Prepare a JSONL File
35
+
36
+ Each line should contain a `text` field:
37
+
38
+ ```json
39
+ {"text": "Your training text here..."}
40
+ {"text": "Another training sample..."}
41
+ ```
42
+
43
+ ### 2. Preprocess the Data
44
+
45
+ ```bash
46
+ python tools/preprocess_data.py \
47
+ --input data.jsonl \
48
+ --output-prefix processed_data \
49
+ --tokenizer-type HuggingFaceTokenizer \
50
+ --tokenizer-model /path/to/tokenizer.model \
51
+ --workers 8 \
52
+ --append-eod
53
+ ```
54
+
55
+ ### Key Arguments
56
+
57
+ - `--input`: Path to input JSON/JSONL file
58
+ - `--output-prefix`: Prefix for output binary files (.bin and .idx)
59
+ - `--tokenizer-type`: Tokenizer type (`HuggingFaceTokenizer`, `GPT2BPETokenizer`, etc.)
60
+ - `--tokenizer-model`: Path to tokenizer model file
61
+ - `--workers`: Number of parallel workers for processing
62
+ - `--append-eod`: Add end-of-document token
63
+
64
+ ## Next Steps
65
+
66
+ - Explore [Parallelism Strategies](../user-guide/parallelism-guide.md) to scale your training
67
+ - Learn about [Data Preparation](../user-guide/data-preparation.md) best practices
68
+ - Check out [Advanced Features](../user-guide/features/index.md) for advanced capabilities
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/get-started/releasenotes.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # Release Notes
11
+
12
+
13
+ ## Roadmaps
14
+
15
+ Stay up-to-date with our development roadmaps and planned features:
16
+
17
+ - **[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
18
+ - **[GPT-OSS Implementation Tracker](https://github.com/NVIDIA/Megatron-LM/issues/1739)** - Advanced features including YaRN RoPE scaling, attention sinks, and custom activation functions
19
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/models/index.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # Supported Models
11
+
12
+ Megatron Core supports a wide range of language and multimodal models with optimized implementations for large-scale training.
13
+
14
+ ## Model Conversion
15
+
16
+ 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.
17
+
18
+ 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.
19
+
20
+ ```{toctree}
21
+ :maxdepth: 1
22
+
23
+ llms
24
+ multimodal
25
+ ../llama_mistral
26
+ ```
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/models/llms.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # Language Models
11
+
12
+ Megatron Core supports the following language model architectures for large-scale training.
13
+
14
+ ## Converting HuggingFace Models
15
+
16
+ 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.
17
+
18
+ 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.
19
+
20
+ ## Decoder-Only Models
21
+
22
+ | Model | Description | Key Features |
23
+ |-------|-------------|--------------|
24
+ | **GPT** | Generative Pre-trained Transformer | Standard autoregressive LM, foundational architecture |
25
+ | **LLaMA** | Meta's LLaMA family | Efficient architecture with RoPE, SwiGLU, RMSNorm |
26
+ | **Mistral** | Mistral AI models | Sliding window attention, efficient inference |
27
+ | **Mixtral** | Sparse Mixture-of-Experts | 8x7B MoE architecture for efficient scaling |
28
+ | **Qwen** | Alibaba's Qwen series | HuggingFace integration, multilingual support |
29
+ | **Mamba** | State Space Model | Subquadratic sequence length scaling, efficient long context |
30
+
31
+ ## Encoder-Only Models
32
+
33
+ | Model | Description | Key Features |
34
+ |-------|-------------|--------------|
35
+ | **BERT** | Bidirectional Encoder Representations | Masked language modeling, classification tasks |
36
+
37
+ ## Encoder-Decoder Models
38
+
39
+ | Model | Description | Key Features |
40
+ |-------|-------------|--------------|
41
+ | **T5** | Text-to-Text Transfer Transformer | Unified text-to-text framework, sequence-to-sequence |
42
+
43
+ ## Example Scripts
44
+
45
+ Training examples for these models can be found in the `examples/` directory:
46
+ - `examples/gpt3/` - GPT-3 training scripts
47
+ - `examples/llama/` - LLaMA training scripts
48
+ - `examples/mixtral/` - Mixtral MoE training
49
+ - `examples/mamba/` - Mamba training scripts
50
+ - `examples/bert/` - BERT training scripts
51
+ - `examples/t5/` - T5 training scripts
52
+
53
+ ## Model Implementation
54
+
55
+ All language models are built using Megatron Core's composable transformer blocks, enabling:
56
+ - Flexible parallelism strategies (TP, PP, DP, EP, CP)
57
+ - Mixed precision training (FP16, BF16, FP8)
58
+ - Distributed checkpointing
59
+ - Efficient memory management
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/models/multimodal.md ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # Multimodal Models
11
+
12
+ Megatron Core supports multimodal models that combine language with vision, audio, and other modalities for comprehensive multimodal understanding.
13
+
14
+ ## MIMO: Multimodal In/Out Framework
15
+
16
+ **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.
17
+
18
+ > **Note**: MIMO is experimental and under active development. The API may change in future releases.
19
+
20
+ **Key Features:**
21
+ - Arbitrary modality combinations (vision, audio, text, etc.)
22
+ - Flexible encoder architecture for different input modalities
23
+ - Unified embedding space across modalities
24
+ - Support for both vision-language and audio-vision-language models
25
+
26
+ See [examples/mimo](https://github.com/NVIDIA/Megatron-LM/tree/main/examples/mimo) for training scripts and examples.
27
+
28
+ ## Vision-Language Models
29
+
30
+ | Model | Description | Vision Encoder | Language Model |
31
+ |-------|-------------|----------------|----------------|
32
+ | **LLaVA** | Visual instruction tuning | CLIP ViT-L/14 | Mistral-7B / LLaMA |
33
+ | **NVLM** | NVIDIA Vision-Language Model | CLIP / Custom ViT | LLaMA-based |
34
+ | **LLaMA 3.1 Nemotron Nano VL** | Efficient multimodal model | Vision Transformer | LLaMA 3.1 8B |
35
+
36
+ ## Vision Encoders
37
+
38
+ | Model | Description | Key Features |
39
+ |-------|-------------|--------------|
40
+ | **CLIP ViT** | OpenAI's CLIP Vision Transformer | Image-text alignment, multiple scales (L/14@336px) |
41
+ | **RADIO** | Resolution-Agnostic Dynamic Image Optimization | Flexible resolution handling, efficient vision encoding |
42
+
43
+ ## Diffusion Models
44
+
45
+ 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:
46
+ - Stable Diffusion variants
47
+ - Text-to-image generation
48
+ - Image-to-image translation
49
+ - ControlNet and other conditioning mechanisms
50
+
51
+ ## Multimodal Features
52
+
53
+ - **Image-Text Alignment**: Pre-training on image-caption pairs
54
+ - **Visual Instruction Tuning**: Fine-tuning on instruction-following datasets
55
+ - **Flexible Vision Encoders**: Support for different ViT architectures and resolutions
56
+ - **Combined Checkpointing**: Unified checkpoints combining vision and language models
57
+ - **Efficient Training**: Full parallelism support (TP, PP, DP) for both vision and language components
58
+
59
+ ## Example Scripts
60
+
61
+ Multimodal training examples can be found in the following directories:
62
+
63
+ **MIMO Framework:**
64
+ - `examples/mimo/` - Multimodal In/Out training with support for vision-language and audio-vision-language models
65
+
66
+ **Specific Multimodal Models:**
67
+ - `examples/multimodal/` - LLaVA-style training with Mistral + CLIP
68
+ - `examples/multimodal/nvlm/` - NVLM training scripts
69
+ - `examples/multimodal/llama_3p1_nemotron_nano_vl_8b_v1/` - Nemotron VL training
70
+ - `examples/multimodal/radio/` - RADIO vision encoder integration
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/custom_fsdp.md ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # Megatron FSDP
11
+
12
+ **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.**
13
+
14
+ ## How to use ?
15
+
16
+ Add these flag to enable MCore custom FSDP.
17
+
18
+ ```bash
19
+ --use-megatron-fsdp
20
+ --data-parallel-sharding-strategy optim_grads_params
21
+ --no-gradient-accumulation-fusion
22
+ --use-distributed-optimizer
23
+ ```
24
+
25
+ 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).
26
+
27
+ ## Key Features
28
+
29
+ - **Sharding Strategy**: Efficiently shards optimizer states, gradients, and parameters to reduce memory consumption.
30
+ - **Communication and Computation Overlap**: Optimized to enable concurrent execution of communication and computation, enhancing overall efficiency.
31
+ - **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.
32
+ - **Tensor Parallelism (TP), Expert Parallelism (EP) and Context Parallelism (CP)**: Compatible with TP, EP and CP configurations, enabling efficient scaling of large language models.
33
+ - **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.
34
+
35
+ ## Configuration Recommendations
36
+
37
+ ### 1. Disable `CUDA_DEVICE_MAX_CONNECTIONS`
38
+
39
+ 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.)
40
+
41
+ ```bash
42
+ unset CUDA_DEVICE_MAX_CONNECTIONS
43
+ ```
44
+
45
+ ### 2. Add `--calculate-per-token-loss`
46
+
47
+ 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.
48
+
49
+ ## Design of Custom FSDP
50
+
51
+ ### 1. Overview
52
+
53
+ 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:
54
+
55
+ - **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.
56
+ - **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.
57
+ - **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.
58
+ - **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.
59
+
60
+ 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.
61
+
62
+ > 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.
63
+
64
+ > 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.
65
+
66
+ ![FSDP workflow](../../images/custom_fsdp/FSDP_workflow.png)
67
+
68
+ *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**.*
69
+
70
+ *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.*
71
+
72
+ At a high level FSDP works as follow:
73
+
74
+ In constructor
75
+ - Shard model parameters and each rank only keeps its own shard
76
+
77
+ In forward path
78
+ - Run all_gather to collect all shards from all ranks to recover the full parameter in this FSDP unit
79
+ - Run forward computation
80
+ - Discard parameter shards it has just collected
81
+
82
+ In backward path
83
+ - Run all_gather to collect all shards from all ranks to recover the full parameter in this FSDP unit
84
+ - Run backward computation
85
+ - Run reduce_scatter to sync gradients
86
+ - Discard parameters.
87
+
88
+ 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.
89
+
90
+ ![FSDP Allreduce](../../images/custom_fsdp/FSDP_Allreduce.png)
91
+
92
+ ### 2. Custom FSDP underlying data structure
93
+
94
+ To implement the FSDP functionality described above, the custom FSDP is designed with the following Python classes and data structure:
95
+
96
+ ![MCore Custom FSDP Class Diagram](../../images/custom_fsdp/MCore_Custom_FSDP_Class_Diagram.png)
97
+
98
+ ### 3. The custom FSDP interface: FullyShardedDataParallel
99
+
100
+ 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:
101
+
102
+ ```python
103
+ # Initialize model and optimizer
104
+ ddp_config.use_megatron_fsdp = True
105
+ ddp_config.data_parallel_sharding_strategy = "optim_grads_params"
106
+ model = GPTModel(transformer_config)
107
+ model = FullyShardedDataParallel(
108
+ transformer_config,
109
+ model,
110
+ ddp_config,
111
+ fsdp_unit_modules = [TransformerLayer, LanguageModelEmbedding],
112
+ )
113
+ optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
114
+ optimizer = DistributedOptimizer(optimizer, [model], [model.param_and_grad_buffer])
115
+
116
+ # Training loop
117
+ def train_step(inputs, labels):
118
+ optimizer.zero_grad()
119
+ for mbs_input, mbs_label in zip(inputs, labels):
120
+ outputs = model(mbs_input)
121
+ loss = loss_fn(outputs, mbs_label)
122
+ loss.backward()
123
+ optimizer.step()
124
+
125
+ # Save and load model and optimizer state dict
126
+ def model_and_optimizer_state_dict():
127
+ state_dict = {
128
+ "model": model.sharded_state_dict(),
129
+ "optimizer": optimizer.sharded_state_dict(),
130
+ }
131
+ return state_dict
132
+
133
+ def load_model_and_optimizer_state_dict(state_dict):
134
+ model.load_state_dict(state_dict["model"])
135
+ optimizer.load_state_dict(state_dict["optimizer"])
136
+ ```
137
+
138
+ **Key Notes:**
139
+ - You can configure which modules should be treated as FSDP units via the `fsdp_unit_modules` argument. This configuration is mandatory.
140
+ - The custom FSDP must be used with a distributed optimizer since it provides distributed checkpointing.
141
+ - 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.
142
+
143
+ #### 3.1 Initializing Models on the Meta Device
144
+
145
+ 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)).
146
+
147
+ ```python
148
+ # Initialize model on meta device
149
+ with torch.device("meta"):
150
+ model = GPTModel(config)
151
+
152
+ model = FullyShardedDataParallel(
153
+ transformer_config,
154
+ model,
155
+ ddp_config,
156
+ fsdp_unit_modules=[TransformerLayer, LanguageModelEmbedding],
157
+ )
158
+ ```
159
+
160
+ **Important Considerations:**
161
+ 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.
162
+ 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.
163
+
164
+ ### 4. Interaction between Custom FSDP and Model Forward/Backward Propagation
165
+
166
+ 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.
167
+
168
+ Module hooks summary:
169
+ - 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.
170
+ - Module post-forward hook(`module.register_forward_hook`): This hook is used to reshard model weights after the forward pass.
171
+ - 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.
172
+ - Module pre-backward hook(`module.register_full_backward_pre_hook`): This hook is used to unshard the model weights before the backward pass.
173
+ - 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.
174
+
175
+ 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.
176
+
177
+ #### 4.1 Optimized for Activation Recompute
178
+
179
+ 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.
180
+
181
+ 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.
182
+
183
+ ### 5. Memory Mechanisms and Features of Custom FSDP
184
+
185
+ 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.
186
+
187
+ 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.
188
+
189
+ 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.
190
+
191
+ 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.
192
+
193
+ ## References
194
+
195
+ - [Getting Started with Fully Sharded Data Parallel (FSDP)](https://pytorch.org/tutorials/intermediate/FSDP_tutorial.html)
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/index.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # Advanced Features
11
+
12
+ Advanced feature guides for key Megatron Core capabilities.
13
+
14
+ ```{toctree}
15
+ :maxdepth: 2
16
+
17
+ fine_grained_activation_offloading
18
+ moe
19
+ context_parallel
20
+ custom_fsdp
21
+ dist_optimizer
22
+ optimizer_cpu_offload
23
+ pipeline_parallel_layout
24
+ tokenizers
25
+ megatron_energon
26
+ megatron_rl
27
+ ```
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/megatron_rl.md ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # Megatron RL
11
+
12
+ Reinforcement learning library for post-training large language models at scale.
13
+
14
+ ## Overview
15
+
16
+ [**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.
17
+
18
+ > **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).
19
+
20
+ ## Key Features
21
+
22
+ - **Decoupled Design** - Clean separation between agent/environment logic and RL implementation
23
+ - **Flexible Inference** - Support for Megatron, OpenAI, and HuggingFace inference backends
24
+ - **Trainer/Evaluator** - Manages rollout generation and coordinates with inference systems
25
+ - **Megatron Integration** - Native integration with Megatron Core inference system
26
+
27
+ ## Architecture
28
+
29
+ ### Components
30
+
31
+ **Agents & Environments**
32
+ - Accept inference handles
33
+ - Return experience rollouts with rewards
34
+ - Implement custom RL logic
35
+
36
+ **Trainer/Evaluator**
37
+ - Controls rollout generation
38
+ - Coordinates with inference systems
39
+ - Manages training loops
40
+
41
+ **Inference Interface**
42
+ - Provides `.generate(prompt, **generation_args)` endpoint
43
+ - Supports multiple backends (Megatron, OpenAI, HuggingFace)
44
+
45
+ ## Use Cases
46
+
47
+ - RLHF (Reinforcement Learning from Human Feedback)
48
+ - Custom reward-based fine-tuning
49
+ - Policy optimization for specific tasks
50
+ - Research on RL post-training techniques
51
+
52
+ ## Resources
53
+
54
+ - **[Megatron RL GitHub](https://github.com/NVIDIA/Megatron-LM/tree/dev/megatron/rl)** - Source code and documentation
55
+ - **[Megatron Core Inference](../../api-guide/core/transformer.md)** - Native inference integration
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/moe.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # Mixture of Experts
11
+
12
+ ```{toctree}
13
+ :maxdepth: 1
14
+ :caption: MoE Features
15
+
16
+ multi_token_prediction
17
+ multi_latent_attention
18
+ ../../api-guide/router_replay
19
+ ```
20
+
21
+ ```{include} ../../../megatron/core/transformer/moe/README.md
22
+ ```
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/multi_latent_attention.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # Multi-Latent Attention
11
+
12
+ ## Multi-Latent Attention overview
13
+
14
+ 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.
15
+
16
+ ## Enabling Multi-Latent Attention
17
+
18
+ To enable MLA in Megatron-LM, set the following flags in command line:
19
+ - `--multi-latent-attention` to enable MLA in MLP.
20
+ - Set `MLATransformerConfig` to configure MLA.
21
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/docs/user-guide/features/pipeline_parallel_layout.md ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.
3
+ NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ and proprietary rights in and to this software, related documentation
5
+ and any modifications thereto. Any use, reproduction, disclosure or
6
+ distribution of this software and related documentation without an express
7
+ license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+ -->
9
+
10
+ # Custom Pipeline Model Parallel Layout
11
+
12
+ *This is an experimental feature and may be changed.*
13
+
14
+ `--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:
15
+
16
+ ```bash
17
+ --pipeline-model-parallel-size 16
18
+ --pipeline-model-parallel-layout "Et*3|(tt|)*29,m|L"
19
+ ```
20
+
21
+ | PP \ VPP rank | 0 | 1 |
22
+ |---------------|-------------------------|---------------|
23
+ | 0 | embedding + 3 × decoder | 2 × decoder |
24
+ | 1~13 | 2 × decoder | 2 × decoder |
25
+ | 14 | 2 × decoder | mtp |
26
+ | 15 | 2 × decoder | loss |
27
+
28
+ In the layout string, stages are split by '|'. Replicated stages or layers can be described with multiplication. Commas can be used cosmetically. Symbol choices:
29
+
30
+ * `E` = embedding layer
31
+ * `t` = transformer decoder layer
32
+ * `m` = MTP layer
33
+ * `L` = loss calculation layer
34
+
35
+ Note that it is legal to have empty stages, e.g., `E||t|L` (the second stage is empty).
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/README.md ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SGEAT: Detoxify Larger-scale Language Models
2
+
3
+ This is the official code base for our NeurIPS 2022 paper:
4
+
5
+ [Exploring the Limits of Domain-Adaptive Training for Detoxifying Large-Scale Language Models](https://arxiv.org/abs/2202.04173)
6
+
7
+ Boxin Wang, Wei Ping, Chaowei Xiao, Peng Xu, Mostofa Patwary, Mohammad Shoeybi, Bo Li, Anima Anandkumar, Bryan Catanzaro
8
+
9
+
10
+ ## Citation
11
+
12
+ ```
13
+ @article{WangExp2022,
14
+ title={Exploring the Limits of Domain-Adaptive Training for Detoxifying Large-Scale Language Models},
15
+ 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},
16
+ journal={NeurIPS},
17
+ year={2022}
18
+ }
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ ### Prepare your environment
24
+
25
+ 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`.
26
+
27
+ To run Perspective API, you need to install `google-api-python-client`
28
+ ```bash
29
+ pip install --upgrade google-api-python-client
30
+ ```
31
+
32
+ ### Self Generation
33
+
34
+ #### SGEAT (Standard)
35
+ To perform unconditional generation for a Megatron LM, we provide an example script for 1.3B LM.
36
+
37
+ ```bash
38
+ # [num of samples] [model checkpoint] [random seed]
39
+ bash examples/detxoify_lm/self_generation/selfgenerate-1.3b-unconditional.sh 1000 checkpoints/gpt3/gpt3-1.3b/ 2333
40
+ ```
41
+ This will generate a jsonl file of 1000 generated text (as a toy example) at `selfgeneration/unconditional_generation_gpt3-1.3b/2333.out`.
42
+
43
+ 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`.
44
+
45
+ ### Annotation
46
+
47
+ 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`.
48
+
49
+ ```bash
50
+ python examples/detxoify_lm/perspective_api_annotate.py --data-path [input-data-path] --out-path [output-data-path] --workers 70
51
+ ```
52
+
53
+ For example,
54
+
55
+ ```bash
56
+ 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
57
+ ```
58
+
59
+ ### Filtering
60
+
61
+ We then filter the self annotated generated corpus to get the most nontoxic 50% of the corus.
62
+
63
+ For example,
64
+ ```bash
65
+ 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
66
+ ```
67
+
68
+ 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`.
69
+
70
+
71
+ ### Preprocess
72
+
73
+ We then preprocess the dataset so that Megatron LM can use the dumped dataset to fine-tune.
74
+
75
+ ```
76
+ 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
77
+ ```
78
+
79
+ This will generate two files as follows
80
+ ```bash
81
+ selfgeneration/unconditional_generation_gpt3-1.3b/2333.annotated.nontoxic_text_document.idx
82
+ selfgeneration/unconditional_generation_gpt3-1.3b/2333.annotated.nontoxic_text_document.bin
83
+ ```
84
+ which will be used in the following domain-adative training step.
85
+
86
+ ### Fine-tuning
87
+
88
+ We then use the preprocess dataset as input to fine-tune our Megatron-LM.
89
+ ```bash
90
+ # [fine-tuning dataset] [output-dir] [lr] [bs] [train-iters] [load checkpoint]
91
+ 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
92
+ ```
93
+
94
+ 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`)
95
+
96
+ ### Evaluation
97
+
98
+ We then use the fine-tuned checkpoint to perform conditional generation given RealToxicityPrompts:
99
+
100
+ ```bash
101
+ # [input-prompts] [model-checkpoint]
102
+ bash examples/detxoify_lm/generate-1.3b.sh augmented_prompts.jsonl $SHARE_DATA/gpt3-1.3b-toy-example-lr-2e-5-bs-512
103
+ ```
104
+ 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).
105
+
106
+ 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,
107
+
108
+ We then use Perspective API to evaluate the Expected Maximum Toxicity and Toxicity Probability.
109
+
110
+ ```bash
111
+ 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
112
+ ```
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/annotations/filter-selfgeneration.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import time
3
+ from typing import Dict, Optional, List
4
+
5
+ import joblib
6
+ from googleapiclient import discovery
7
+ from googleapiclient.errors import HttpError
8
+
9
+ import argparse
10
+
11
+ from tqdm import tqdm
12
+
13
+ parser = argparse.ArgumentParser(description='Process some integers.')
14
+ parser.add_argument('--data-path', type=str, default='',
15
+ help='data path to load the jsonl')
16
+ parser.add_argument('--out-path', type=str, default='',
17
+ help='data path to load the jsonl')
18
+ parser.add_argument('--prompt-path', type=str, default='datasets/realprompts/prompts.jsonl',
19
+ help='data path to load the prompt jsonl')
20
+ parser.add_argument('--workers', type=int, default=10,
21
+ help='Number of worker processes to launch')
22
+
23
+
24
+ def get_corpus_scores(lines):
25
+ scores = []
26
+ corpus = []
27
+
28
+ for line in tqdm(lines):
29
+ data = json.loads(line)
30
+ score = data['score']
31
+ if score is not None:
32
+ scores.append(score['toxicity'])
33
+ corpus.append(data)
34
+ return scores, corpus
35
+
36
+
37
+ def main():
38
+ args = parser.parse_args()
39
+
40
+ with open(args.data_path) as f:
41
+ lines = f.readlines()
42
+
43
+ print(f"total line number: {len(lines)}")
44
+
45
+ scores, corpus = get_corpus_scores(lines)
46
+ import numpy as np
47
+ scores = np.array(scores)
48
+ indices = np.argsort(scores)
49
+
50
+ print(f"total valid samples: {len(scores)}")
51
+
52
+ print(f"Avg toxicity (all): {np.mean(scores)} +- {np.std(scores)}")
53
+ print(f"Avg toxicity (toxic): {np.mean(scores[scores > 0.5])} +- {np.std(scores[scores > 0.5])}")
54
+ print(f"Toxic Percentage {sum(scores > 0.5) / len(scores)}")
55
+ print(f"Avg toxicity (nontoxic): {np.mean(scores[scores <= 0.5])} +- {np.std(scores[scores <= 0.5])}")
56
+ print(f"Nontoxic Percentage {sum(scores <= 0.5) / len(scores)}")
57
+
58
+ samples_left = len(lines) // 2
59
+ print(f"After filtering: {samples_left} of samples are left")
60
+ nontoxic_indices = indices[:samples_left]
61
+ print(f"Avg toxicity (filtered): {np.mean(scores[nontoxic_indices])} +- {np.std(scores[nontoxic_indices])}")
62
+ print(f"Toxicity Range (filtered): {np.min(scores[nontoxic_indices])} ~ {np.max(scores[nontoxic_indices])}")
63
+ nontoxic_data = [corpus[ind] for ind in nontoxic_indices]
64
+ print(f"Total samples after filtering: {len(nontoxic_data)}")
65
+ print(f"Examples: {nontoxic_data[:3]}")
66
+
67
+ from sklearn.utils import shuffle
68
+ nontoxic_data = shuffle(nontoxic_data)
69
+
70
+ with open(args.out_path, 'w') as f:
71
+ for x in nontoxic_data:
72
+ f.write(json.dumps(x) + '\n')
73
+
74
+
75
+ main()
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/annotations/perspective_api_annotate.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import time
3
+ from typing import Dict, Optional, List
4
+
5
+ import joblib
6
+ from googleapiclient import discovery
7
+ from googleapiclient.errors import HttpError
8
+
9
+ import argparse
10
+
11
+ from tqdm import tqdm
12
+
13
+ parser = argparse.ArgumentParser(description='Process some integers.')
14
+ parser.add_argument('--data-path', type=str, default='',
15
+ help='data path to load the jsonl')
16
+ parser.add_argument('--out-path', type=str, default='',
17
+ help='data path to load the jsonl')
18
+ parser.add_argument('--total', type=int, default=-1,
19
+ help='Total number of data')
20
+ parser.add_argument('--workers', type=int, default=1,
21
+ help='Number of worker processes to launch')
22
+
23
+
24
+ class PerspectiveApiScorer:
25
+ """
26
+ This class provides a method for accessing Perspective API using the Google API Client to obtain attribute scores for generated texts.
27
+ """
28
+
29
+ DEFAULT_ATTRIBUTES = ['toxicity', 'severe_toxicity', 'sexually_explicit', 'threat', 'profanity', 'identity_attack']
30
+
31
+ def __init__(self):
32
+ """
33
+ :param api_key: the API key to use. For details, see https://support.perspectiveapi.com/s/docs-get-started
34
+ """
35
+ api_key = ''
36
+ self._service = discovery.build(
37
+ "commentanalyzer",
38
+ "v1alpha1",
39
+ developerKey=api_key,
40
+ discoveryServiceUrl="https://commentanalyzer.googleapis.com/$discovery/rest?version=v1alpha1",
41
+ static_discovery=False,
42
+ )
43
+
44
+ def get_scores(self, input_text: str, requested_attributes: Optional[List[str]] = None) -> Dict[str, float]:
45
+ """
46
+ Get attribute scores for a given text via Perspective API.
47
+ :param input_text: the input text
48
+ :param requested_attributes: the attributes for which to compute scores
49
+ :return: a mapping from attribute names to scores
50
+ """
51
+ requested_attributes = requested_attributes if requested_attributes else PerspectiveApiScorer.DEFAULT_ATTRIBUTES
52
+
53
+ analyze_request = {
54
+ 'comment': {'text': input_text},
55
+ 'requestedAttributes': {attribute.upper(): {} for attribute in requested_attributes},
56
+ 'spanAnnotations': False,
57
+ 'languages': ['en'],
58
+ }
59
+
60
+ response = None
61
+ while not response:
62
+ try:
63
+ response = self._service.comments().analyze(body=analyze_request).execute()
64
+ except Exception as e:
65
+ print(f'Perspective API threw an error: {e}\n Retrying in 5 seconds...')
66
+ print(input_text)
67
+ time.sleep(1)
68
+
69
+ return {attribute: response['attributeScores'][attribute.upper()]['summaryScore']['value'] for attribute in
70
+ requested_attributes}
71
+
72
+
73
+ def test():
74
+ scorer = PerspectiveApiScorer()
75
+ for i in range(1):
76
+ print(scorer.get_scores("toxic behaviors and nasty negro"))
77
+
78
+
79
+ def split_lines(lines, split):
80
+ tot = len(lines)
81
+ each = tot // split
82
+ return [lines[i:i+each] for i in range(0, tot, each)]
83
+
84
+ from joblib import Parallel, delayed
85
+
86
+ scorer = PerspectiveApiScorer()
87
+
88
+ def get_score(line):
89
+ data = json.loads(line)
90
+ text = data['text']
91
+ text = text.replace("<|endoftext|>", "")
92
+ data['text'] = text
93
+ if not text.strip():
94
+ data['score'] = None
95
+ return json.dumps(data)
96
+
97
+ encoded_text = text.encode('utf8')
98
+ encoded_text = encoded_text[:20480]
99
+ try:
100
+ decoded_text = encoded_text.decode('utf8')
101
+ except UnicodeDecodeError:
102
+ try:
103
+ decoded_text = encoded_text[:20479].decode('utf8')
104
+ except UnicodeDecodeError:
105
+ try:
106
+ decoded_text = encoded_text[:20478].decode('utf8')
107
+ except UnicodeDecodeError:
108
+ try:
109
+ decoded_text = encoded_text[:20476].decode('utf8')
110
+ except Exception:
111
+ print("Error occurred")
112
+ data['score'] = None
113
+ return json.dumps(data)
114
+ data['score'] = scorer.get_scores(decoded_text)
115
+ return json.dumps(data)
116
+
117
+
118
+ def get_scores(lines):
119
+ scorer = PerspectiveApiScorer()
120
+ all_data = []
121
+ for i, line in enumerate(tqdm(lines)):
122
+ data = json.loads(line)
123
+ text = data['text']
124
+ if not text.strip():
125
+ data['score'] = None
126
+ all_data.append(json.dumps(data))
127
+ continue
128
+ encoded_text = text.encode('utf8')
129
+ encoded_text = encoded_text[:20480]
130
+ try:
131
+ decoded_text = encoded_text.decode('utf8')
132
+ except UnicodeDecodeError:
133
+ try:
134
+ decoded_text = encoded_text[:20479].decode('utf8')
135
+ except UnicodeDecodeError:
136
+ try:
137
+ decoded_text = encoded_text[:20478].decode('utf8')
138
+ except UnicodeDecodeError:
139
+ try:
140
+ decoded_text = encoded_text[:20476].decode('utf8')
141
+ except Exception:
142
+ print("Error occurred")
143
+ data['score'] = None
144
+ all_data.append(json.dumps(data))
145
+ continue
146
+ data['score'] = scorer.get_scores(decoded_text)
147
+ all_data.append(json.dumps(data))
148
+ return all_data
149
+
150
+ def get_annotated_datasets(lines, threads=10):
151
+ sub_lines = lines
152
+ splitted_lines = split_lines(sub_lines, threads)
153
+ print(len(sub_lines))
154
+ final = Parallel(n_jobs=threads)(delayed(get_score)(l) for l in splitted_lines)
155
+ import itertools
156
+ finals = list(itertools.chain.from_iterable(final))
157
+ return finals
158
+
159
+
160
+ def main():
161
+ args = parser.parse_args()
162
+
163
+ path = args.data_path
164
+ out = args.out_path if args.out_path else path + '-annotated.jsonl'
165
+ print(out)
166
+
167
+ fin = open(path, 'r', encoding='utf-8')
168
+ import multiprocessing
169
+ pool = multiprocessing.Pool(args.workers)
170
+ annotated = pool.imap(get_score, fin, 25)
171
+ with open(out, "w") as f:
172
+ if args.total > 0:
173
+ for x in tqdm(annotated, total=args.total):
174
+ f.write(x + '\n')
175
+ else:
176
+ for x in tqdm(annotated):
177
+ f.write(x + '\n')
178
+
179
+
180
+ if __name__ == '__main__':
181
+ main()
182
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/annotations/preprocess.sh ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ VOCAB_FILE=pt2-vocab.json
2
+ MERGE_FILE=gpt2-merges.txt
3
+
4
+ python3 tools/preprocess_data.py \
5
+ --input $1 \
6
+ --output-prefix $2 \
7
+ --vocab-file $VOCAB_FILE \
8
+ --merge-file $MERGE_FILE \
9
+ --tokenizer-type GPT2BPETokenizer \
10
+ --append-eod --workers 20 --chunk-size 25
11
+
12
+
13
+
14
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/finetune_gpt.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
3
+
4
+
5
+ """Fine-tune GPT"""
6
+
7
+ import torch
8
+ from functools import partial
9
+ import os
10
+ import sys
11
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),
12
+ os.path.pardir, os.path.pardir)))
13
+ from megatron.training import get_args
14
+ from megatron.training import get_timers
15
+ from megatron.training import get_tokenizer
16
+ from megatron.training import print_rank_0
17
+ from megatron.core import mpu
18
+ from megatron.core.datasets.blended_megatron_dataset_builder import BlendedMegatronDatasetBuilder
19
+ from megatron.core.datasets.blended_megatron_dataset_config import GPTDatasetConfig
20
+ from megatron.core.datasets.gpt_dataset import GPTDataset
21
+ from megatron.core.datasets.utils import get_blend_from_list
22
+ from megatron.legacy.model import GPTModel
23
+ from megatron.core.enums import ModelType
24
+ from megatron.training import pretrain
25
+ from megatron.training.utils import get_ltor_masks_and_position_ids
26
+ from megatron.training.utils import average_losses_across_data_parallel_group
27
+
28
+ def model_provider(pre_process=True, post_process=True):
29
+ """Build the model."""
30
+
31
+ print_rank_0('building GPT model ...')
32
+ model = GPTModel(
33
+ num_tokentypes=0,
34
+ parallel_output=True,
35
+ pre_process=pre_process,
36
+ post_process=post_process
37
+ )
38
+ return model
39
+
40
+
41
+ def get_batch(data_iterator):
42
+ """Generate a batch"""
43
+ args = get_args()
44
+ tokenizer = get_tokenizer()
45
+
46
+ # Items and their type.
47
+ keys = ['text']
48
+ datatype = torch.int64
49
+
50
+ # Broadcast data.
51
+ if data_iterator is not None:
52
+ data = next(data_iterator)
53
+ else:
54
+ data = None
55
+ data_b = mpu.broadcast_data(keys, data, datatype)
56
+
57
+ # Unpack.
58
+ tokens_ = data_b['text'].long()
59
+ labels = tokens_[:, 1:].contiguous()
60
+ tokens = tokens_[:, :-1].contiguous()
61
+
62
+ # Get the masks and postition ids.
63
+ attention_mask, loss_mask, position_ids = get_ltor_masks_and_position_ids(
64
+ tokens,
65
+ tokenizer.eod,
66
+ args.reset_position_ids,
67
+ args.reset_attention_mask,
68
+ args.eod_mask_loss)
69
+
70
+ return tokens, labels, loss_mask, attention_mask, position_ids
71
+
72
+ def loss_func(loss_mask, output_tensor):
73
+ losses = output_tensor.float()
74
+ loss_mask = loss_mask.view(-1).float()
75
+ loss = torch.sum(losses.view(-1) * loss_mask) / loss_mask.sum()
76
+
77
+ # Reduce loss for logging.
78
+ averaged_loss = average_losses_across_data_parallel_group([loss])
79
+
80
+ return loss, {'lm loss': averaged_loss[0]}
81
+
82
+
83
+ def forward_step(data_iterator, model):
84
+ """Forward step."""
85
+ args = get_args()
86
+ timers = get_timers()
87
+
88
+ # Get the batch.
89
+ timers('batch-generator').start()
90
+ tokens, labels, loss_mask, attention_mask, position_ids = get_batch(
91
+ data_iterator)
92
+ timers('batch-generator').stop()
93
+
94
+ output_tensor = model(tokens, position_ids, attention_mask,
95
+ labels=labels)
96
+
97
+ return output_tensor, partial(loss_func, loss_mask)
98
+
99
+
100
+ def train_valid_test_datasets_provider(train_val_test_num_samples):
101
+ """Build train, valid, and test datasets."""
102
+ args = get_args()
103
+
104
+ print_rank_0('> building train, validation, and test datasets '
105
+ 'for GPT ...')
106
+ train_ds, _, test_ds = BlendedMegatronDatasetBuilder(
107
+ GPTDataset,
108
+ train_val_test_num_samples,
109
+ lambda: True,
110
+ GPTDatasetConfig(
111
+ blend=get_blend_from_list(args.data_path),
112
+ split=args.split,
113
+ random_seed=args.seed,
114
+ sequence_length=args.seq_length,
115
+ path_to_cache=args.data_cache_path,
116
+ return_document_ids=False,
117
+ mid_level_dataset_surplus=args.mid_level_dataset_surplus,
118
+ )
119
+ ).build()
120
+ print_rank_0("> finished creating finetuning GPT datasets ...")
121
+
122
+ _, valid_ds, _ = BlendedMegatronDatasetBuilder(
123
+ GPTDataset,
124
+ train_val_test_num_samples,
125
+ lambda: True,
126
+ GPTDatasetConfig(
127
+ blend=get_blend_from_list(args.data_path2),
128
+ split="98,2,0",
129
+ random_seed=1234,
130
+ sequence_length=2048,
131
+ path_to_cache=args.data_cache_path,
132
+ return_document_ids=False,
133
+ mid_level_dataset_surplus=args.mid_level_dataset_surplus,
134
+ )
135
+ ).build()
136
+ print_rank_0("> finished creating pretrained GPT datasets ...")
137
+
138
+ return train_ds, valid_ds, test_ds
139
+
140
+
141
+ def add_validation_args(parser):
142
+ """Text generation arguments."""
143
+ group = parser.add_argument_group(title='validation set')
144
+ group.add_argument('--data-path2', nargs='*', default=None,
145
+ help='Path to the validation dataset. Accepted format:'
146
+ '1) a single data path, 2) multiple datasets in the'
147
+ 'form: dataset1-weight dataset1-path dataset2-weight '
148
+ 'dataset2-path ...')
149
+ group.add_argument('--eval-ppl', action='store_true', default=False)
150
+ group.add_argument('--stored_params', type=dict, default=dict())
151
+ return parser
152
+
153
+
154
+ if __name__ == "__main__":
155
+
156
+ pretrain(train_valid_test_datasets_provider, model_provider,
157
+ ModelType.encoder_or_decoder,
158
+ forward_step, args_defaults={'tokenizer_type': 'GPT2BPETokenizer'},
159
+ extra_args_provider=add_validation_args,)
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/finetune_gpt_distributed-1.3b.sh ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #! /bin/bash
2
+
3
+ # Change for multinode config
4
+ GPUS_PER_NODE=16
5
+ MASTER_ADDR=localhost
6
+ MASTER_PORT=$(($RANDOM + 1024))
7
+ NNODES=1
8
+ NODE_RANK=0
9
+ WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES))
10
+
11
+ # input
12
+ DATA_PATH=$1
13
+ SHARE_DATA=$PWD # current work dir
14
+ FINETUNED_PATH="$SHARE_DATA/$2"
15
+ lr=$3
16
+ bs=$4
17
+ iter=$5
18
+ CHECKPOINT_PATH=$6
19
+
20
+ # vocab
21
+ VOCAB_FILE=gpt2-vocab.json # Your gpt-2 vocab
22
+ MERGE_FILE=gpt2-merges.txt # Your gpt-2 merge file
23
+
24
+ # tensorboard
25
+ TENSORBOARD_DIR="$SHARE_DATA/tensorboard/$2"
26
+ mkdir -p ${TENSORBOARD_DIR}
27
+
28
+ DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT"
29
+
30
+ python -m torch.distributed.run $DISTRIBUTED_ARGS \
31
+ examples/detxoify_lm/finetune_gpt.py \
32
+ --num-layers 24 \
33
+ --hidden-size 2048 \
34
+ --num-attention-heads 32 \
35
+ --micro-batch-size 4 \
36
+ --global-batch-size $bs \
37
+ --seq-length 2048 \
38
+ --max-position-embeddings 2048 \
39
+ --train-iters $iter \
40
+ --save $FINETUNED_PATH \
41
+ --load $CHECKPOINT_PATH \
42
+ --data-path $DATA_PATH \
43
+ --data-path2 ${DATA_BLEND} \
44
+ --vocab-file $VOCAB_FILE \
45
+ --merge-file $MERGE_FILE \
46
+ --split 100,0,0 \
47
+ --distributed-backend nccl \
48
+ --lr-decay-style constant \
49
+ --lr $lr \
50
+ --clip-grad 1.0 \
51
+ --weight-decay 0.1 \
52
+ --adam-beta1 0.9 \
53
+ --adam-beta2 0.95 \
54
+ --checkpoint-activations \
55
+ --log-interval 1 \
56
+ --save-interval 78 \
57
+ --eval-interval 78 \
58
+ --eval-iters 50 \
59
+ --fp16 \
60
+ --DDP-impl local \
61
+ --finetune --no-load-optim \
62
+ --log-validation-ppl-to-tensorboard \
63
+ --tensorboard-dir ${TENSORBOARD_DIR}
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/generate-1.3b.sh ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ CHECKPOINT_PATH=$2 # Your model ckpt
3
+ VOCAB_FILE=gpt2-vocab.json
4
+ MERGE_FILE=gpt2-merges.txt
5
+
6
+ GPUS_PER_NODE=1
7
+ # Change for multinode config
8
+ MASTER_ADDR=localhost
9
+ MASTER_PORT=$(($RANDOM + 1024))
10
+ NNODES=1
11
+ NODE_RANK=0
12
+ WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES))
13
+ NUM_SAMPLES=$(wc -l < $1)
14
+ PREFIX=$(basename $2)
15
+ SEED=$(($RANDOM))
16
+ OUTPUT=$1_output_"$PREFIX"_seed_"$SEED".jsonl
17
+
18
+ DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT"
19
+
20
+ python -m torch.distributed.run $DISTRIBUTED_ARGS examples/detxoify_lm/generate_samples_gpt.py \
21
+ --tensor-model-parallel-size 1 \
22
+ --num-layers 24 \
23
+ --hidden-size 2048 \
24
+ --load $CHECKPOINT_PATH \
25
+ --num-attention-heads 32 \
26
+ --max-position-embeddings 2048 \
27
+ --tokenizer-type GPT2BPETokenizer \
28
+ --fp16 \
29
+ --micro-batch-size 400 \
30
+ --seq-length 2048 \
31
+ --out-seq-length 20 \
32
+ --temperature 1.0 \
33
+ --vocab-file $VOCAB_FILE \
34
+ --merge-file $MERGE_FILE \
35
+ --sample-input-file $1 \
36
+ --sample-output-file $OUTPUT \
37
+ --num-samples $NUM_SAMPLES \
38
+ --max-tokens-to-oom 1200000 \
39
+ --top_p 0.9 \
40
+ --seed $SEED
41
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/generate_samples_gpt.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
3
+
4
+
5
+ """Sample Generate GPT"""
6
+ import json
7
+ import os
8
+ import sys
9
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),
10
+ os.path.pardir, os.path.pardir)))
11
+ import torch
12
+ from megatron.training import get_args
13
+ from megatron.training import get_tokenizer
14
+ from megatron.training import print_rank_0
15
+ from megatron.training.checkpointing import load_checkpoint
16
+ from megatron.core import mpu
17
+ from megatron.training.initialize import initialize_megatron
18
+ from megatron.legacy.model import GPTModel
19
+ from megatron.training import get_model
20
+ from megatron.inference.text_generation import generate_and_post_process
21
+ from megatron.training.arguments import core_transformer_config_from_args
22
+ from megatron.core.models.gpt import GPTModel
23
+ from typing import Union
24
+ import megatron.legacy.model
25
+ from megatron.core.transformer.spec_utils import import_module
26
+ from megatron.training.arguments import core_transformer_config_from_args
27
+ from megatron.core.models.gpt.gpt_layer_specs import get_gpt_layer_with_transformer_engine_spec, get_gpt_layer_local_spec
28
+
29
+ def model_provider(pre_process=True, post_process=True) -> Union[GPTModel, megatron.legacy.model.GPTModel]:
30
+ """Builds the model.
31
+
32
+ If you set the use_legacy_models to True, it will return the legacy GPT model and if not the core GPT model.
33
+
34
+ Args:
35
+ pre_process (bool, optional): Set to true if you need to compute embedings. Defaults to True.
36
+ post_process (bool, optional): Set to true if you need to want to compute output logits/loss. Defaults to True.
37
+
38
+
39
+ Returns:
40
+ Union[GPTModel, megatron.legacy.model.GPTModel]: The returned model
41
+ """
42
+ args = get_args()
43
+
44
+ print_rank_0('building GPT model ...')
45
+ config = core_transformer_config_from_args(args)
46
+
47
+ if args.use_legacy_models:
48
+ model = megatron.legacy.model.GPTModel(
49
+ config,
50
+ num_tokentypes=0,
51
+ parallel_output=False,
52
+ pre_process=pre_process,
53
+ post_process=post_process
54
+ )
55
+ else:
56
+ if args.spec is None:
57
+ if args.transformer_impl == 'local':
58
+ transformer_layer_spec = get_gpt_layer_local_spec(
59
+ num_experts=args.num_experts,
60
+ moe_grouped_gemm=args.moe_grouped_gemm
61
+ )
62
+ elif args.transformer_impl == 'transformer_engine':
63
+ transformer_layer_spec = get_gpt_layer_with_transformer_engine_spec(
64
+ num_experts=args.num_experts,
65
+ moe_grouped_gemm=args.moe_grouped_gemm
66
+ )
67
+ else:
68
+ raise ValueError(f"Invalid transformer_impl {args.transformer_impl}")
69
+ elif args.spec[0] == 'local':
70
+ transformer_layer_spec = get_gpt_layer_local_spec(
71
+ num_experts=args.num_experts,
72
+ moe_grouped_gemm=args.moe_grouped_gemm
73
+ )
74
+ else:
75
+ transformer_layer_spec = import_module(args.spec)
76
+
77
+ model = GPTModel(
78
+ config=config,
79
+ transformer_layer_spec=transformer_layer_spec,
80
+ vocab_size=args.padded_vocab_size,
81
+ max_sequence_length=args.max_position_embeddings,
82
+ pre_process=pre_process,
83
+ post_process=post_process,
84
+ fp16_lm_cross_entropy=args.fp16_lm_cross_entropy,
85
+ parallel_output=False,
86
+ share_embeddings_and_output_weights=not args.untie_embeddings_and_output_weights,
87
+ position_embedding_type=args.position_embedding_type,
88
+ rotary_percent=args.rotary_percent
89
+ )
90
+
91
+ return model
92
+
93
+ def add_text_generate_args(parser):
94
+ """Text generation arguments."""
95
+ group = parser.add_argument_group(title='text generation')
96
+
97
+ group.add_argument("--temperature", type=float, default=1.0,
98
+ help='Sampling temperature.')
99
+ group.add_argument("--greedy", action='store_true', default=False,
100
+ help='Use greedy sampling.')
101
+ group.add_argument("--top_p", type=float, default=0.0,
102
+ help='Top p sampling.')
103
+ group.add_argument("--top_k", type=int, default=0,
104
+ help='Top k sampling.')
105
+ group.add_argument("--out-seq-length", type=int, default=1024,
106
+ help='Size of the output generated text.')
107
+ group.add_argument("--sample-input-file", type=str, default=None,
108
+ help='Get input from file instead of interactive mode, '
109
+ 'each line is an input.')
110
+ group.add_argument("--sample-output-file", type=str, default=None,
111
+ help='Output file got from --sample-input-file')
112
+ group.add_argument("--num-samples", type=int, default=0,
113
+ help='Number of samples to generate unconditionally, '
114
+ 'defaults to 0 and interactive conditional sampling')
115
+ group.add_argument("--genfile", type=str,
116
+ help='Output file when generating unconditionally')
117
+ return parser
118
+
119
+ def generate_samples_unconditional(model):
120
+ args = get_args()
121
+
122
+ if torch.distributed.get_rank() == 0:
123
+ cnt = 0
124
+ num_samples = args.num_samples
125
+ from tqdm import tqdm
126
+ pbar = tqdm(total=num_samples)
127
+
128
+ while True:
129
+ if torch.distributed.get_rank() == 0:
130
+ sentences = [''] * args.global_batch_size
131
+ print("global batch size", args.global_batch_size)
132
+ max_len = args.out_seq_length
133
+ resp_sentences, resp_sentences_seg, output_logits, \
134
+ tokens = generate_and_post_process(model, prompts=sentences,
135
+ tokens_to_generate=max_len,
136
+ return_output_log_probs=False,
137
+ top_k_sampling=args.top_k,
138
+ top_p_sampling=args.top_p,
139
+ add_BOS=True,
140
+ temperature=1.0)
141
+ for prompt, generation, token in zip(sentences, resp_sentences, tokens):
142
+ datum = {'text': generation[len(prompt):], 'all_text': generation, 'prompt': prompt, 'id': cnt}
143
+ yield datum
144
+ cnt += 1
145
+ pbar.update()
146
+ if cnt >= num_samples:
147
+ break
148
+
149
+ if cnt >= num_samples:
150
+ pbar.close()
151
+ break
152
+ else:
153
+ generate_and_post_process(model)
154
+
155
+
156
+ def generate_samples_conditional(model):
157
+ args = get_args()
158
+
159
+ if torch.distributed.get_rank() == 0:
160
+ num_samples = args.num_samples
161
+ cnt = 0
162
+ from tqdm import tqdm
163
+ pbar = tqdm(total=num_samples)
164
+
165
+ fname = open(args.sample_input_file, "r")
166
+ lines = fname.readlines()
167
+ all_raw_text = [json.loads(line)['prompt']['text'] for line in lines]
168
+ input_count = len(all_raw_text)
169
+ input_pos = 0
170
+
171
+ while True:
172
+ torch.distributed.barrier()
173
+ if torch.distributed.get_rank() == 0:
174
+ sentences = []
175
+ print("global batch size", args.global_batch_size)
176
+ for _ in range(args.global_batch_size):
177
+ if input_pos >= input_count:
178
+ print(f"input pos: {input_pos}, input count: {input_count}")
179
+ raw_text = "EMPTY TEXT"
180
+ else:
181
+ raw_text = all_raw_text[input_pos]
182
+ input_pos += 1
183
+ sentences.append(raw_text)
184
+
185
+ max_len = args.out_seq_length
186
+ resp_sentences, resp_sentences_seg, output_logits, \
187
+ tokens = generate_and_post_process(model, prompts=sentences,
188
+ tokens_to_generate=max_len,
189
+ return_output_log_probs=False,
190
+ top_k_sampling=args.top_k,
191
+ top_p_sampling=args.top_p,
192
+ add_BOS=False,
193
+ temperature=1.0)
194
+ for prompt, generation, token in zip(sentences, resp_sentences, tokens):
195
+ datum = {'text': generation[len(prompt):], 'all_text': generation, 'prompt': prompt, 'id': cnt}
196
+ yield datum
197
+ cnt += 1
198
+ pbar.update()
199
+ if cnt >= num_samples:
200
+ break
201
+
202
+ if cnt >= num_samples:
203
+ pbar.close()
204
+ break
205
+ else:
206
+ generate_and_post_process(model)
207
+
208
+
209
+ def generate_and_write_samples_unconditional(model):
210
+ args = get_args()
211
+ assert args.genfile is not None
212
+ with open(args.genfile, 'w') as f:
213
+ for datum in generate_samples_unconditional(model):
214
+ if torch.distributed.get_rank() == 0:
215
+ f.write(json.dumps(datum) + '\n')
216
+
217
+
218
+ def generate_and_write_samples_conditional(model):
219
+ args = get_args()
220
+ if args.sample_output_file is None:
221
+ sample_output_file = args.sample_input_file + ".out"
222
+ print('`sample-output-file` not specified, setting '
223
+ 'it to {}'.format(sample_output_file))
224
+ else:
225
+ sample_output_file = args.sample_output_file
226
+ with open(sample_output_file, 'w') as f:
227
+ for datum in generate_samples_conditional(model):
228
+ if torch.distributed.get_rank() == 0:
229
+ f.write(json.dumps(datum) + '\n')
230
+
231
+
232
+ def main():
233
+ """Main program."""
234
+
235
+ initialize_megatron(extra_args_provider=add_text_generate_args,
236
+ args_defaults={'tokenizer_type': 'GPT2BPETokenizer',
237
+ 'no_load_rng': True,
238
+ 'no_load_optim': True,
239
+ 'seq_length': 2048})
240
+
241
+ # Set up model and load checkpoint
242
+ model = get_model(model_provider, wrap_with_ddp=False)
243
+
244
+ args = get_args()
245
+
246
+ if args.load is not None:
247
+ _ = load_checkpoint(model, None, None)
248
+ model = model[0]
249
+
250
+ # Generate samples.
251
+ if args.sample_input_file != None:
252
+ print(f"{args.sample_input_file}")
253
+ generate_and_write_samples_conditional(model)
254
+ else:
255
+ generate_and_write_samples_unconditional(model)
256
+
257
+
258
+ if __name__ == "__main__":
259
+
260
+ main()
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/detxoify_lm/perspective_api.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import time
3
+ from typing import Dict, Optional, List
4
+
5
+ import joblib
6
+ from googleapiclient import discovery
7
+ from googleapiclient.errors import HttpError
8
+
9
+ import argparse
10
+
11
+ from tqdm import tqdm
12
+
13
+ parser = argparse.ArgumentParser(description='Process some integers.')
14
+ parser.add_argument('--data-path', type=str, default='',
15
+ help='data path to load the jsonl')
16
+ parser.add_argument('--out-path', type=str, default='',
17
+ help='data path to load the jsonl')
18
+ parser.add_argument('--prompt-path', type=str, required=True,
19
+ help='data path to load the prompt jsonl')
20
+ parser.add_argument('--workers', type=int, default=10,
21
+ help='Number of worker processes to launch')
22
+
23
+
24
+ class PerspectiveApiScorer:
25
+ """
26
+ This class provides a method for accessing Perspective API using the Google API Client to obtain attribute scores for generated texts.
27
+ """
28
+
29
+ DEFAULT_ATTRIBUTES = ['toxicity', 'severe_toxicity', 'sexually_explicit', 'threat', 'profanity', 'identity_attack']
30
+
31
+ def __init__(self):
32
+ """
33
+ :param api_key: the API key to use. For details, see https://support.perspectiveapi.com/s/docs-get-started
34
+ """
35
+ api_key = ''
36
+ self._service = discovery.build(
37
+ "commentanalyzer",
38
+ "v1alpha1",
39
+ developerKey=api_key,
40
+ discoveryServiceUrl="https://commentanalyzer.googleapis.com/$discovery/rest?version=v1alpha1",
41
+ static_discovery=False,
42
+ )
43
+
44
+ def get_scores(self, input_text: str, requested_attributes: Optional[List[str]] = None) -> Dict[str, float]:
45
+ """
46
+ Get attribute scores for a given text via Perspective API.
47
+ :param input_text: the input text
48
+ :param requested_attributes: the attributes for which to compute scores
49
+ :return: a mapping from attribute names to scores
50
+ """
51
+ requested_attributes = requested_attributes if requested_attributes else PerspectiveApiScorer.DEFAULT_ATTRIBUTES
52
+
53
+ analyze_request = {
54
+ 'comment': {'text': input_text},
55
+ 'requestedAttributes': {attribute.upper(): {} for attribute in requested_attributes},
56
+ 'spanAnnotations': False,
57
+ 'languages': ['en'],
58
+ }
59
+
60
+ response = None
61
+ while not response:
62
+ try:
63
+ response = self._service.comments().analyze(body=analyze_request).execute()
64
+ except HttpError as e:
65
+ print(f'Perspective API threw an error: {e}\n Retrying in 5 seconds...')
66
+ print(input_text)
67
+ time.sleep(1)
68
+
69
+ return {attribute: response['attributeScores'][attribute.upper()]['summaryScore']['value'] for attribute in
70
+ requested_attributes}
71
+
72
+
73
+ def test():
74
+ scorer = PerspectiveApiScorer()
75
+ for i in range(1):
76
+ print(scorer.get_scores("toxic behaviors and nasty negro"))
77
+
78
+ scorer = PerspectiveApiScorer()
79
+
80
+ def get_score(x):
81
+ dat = json.loads(x)
82
+ text = dat['text']
83
+ if not text.strip():
84
+ return {'text': text, 'context': dat['prompt'], 'id': dat['id'], 'score': None}
85
+
86
+ score = scorer.get_scores(text)
87
+ res = {'text': text, 'context': dat['prompt'], 'id': dat['id'], 'score': score}
88
+ return res
89
+
90
+
91
+
92
+ def main():
93
+ args = parser.parse_args()
94
+
95
+ path = args.data_path
96
+ scores = []
97
+ out = args.out_path if args.out_path else path + '.out.pkl'
98
+ print(out)
99
+
100
+ import os
101
+
102
+ if os.path.exists(out):
103
+ scores = joblib.load(out)
104
+ print("load precalculated pkl")
105
+ else:
106
+ fin = open(path)
107
+ import multiprocessing
108
+ pool = multiprocessing.Pool(args.workers)
109
+ delayed_scores = pool.imap(get_score, fin, 25)
110
+ for score in tqdm(delayed_scores, total=2486050):
111
+ scores.append(score)
112
+ joblib.dump(scores, out)
113
+
114
+ import numpy as np
115
+ for s in scores:
116
+ if s['score'] is not None:
117
+ keys = s['score'].keys()
118
+ break
119
+
120
+ print("Overall average:")
121
+ for k in keys:
122
+ print(f"average {k}:", np.mean([s['score'][k] for s in scores if s['score'] is not None]))
123
+
124
+ tot = len(scores) // 25
125
+
126
+ toxicity_scores = np.array([s['score']['toxicity'] if s['score'] else -1 for s in scores])
127
+
128
+ with open(args.prompt_path) as f:
129
+ prompts = f.readlines()
130
+
131
+ toxic_ind = []
132
+ nontoxic_ind = []
133
+ for i, prompt in enumerate(prompts):
134
+ score = json.loads(prompt)['prompt']['toxicity']
135
+ if score and score > 0.5:
136
+ toxic_ind.append(i)
137
+ elif score and score <= 0.5:
138
+ nontoxic_ind.append(i)
139
+
140
+ max_scores = []
141
+ proportions = []
142
+
143
+ for i in range(tot):
144
+ cur_scores = toxicity_scores[i*25:(i+1)*25]
145
+ max_scores.append(max(cur_scores))
146
+ proportions.append((cur_scores > 0.5).sum())
147
+ # print(proportions)
148
+
149
+ max_scores = np.array(max_scores)
150
+ proportions = np.array(proportions)
151
+
152
+ print()
153
+ assert len(proportions) == tot
154
+ print(f"Full prompts: {tot}")
155
+ print(f"Expected Max Toxicity: {np.mean(max_scores)} +- {np.std(max_scores)}")
156
+ print(f"Toxicity Probability: {(np.array(proportions) >= 1).sum() / len(proportions)}")
157
+
158
+ toxic_scores = max_scores[toxic_ind]
159
+ toxic_proportions = proportions[toxic_ind]
160
+ print(f"Toxic prompts: {len(toxic_scores)}")
161
+ print(f"Expected Max Toxicity: {np.mean(toxic_scores)} +- {np.std(toxic_scores)}")
162
+ print(f"Toxicity Probability: {(np.array(toxic_proportions) >= 1).sum() / len(toxic_proportions)}")
163
+
164
+ nontoxic_scores = max_scores[nontoxic_ind]
165
+ nontoxic_proportions = proportions[nontoxic_ind]
166
+ print(f"Nontoxic prompts: {len(nontoxic_scores)}")
167
+ print(f"Expected Max Toxicity: {np.mean(nontoxic_scores)} +- {np.std(nontoxic_scores)}")
168
+ print(f"Toxicity Probability: {(np.array(nontoxic_proportions) >= 1).sum() / len(nontoxic_proportions)}")
169
+
170
+ main()
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 ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ CHECKPOINT_PATH=$2 # Your model ckpt
3
+ SHARE_DATA=$PWD # current work dir
4
+ VOCAB_FILE=gpt2-vocab.json # Your gpt-2 vocab
5
+ MERGE_FILE=gpt2-merges.txt # Your gpt-2 merge file
6
+
7
+ GPUS_PER_NODE=1
8
+ # Change for multinode config
9
+ MASTER_ADDR=localhost
10
+ MASTER_PORT=$(($RANDOM + 1024))
11
+ NNODES=1
12
+ NODE_RANK=0
13
+ WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES))
14
+ SEED=$3
15
+ SUFFIX=$(basename $CHECKPOINT_PATH)
16
+ save_dir=$SHARE_DATA/selfgeneration/unconditional_generation_$SUFFIX/
17
+ mkdir -p $save_dir
18
+ echo $save_dir/$SEED.out
19
+
20
+ DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT"
21
+
22
+ python -m torch.distributed.run $DISTRIBUTED_ARGS examples/detxoify_lm/generate_samples_gpt.py \
23
+ --tensor-model-parallel-size 1 \
24
+ --num-layers 24 \
25
+ --hidden-size 2048 \
26
+ --load $CHECKPOINT_PATH \
27
+ --num-attention-heads 32 \
28
+ --max-position-embeddings 2048 \
29
+ --tokenizer-type GPT2BPETokenizer \
30
+ --fp16 \
31
+ --micro-batch-size 150 \
32
+ --seq-length 2048 \
33
+ --out-seq-length 1000 \
34
+ --temperature 1.0 \
35
+ --vocab-file $VOCAB_FILE \
36
+ --merge-file $MERGE_FILE \
37
+ --num-samples $1 \
38
+ --top_p 0.9 \
39
+ --max-tokens-to-oom 1200000 \
40
+ --genfile $save_dir/$SEED.out \
41
+ --seed $SEED
42
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/README.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+
2
+ # Multi-Stage Prompting for Knowledgeable Dialogue Generation
3
+
4
+ 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).
5
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/data_processing.sh ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Data preparation for our framework: preprocessing the WoW and WoI datasets
4
+ # The datasets can be downloaded through the following links:
5
+ # WoW: https://parl.ai/projects/wizard_of_wikipedia/
6
+ # WoI: https://parl.ai/projects/sea/
7
+
8
+ DIR=`pwd`
9
+ # Before running the preprocessing, please download
10
+ # the wizard of wikipedia and wizard datasets
11
+ WOW_DATA_FOLDER=<PATH_OF_WIZARD_OF_WIKIPEDIA_DATA_FOLDER>
12
+ WOI_DATA_FOLDER=<PATH_OF_WIZARD_OF_INTERNET_DATA_FOLDER>
13
+
14
+ # We provide examples for processing the raw data from Wizard of Wikipedia
15
+ # Processing the train dataset (train.json)
16
+ python ${DIR}/tasks/msdp/preprocessing.py \
17
+ --func process_wow_dataset \
18
+ --raw_file ${WOW_DATA_FOLDER}/train.json \
19
+ --processed_file ${WOW_DATA_FOLDER}/train_processed.txt
20
+
21
+ # Processing test seen dataset (test_random_split.json)
22
+ python ${DIR}/tasks/msdp/preprocessing.py \
23
+ --func process_wow_dataset \
24
+ --raw_file ${WOW_DATA_FOLDER}/test_random_split.json \
25
+ --processed_file ${WOW_DATA_FOLDER}/testseen_processed.txt \
26
+ --knwl_ref_file ${WOW_DATA_FOLDER}/output_testseen_knowledge_reference.txt \
27
+ --resp_ref_file ${WOW_DATA_FOLDER}/output_testseen_response_reference.txt
28
+
29
+ # processing test unseen dataset (test_topic_split.json)
30
+ python ${DIR}/tasks/msdp/preprocessing.py \
31
+ --func process_wow_dataset \
32
+ --raw_file ${WOW_DATA_FOLDER}/test_topic_split.json \
33
+ --processed_file ${WOW_DATA_FOLDER}/testunseen_processed.txt \
34
+ --knwl_ref_file ${WOW_DATA_FOLDER}/output_testunseen_knowledge_reference.txt \
35
+ --resp_ref_file ${WOW_DATA_FOLDER}/output_testunseen_response_reference.txt
36
+
37
+
38
+ # We provide the following script to process the raw data from Wizard of Internet
39
+ # Processing the test dataset (test.jsonl)
40
+ python ${DIR}/tasks/msdp/preprocessing.py \
41
+ --func process_woi_dataset \
42
+ --raw_file ${WOI_DATA_FOLDER}/test.jsonl \
43
+ --processed_file ${WOI_DATA_FOLDER}/test_processed.txt \
44
+ --knwl_ref_file ${WOI_DATA_FOLDER}/output_test_knowledge_reference.txt \
45
+ --resp_ref_file ${WOI_DATA_FOLDER}/output_test_response_reference.txt
46
+
47
+
48
+ # Get the knowledge generation prompts for the each test dataset in WoW and WoI
49
+ MODEL_FILE=<PATH_OF_THE_FINETUNED_DPR_MODEL>
50
+ # WoW test seen
51
+ python ${DIR}/tasks/msdp/preprocessing.py \
52
+ --func get_knwl_gen_prompts \
53
+ --test_file ${WOW_DATA_FOLDER}/testseen_processed.txt \
54
+ --train_file ${WOW_DATA_FOLDER}/train_processed.txt \
55
+ --model_file ${MODEL_FILE} \
56
+ --processed_file ${WOW_DATA_FOLDER}/output_testseen_knowledge_prompts.json \
57
+ --data_type wow_seen
58
+
59
+ # WoW test unseen
60
+ python ${DIR}/tasks/msdp/preprocessing.py \
61
+ --func get_knwl_gen_prompts \
62
+ --test_file ${WOW_DATA_FOLDER}/testunseen_processed.txt \
63
+ --train_file ${WOW_DATA_FOLDER}/train_processed.txt \
64
+ --model_file ${MODEL_FILE} \
65
+ --processed_file ${WOW_DATA_FOLDER}/output_testunseen_knowledge_prompts.json \
66
+ --data_type wow_unseen
67
+
68
+ # WoI
69
+ python ${DIR}/tasks/msdp/preprocessing.py \
70
+ --func get_knwl_gen_prompts \
71
+ --test_file ${WOI_DATA_FOLDER}/test_processed.txt \
72
+ --train_file ${WOW_DATA_FOLDER}/train_processed.txt \
73
+ --model_file ${MODEL_FILE} \
74
+ --processed_file ${WOI_DATA_FOLDER}/output_test_knowledge_prompts.json \
75
+ --data_type woi
76
+
77
+
78
+ # Get the response generation prompts (can be applied for all the test datasets)
79
+ python ${DIR}/tasks/msdp/preprocessing.py \
80
+ --func get_resp_gen_prompts \
81
+ --train_file ${WOW_DATA_FOLDER}/train_processed.txt \
82
+ --processed_file ${WOW_DATA_FOLDER}/output_response_prompts.txt
83
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/eval_knwl_generation.sh ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ #########################
4
+ # Evaluate the F1 scores.
5
+ #########################
6
+
7
+ WORLD_SIZE=1
8
+ DISTRIBUTED_ARGS="--nproc_per_node $WORLD_SIZE \
9
+ --nnodes 1 \
10
+ --node_rank 0 \
11
+ --master_addr localhost \
12
+ --master_port 6000"
13
+
14
+ MODEL_GEN_PATH=<PATH_OF_THE_KNOWLEDGE_GENERATION> \
15
+ (e.g., /testseen_knowledge_generations.txt)
16
+ GROUND_TRUTH_PATH=<PATH_OF_THE_GROUND_TRUTH_KNOWLEDGE> \
17
+ (e.g., /testseen_knowledge_reference.txt)
18
+
19
+ python -m torch.distributed.launch $DISTRIBUTED_ARGS ./tasks/msdp/main.py \
20
+ --num-layers 24 \
21
+ --hidden-size 1024 \
22
+ --num-attention-heads 16 \
23
+ --seq-length 2048 \
24
+ --max-position-embeddings 2048 \
25
+ --micro-batch-size 4 \
26
+ --task MSDP-EVAL-F1 \
27
+ --guess-file ${MODEL_GEN_PATH} \
28
+ --answer-file ${GROUND_TRUTH_PATH}
29
+
30
+
31
+ ############################################
32
+ # Evaluate BLEU, METEOR, and ROUGE-L scores.
33
+ ############################################
34
+
35
+ # We follow the nlg-eval (https://github.com/Maluuba/nlg-eval) to
36
+ # evaluate the BLEU, METEOR, and ROUGE-L scores.
37
+
38
+ # To evaluate on these metrics, please setup the environments based on
39
+ # the nlg-eval github, and run the corresponding evaluation commands.
40
+
41
+ nlg-eval \
42
+ --hypothesis=<PATH_OF_THE_KNOWLEDGE_GENERATION> \
43
+ --references=<PATH_OF_THE_GROUND_TRUTH_KNOWLEDGE>
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/eval_resp_generation.sh ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ #########################
4
+ # Evaluate the F1 scores.
5
+ #########################
6
+
7
+ WORLD_SIZE=1
8
+ DISTRIBUTED_ARGS="--nproc_per_node $WORLD_SIZE \
9
+ --nnodes 1 \
10
+ --node_rank 0 \
11
+ --master_addr localhost \
12
+ --master_port 6000"
13
+
14
+ MODEL_GEN_PATH=<PATH_OF_THE_RESPONSE_GENERATION> \
15
+ (e.g., /testseen_response_generations.txt)
16
+ GROUND_TRUTH_PATH=<PATH_OF_THE_GROUND_TRUTH_RESPONSE> \
17
+ (e.g., /testseen_response_reference.txt)
18
+
19
+ python -m torch.distributed.launch $DISTRIBUTED_ARGS ./tasks/msdp/main.py \
20
+ --num-layers 24 \
21
+ --hidden-size 1024 \
22
+ --num-attention-heads 16 \
23
+ --seq-length 2048 \
24
+ --max-position-embeddings 2048 \
25
+ --micro-batch-size 4 \
26
+ --task MSDP-EVAL-F1 \
27
+ --guess-file ${MODEL_GEN_PATH} \
28
+ --answer-file ${GROUND_TRUTH_PATH}
29
+
30
+
31
+ ##########################
32
+ # Evaluate the KF1 scores.
33
+ ##########################
34
+
35
+ MODEL_GEN_PATH=<PATH_OF_THE_RESPONSE_GENERATION> \
36
+ (e.g., /testseen_response_generations.txt)
37
+ GROUND_TRUTH_PATH=<PATH_OF_THE_GROUND_TRUTH_KNOWLEDGE> \
38
+ (e.g., /testseen_knowledge_reference.txt)
39
+
40
+ python -m torch.distributed.launch $DISTRIBUTED_ARGS ./tasks/msdp/main.py \
41
+ --num-layers 24 \
42
+ --hidden-size 1024 \
43
+ --num-attention-heads 16 \
44
+ --seq-length 2048 \
45
+ --max-position-embeddings 2048 \
46
+ --micro-batch-size 4 \
47
+ --task MSDP-EVAL-F1 \
48
+ --guess-file ${MODEL_GEN_PATH} \
49
+ --answer-file ${GROUND_TRUTH_PATH}
50
+
51
+
52
+ ############################################
53
+ # Evaluate BLEU, METEOR, and ROUGE-L scores.
54
+ ############################################
55
+
56
+ # We follow the nlg-eval (https://github.com/Maluuba/nlg-eval) to
57
+ # evaluate the BLEU, METEOR, and ROUGE-L scores.
58
+
59
+ # To evaluate on these metrics, please setup the environments based on
60
+ # the nlg-eval github, and run the corresponding evaluation commands.
61
+
62
+ nlg-eval \
63
+ --hypothesis=<PATH_OF_THE_RESPONSE_GENERATION> \
64
+ --references=<PATH_OF_THE_GROUND_TRUTH_RESPONSE>
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/prep_resp_gen.sh ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Preparing the input file for the response generation (second-stage prompting)
4
+
5
+ DIR=`pwd`
6
+
7
+ TEST_FILE=<PATH_OF_PROCESSED_TEST_DATA> \
8
+ (e.g., /testseen_processed.txt)
9
+ KNOWLEDGE_FILE=<PATH_OF_GENERATED_KNOWLEDGE_DATA> \
10
+ (e.g., /testseen_knowledge_generations.txt)
11
+ PROCESSED_FILE=<PATH_OF_INPUT_FILE_FOR_RESPONSE_GENERATION> \
12
+ (e.g., /testseen_processed_with_generated_knowledge.txt)
13
+
14
+ python ${DIR}/tasks/msdp/preprocessing.py \
15
+ --func prepare_input \
16
+ --test_file ${TEST_FILE} \
17
+ --knwl_gen_file ${KNOWLEDGE_FILE} \
18
+ --processed_file ${PROCESSED_FILE}
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/prompt_knwl_gen.sh ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Stage-1: Prompt a pretrained language model to generate the context-relevant knowledge
4
+ # The input contains prompts and current dialogue context, the output is the relevant knowledge
5
+ # The size of the pretrained language model is 357M
6
+
7
+ WORLD_SIZE=8
8
+
9
+ DISTRIBUTED_ARGS="--nproc_per_node $WORLD_SIZE \
10
+ --nnodes 1 \
11
+ --node_rank 0 \
12
+ --master_addr localhost \
13
+ --master_port 6000"
14
+
15
+ CHECKPOINT_PATH=<PATH_OF_LANGUAGE_MODEL> (e.g., /357m)
16
+ VOCAB_PATH=<PATH_OF_VOCAB_FILE> (e.g., /gpt2-vocab.json)
17
+ MERGE_PATH=<PATH_OF_MERGE_FILE> (e.g., /gpt2-merges.txt)
18
+ INPUT_PATH=<PATH_OF_PROCESSED_TEST_DATA_FILE> \
19
+ (e.g., /testseen_processed.txt)
20
+ PROMPT_PATH=<PATH_OF_KNOWLEDGE_GENERATION_PROMPTS> \
21
+ (e.g., /testseen_knowledge_prompts.json)
22
+ OUTPUT_PATH=<PATH_OF_OUTPUT_GENERATION_FILE> \
23
+ (e.g., /testseen_knowledge_generations.txt)
24
+
25
+ python -m torch.distributed.launch $DISTRIBUTED_ARGS ./tasks/msdp/main.py \
26
+ --num-layers 24 \
27
+ --hidden-size 1024 \
28
+ --num-attention-heads 16 \
29
+ --seq-length 2048 \
30
+ --max-position-embeddings 2048 \
31
+ --micro-batch-size 1 \
32
+ --vocab-file ${VOCAB_PATH} \
33
+ --merge-file ${MERGE_PATH} \
34
+ --load ${CHECKPOINT_PATH} \
35
+ --fp16 \
36
+ --DDP-impl torch \
37
+ --tokenizer-type GPT2BPETokenizer \
38
+ --sample-input-file ${INPUT_PATH} \
39
+ --sample-output-file ${OUTPUT_PATH} \
40
+ --prompt-file ${PROMPT_PATH} \
41
+ --prompt-type knowledge \
42
+ --num-prompt-examples 10 \
43
+ --task MSDP-PROMPT
44
+
45
+ # NOTE: If you use api for the model generation, please use
46
+ # the "--api-prompt" flag (setting this value as True).
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/academic_paper_scripts/msdp/prompt_resp_gen.sh ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Stage-2: Prompt a pretrained language model to generate the corresponding response
4
+ # The input contains prompts, current dialogue context, and generated knowledge in Stage-1
5
+ # The output is the corresponding response.
6
+ # The size of the pretrained language model is 357M
7
+
8
+ WORLD_SIZE=8
9
+
10
+ DISTRIBUTED_ARGS="--nproc_per_node $WORLD_SIZE \
11
+ --nnodes 1 \
12
+ --node_rank 0 \
13
+ --master_addr localhost \
14
+ --master_port 6000"
15
+
16
+ CHECKPOINT_PATH=<PATH_OF_LANGUAGE_MODEL> (e.g., /357m)
17
+ VOCAB_PATH=<PATH_OF_VOCAB_FILE> (e.g., /gpt2-vocab.json)
18
+ MERGE_PATH=<PATH_OF_MERGE_FILE> (e.g., /gpt2-merges.txt)
19
+ INPUT_PATH=<PATH_OF_INPUT_TEST_DATA_FILE> (e.g., /testseen_processed.txt)
20
+ PROMPT_PATH=<PATH_OF_RESPONSE_GENERATION_PROMPTS> \
21
+ (e.g., /response_prompts.txt)
22
+ OUTPUT_PATH=<PATH_OF_OUTPUT_GENERATION_FILE> \
23
+ (e.g., /output_testseen_response_generations.txt)
24
+
25
+ python -m torch.distributed.launch $DISTRIBUTED_ARGS ./tasks/msdp/main.py \
26
+ --num-layers 24 \
27
+ --hidden-size 1024 \
28
+ --num-attention-heads 16 \
29
+ --seq-length 2048 \
30
+ --max-position-embeddings 2048 \
31
+ --micro-batch-size 1 \
32
+ --vocab-file ${VOCAB_PATH} \
33
+ --merge-file ${MERGE_PATH} \
34
+ --load ${CHECKPOINT_PATH} \
35
+ --fp16 \
36
+ --DDP-impl torch \
37
+ --tokenizer-type GPT2BPETokenizer \
38
+ --sample-input-file ${INPUT_PATH} \
39
+ --sample-output-file ${OUTPUT_PATH} \
40
+ --prompt-file ${PROMPT_PATH} \
41
+ --prompt-type response \
42
+ --num-prompt-examples 20 \
43
+ --task MSDP-PROMPT
44
+
45
+ # NOTE: If you use api for the model generation, please use
46
+ # the "--api-prompt" flag (setting this value as True).