diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/gptoss/01_convert_from_hf.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/gptoss/01_convert_from_hf.py
new file mode 100644
index 0000000000000000000000000000000000000000..adee3358ec3c2866b77b2d20a163fa61525509f9
--- /dev/null
+++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/gptoss/01_convert_from_hf.py
@@ -0,0 +1,55 @@
+# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+"""Convert HuggingFace checkpoints to Megatron format."""
+
+import os
+import argparse
+
+from megatron.bridge import AutoBridge
+
+def _parse_args():
+ parser = argparse.ArgumentParser(description="Convert HF LLMs to Megatron format")
+ parser.add_argument(
+ "--hf-model",
+ type=str,
+ required=True,
+ help="HuggingFace model identifier or path",
+ )
+ parser.add_argument(
+ "--save-path",
+ type=str,
+ default=None,
+ help="Path to save the converted Megatron checkpoint",
+ )
+ parser.add_argument('--local-rank', '--local_rank', type=int, default=0)
+ return parser.parse_args()
+
+if __name__ == "__main__":
+ args = _parse_args()
+ HF_MODEL = args.hf_model
+ SAVE_PATH = args.save_path
+ WORLD_SIZE = int(os.environ.get("WORLD_SIZE", 1))
+
+ if SAVE_PATH is None:
+ SAVE_PATH = f"./megatron_checkpoints/{HF_MODEL.replace('/', '_')}"
+
+ print(f"Converting {HF_MODEL} to Megatron format...")
+ print(f"Save path: {SAVE_PATH}")
+
+ bridge = AutoBridge.from_hf_pretrained(HF_MODEL, trust_remote_code=True)
+ provider = bridge.to_megatron_provider()
+ # Update these configs as needed
+ provider.expert_tensor_parallel_size = 1
+ provider.tensor_model_parallel_size = 1
+ provider.pipeline_model_parallel_size = WORLD_SIZE
+ provider.finalize()
+
+ model = provider.provide_distributed_model(wrap_with_ddp=False)
+
+ bridge.save_megatron_model(
+ model,
+ SAVE_PATH,
+ hf_tokenizer_path=HF_MODEL
+ )
+
+ print(f"Saved Megatron checkpoint to {SAVE_PATH}")
diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/gptoss/02_train.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/gptoss/02_train.sh
new file mode 100644
index 0000000000000000000000000000000000000000..d129adc2b845a1ff0adcb83bca87cc22cb14a335
--- /dev/null
+++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/gptoss/02_train.sh
@@ -0,0 +1,259 @@
+#!/bin/bash
+
+export CUDA_DEVICE_MAX_CONNECTIONS=${CUDA_DEVICE_MAX_CONNECTIONS:-1}
+
+
+# Setup arguments with defaults
+CHECKPOINT_PATH="NO_VALUE_PROVIDED"
+TENSORBOARD_LOGS_PATH="./tensorboard_logs/"
+TOKENIZER_ARG="MOCK"
+DATA_ARG="MOCK"
+DISTRIBUTED_CONFIG_FILE=""
+
+# Parse command line arguments
+while [[ $# -gt 0 ]]; do
+ case $1 in
+ --checkpoint-path)
+ CHECKPOINT_PATH="$2"
+ shift 2
+ ;;
+ --tensorboard-logs-path)
+ TENSORBOARD_LOGS_PATH="$2"
+ shift 2
+ ;;
+ --tokenizer)
+ TOKENIZER_ARG="$2"
+ shift 2
+ ;;
+ --data)
+ DATA_ARG="$2"
+ shift 2
+ ;;
+ --distributed-config-file)
+ DISTRIBUTED_CONFIG_FILE="$2"
+ shift 2
+ ;;
+ -h|--help)
+ echo "Usage: $0 [OPTIONS]"
+ echo "Options:"
+ echo " --checkpoint-path PATH Path to Megatron checkpoint"
+ echo " --tensorboard-logs-path PATH Path to TensorBoard logs"
+ echo " --tokenizer PATH|MOCK Path to tokenizer model, or 'MOCK' (default: MOCK)"
+ echo " --data PATH|MOCK Data prefix, or 'MOCK' (default: MOCK)"
+ echo " --distributed-config-file FILE Path to distributed training config file"
+ echo " -h, --help Show this help message"
+ exit 0
+ ;;
+ *)
+ echo "Unknown option: $1"
+ echo "Use --help for usage information"
+ exit 1
+ ;;
+ esac
+done
+
+# Check if checkpoint path exists
+if [ ! -d "$CHECKPOINT_PATH" ]; then
+ echo "Error: Checkpoint path does not exist: $CHECKPOINT_PATH"
+ exit 1
+fi
+echo "Checkpoint path exists: $CHECKPOINT_PATH"
+
+# Check if tensorboard logs path exists
+if [ ! -d "$TENSORBOARD_LOGS_PATH" ]; then
+ echo "Warning: TensorBoard logs path does not exist. Creating: $TENSORBOARD_LOGS_PATH"
+ mkdir -p "$TENSORBOARD_LOGS_PATH"
+fi
+echo "TensorBoard logs path exists: $TENSORBOARD_LOGS_PATH"
+
+# NOTE: by default we use 8 GPUs
+# These values will be over-written below with environmental variables
+GPUS_PER_NODE=8
+NUM_NODES=1
+MASTER_ADDR="localhost"
+MASTER_PORT=6000
+NODE_RANK=0
+
+# Load distributed config from file if provided
+if [ -n "$DISTRIBUTED_CONFIG_FILE" ]; then
+ if [ ! -f "$DISTRIBUTED_CONFIG_FILE" ]; then
+ echo "Warning: Distributed config file does not exist: $DISTRIBUTED_CONFIG_FILE"
+ echo "Continuing with default distributed training settings."
+ else
+ echo "Loading distributed config from: $DISTRIBUTED_CONFIG_FILE"
+ source "$DISTRIBUTED_CONFIG_FILE"
+ fi
+fi
+
+# Override with environment variables if set
+GPUS_PER_NODE=${GPUS_PER_NODE:-8}
+NUM_NODES=${NUM_NODES:-1}
+MASTER_ADDR=${MASTER_ADDR:-localhost}
+MASTER_PORT=${MASTER_PORT:-6000}
+NODE_RANK=${NODE_RANK:-0}
+WORLD_SIZE=$(($GPUS_PER_NODE*$NUM_NODES))
+
+# Path to the pretrain_gpt.py script, assuming this script is run from the root of the Megatron-LM repository
+PRETRAIN_SCRIPT_PATH="pretrain_gpt.py"
+
+# Data cache path (useful for both mock and real data)
+DATA_CACHE_PATH="${PWD}/benchmark_cache_gpt_oss_20b"
+mkdir -p "$DATA_CACHE_PATH"
+
+DISTRIBUTED_ARGS=(
+ --nproc_per_node $GPUS_PER_NODE
+ --nnodes $NUM_NODES
+ --master_addr $MASTER_ADDR
+ --master_port $MASTER_PORT
+ --node_rank $NODE_RANK
+)
+
+# NOTE: we only set pipeline parallelism to be the number of GPUs
+# Adjust each value based on your setup.
+TP_SIZE=1
+EP_SIZE=1
+PP_SIZE=${WORLD_SIZE}
+MICRO_BATCH_SIZE=1
+GLOBAL_BATCH_SIZE=128
+NUM_LAYERS=12
+DTYPE="fp8"
+SEQ_LENGTH=8192
+MAX_POSITION_EMBEDDINGS=8192
+TRAIN_SAMPLES=1953125000
+LR_DECAY_SAMPLES=1949218748
+
+MODEL_ARGS=(
+ --no-masked-softmax-fusion
+ --transformer-impl transformer_engine
+ --disable-bias-linear
+ --untie-embeddings-and-output-weights
+ --no-rope-fusion
+ --normalization RMSNorm
+ --num-layers ${NUM_LAYERS}
+ --hidden-size 512
+ --ffn-hidden-size 2048
+ --num-attention-heads 64
+ --group-query-attention
+ --num-query-groups 8
+ --seq-length ${SEQ_LENGTH}
+ --max-position-embeddings ${MAX_POSITION_EMBEDDINGS}
+ --use-mcore-models
+ --rotary-percent 1.0
+ --rope-type rope
+ --position-embedding-type rope
+ --rotary-base 10000
+ --no-bias-gelu-fusion
+ --export-force-local-attention
+ --no-bias-dropout-fusion
+ --quick-geglu
+ --glu-linear-offset 1.0
+ --softmax-type learnable
+ --window-attn-skip-freq 2
+ --activation-func-clamp-value 7.0
+ --window-size 127,0
+ --enable-gpt-oss
+)
+
+MOE_ARGS=(
+ --num-experts 4
+ --moe-router-topk 2
+ --moe-router-load-balancing-type aux_loss
+ --moe-aux-loss-coeff 1e-3
+ --moe-grouped-gemm
+ --moe-token-dispatcher-type alltoall
+ --overlap-param-gather
+ --overlap-grad-reduce
+ --moe-ffn-hidden-size 2048
+ --moe-router-dtype fp32
+ --moe-z-loss-coeff 1e-3
+ --moe-permute-fusion
+)
+
+DATA_ARGS_LIST=()
+if [[ "$TOKENIZER_ARG" == "MOCK" ]] || [[ "$DATA_ARG" == "MOCK" ]] || [[ -z "$TOKENIZER_ARG" ]]; then
+ DATA_ARGS_LIST+=(
+ "--mock-data"
+ "--tokenizer-type NullTokenizer"
+ "--vocab-size 128256"
+ "--data-cache-path ${DATA_CACHE_PATH}"
+ "--tiktoken-pattern v2"
+ "--split '99,1,0'"
+ "--no-create-attention-mask-in-dataloader"
+ "--no-mmap-bin-files"
+ "--num-workers 1"
+ )
+else
+ # Settings for real data
+ DATA_ARGS_LIST+=(
+ "--data-path $DATA_ARG"
+ "--tokenizer-type HuggingFaceTokenizer"
+ "--tokenizer-model $TOKENIZER_ARG"
+ "--data-cache-path ${DATA_CACHE_PATH}"
+ "--split '99,1,0'"
+ "--no-create-attention-mask-in-dataloader"
+ "--no-mmap-bin-files"
+ "--num-workers 1"
+ # Note: --vocab-size might be inferred by HuggingFaceTokenizer or might need to be explicit.
+ "--vocab-size 128256"
+ )
+fi
+
+TRAINING_ARGS=(
+ --micro-batch-size ${MICRO_BATCH_SIZE}
+ --global-batch-size ${GLOBAL_BATCH_SIZE}
+ --lr 1.0e-5
+ --train-samples ${TRAIN_SAMPLES}
+ --lr-decay-samples ${LR_DECAY_SAMPLES}
+ --lr-decay-style cosine
+ --min-lr 1.0e-6
+ --weight-decay 0.1
+ --lr-warmup-fraction 0.05
+ --clip-grad 1.0
+ --bf16
+ --use-flash-attn
+ --attention-softmax-in-fp32
+ --accumulate-allreduce-grads-in-fp32
+ --disable-bf16-reduced-precision-matmul
+ --recompute-activations
+)
+
+MODEL_PARALLEL_ARGS=(
+ --tensor-model-parallel-size ${TP_SIZE}
+ --pipeline-model-parallel-size ${PP_SIZE}
+ --expert-model-parallel-size ${EP_SIZE}
+ --sequence-parallel
+ --context-parallel-size 1
+ --use-distributed-optimizer
+ --fp8-format hybrid
+ --fp8-param-gather
+ --fp8-amax-compute-algo max
+ --fp8-amax-history-len 1024
+)
+
+LOGGING_ARGS=(
+ --log-interval 1
+ --save-interval 10000
+ --eval-interval 50000000
+ --eval-iters 0
+ --save $CHECKPOINT_PATH
+ --tensorboard-dir "${CHECKPOINT_PATH}/tensorboard"
+ --moe-per-layer-logging
+ --no-load-optim
+ --no-load-rng
+ --log-throughput
+)
+
+# Ensure pretrain_gpt.py is found
+if [ ! -f "$PRETRAIN_SCRIPT_PATH" ]; then
+ echo "Error: pretrain_gpt.py not found at $PRETRAIN_SCRIPT_PATH"
+ echo "Please ensure you are running this script from the root of the Megatron-LM repository, and pretrain_gpt.py is present."
+ exit 1
+fi
+
+python -m torch.distributed.run ${DISTRIBUTED_ARGS[@]} ${PRETRAIN_SCRIPT_PATH} \
+ ${MODEL_ARGS[@]} \
+ ${MOE_ARGS[@]} \
+ ${DATA_ARGS_LIST[@]} \
+ ${TRAINING_ARGS[@]} \
+ ${MODEL_PARALLEL_ARGS[@]} \
+ ${LOGGING_ARGS[@]}
diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/gptoss/03_convert_to_hf.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/gptoss/03_convert_to_hf.py
new file mode 100644
index 0000000000000000000000000000000000000000..8089afec854fd78e7fc52674bb71efe78ec49f27
--- /dev/null
+++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/gptoss/03_convert_to_hf.py
@@ -0,0 +1,52 @@
+# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+"""Convert HuggingFace checkpoints to Megatron format."""
+
+import os
+import argparse
+
+from megatron.bridge import AutoBridge
+
+def _parse_args():
+ parser = argparse.ArgumentParser(description="Convert Megatron LLMs to HuggingFace format")
+ parser.add_argument(
+ "--hf-model",
+ type=str,
+ required=True,
+ help="HuggingFace model identifier or path to load config from",
+ )
+ parser.add_argument(
+ "--megatron-model",
+ type=str,
+ required=True,
+ help="Megatron model identifier or path",
+ )
+ parser.add_argument(
+ "--save-path",
+ type=str,
+ default=None,
+ help="Path to save the converted HuggingFace checkpoint",
+ )
+ parser.add_argument('--local-rank', '--local_rank', type=int, default=0)
+ return parser.parse_args()
+
+if __name__ == "__main__":
+ args = _parse_args()
+ HF_MODEL = args.hf_model
+ MEGATRON_MODEL = args.megatron_model
+ SAVE_PATH = args.save_path
+ WORLD_SIZE = int(os.environ.get("WORLD_SIZE", 1))
+
+ if SAVE_PATH is None:
+ SAVE_PATH = f"./huggingface_checkpoints/{MEGATRON_MODEL.replace('/', '_')}"
+
+ print(f"Converting {MEGATRON_MODEL} to HuggingFace {HF_MODEL} format...")
+ print(f"Save path: {SAVE_PATH}")
+
+ bridge = AutoBridge.from_hf_pretrained(HF_MODEL, trust_remote_code=True)
+ bridge.export_ckpt(
+ MEGATRON_MODEL,
+ SAVE_PATH,
+ )
+
+ print(f"Saved HuggingFace checkpoint to {SAVE_PATH}")
diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/gptoss/README.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/gptoss/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..eeb92ad995313989a9936f04bd2472b0ac765135
--- /dev/null
+++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/gptoss/README.md
@@ -0,0 +1,153 @@
+# GPT-OSS Training Tutorial
+
+## Step 0: Install Dependencies
+
+### Using Megatron Bridge
+
+[Megatron-Bridge](https://github.com/NVIDIA-NeMo/Megatron-Bridge)
+
+Megatron Bridge provides a quick and convenient way to convert HuggingFace checkpoints to the Megatron format used by Megatron-LM. Follow the instructions in the [Megatron-Bridge Installation](https://github.com/NVIDIA-NeMo/Megatron-Bridge/blob/main/README.md#-installation) to run the nemo docker container and convert checkpoints (via mounted volumes - make sure that the huggingface cache location AND the megatron checkpoint locations are properly mounted, otherwise you may not be saving the converted model to disk correctly).
+
+Below is an example of how to use Megatron-Bridge inside the pytorch container to convert a HuggingFace model checkpoint to Megatron format.
+
+Reference: [Megatron-Bridge Dockerfile](https://github.com/NVIDIA-NeMo/Megatron-Bridge/blob/main/docker/Dockerfile.ci)
+
+Inside the [pytorch container](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/pytorch) run the following commands to install Megatron-Bridge:
+```bash
+cd /opt
+git clone --recursive https://github.com/NVIDIA-NeMo/Megatron-Bridge.git
+cd Megatron-Bridge
+
+# Make sure submodules are initialized (for 3rdparty/Megatron-LM)
+git submodule update --init --recursive
+
+export PATH="/root/.local/bin:$PATH"
+export UV_PROJECT_ENVIRONMENT=/opt/venv
+export VIRTUAL_ENV=/opt/venv
+export PATH="$UV_PROJECT_ENVIRONMENT/bin:$PATH"
+export UV_LINK_MODE=copy
+export UV_VERSION="0.7.2"
+
+# Install UV
+curl -LsSf https://astral.sh/uv/${UV_VERSION}/install.sh | sh
+
+# Create virtual environment and build the package
+uv venv ${UV_PROJECT_ENVIRONMENT} --system-site-packages
+
+uv sync --locked --only-group build
+uv sync --locked --link-mode copy --all-extras --all-groups
+
+uv pip install --no-deps -e .
+
+source ${UV_PROJECT_ENVIRONMENT}/bin/activate
+```
+
+### Setup Environment
+
+```bash
+export HOST_MEGATRON_LM_DIR="/path/to/your/host/megatron-lm"
+git clone https://github.com/NVIDIA/Megatron-LM.git "$HOST_MEGATRON_LM_DIR"
+cd "$HOST_MEGATRON_LM_DIR"
+```
+
+```bash
+export HF_TOKEN={your_hf_token_here}
+```
+
+## Step 1: Convert HuggingFace to Megatron (Optional - skip if you already have a Megatron checkpoint)
+
+Set `--nproc-per-node` to be the number of GPUs per node. Set `hf_model_name` to be the Huggingface model e.g. `openai/gpt-oss-20b`
+
+```bash
+python3 -m torch.distributed.launch --nproc-per-node=8 examples/gptoss/01_convert_from_hf.py --hf-model openai/gpt-oss-20b
+```
+
+## Step 2: Train from Scratch
+
+To train from scratch first follow the steps below to setup the environment appropriately before running the training script in docker. Even though we are running the same container as before, it is better to restart the container to ensure a clean environment and that all environment and docker variables are set correctly. For the following example we used 8x GB300, but you should change the number of GPUs and nodes as needed.
+
+### Setup Environment
+
+```bash
+# Change these based on model and directory from previous conversion step
+export MODEL_DIR_NAME="openai_gpt-oss_20b"
+
+export HOST_CHECKPOINT_PATH="./megatron_checkpoints/${MODEL_DIR_NAME}"
+export HOST_TENSORBOARD_LOGS_PATH="./tensorboard_logs/${MODEL_DIR_NAME}"
+```
+
+By default we will use mock data to train the model in the example below. To use your own data, set the following environment variables:
+
+```bash
+# Optional: For real data
+export HOST_TOKENIZER_MODEL_PATH="/path/to/host/tokenizer.model"
+export HOST_DATA_PREFIX="/path/to/host/mydata_prefix"
+```
+
+### Setup Training Configurations
+
+Run the following to create a `distributed_config.env` file with the appropriate distributed training configurations. Change the values as needed for your setup. This file will override the default values in `02_train.sh`.
+
+```bash
+cat > ./distributed_config.env << 'EOF'
+GPUS_PER_NODE=8
+NUM_NODES=1
+MASTER_ADDR=localhost
+MASTER_PORT=6000
+NODE_RANK=0
+EOF
+```
+
+### Run Container with Mounted Volumes
+
+**NOTE:** This container runs the example training script `02_train.sh` located in the `examples/gptoss` directory. By default, we have only set pipeline parallelism to be the number of GPUs. Adjust TP_SIZE, EP_SIZE, PP_SIZE, etc. in `02_train.sh`. You can also adjust modify `--hidden-size`, `--ffn-hidden-size`, `--num-attention-heads`, `NUM_LAYERS`, etc.
+
+To train using mock data, run the following command:
+```bash
+PYTORCH_IMAGE="nvcr.io/nvidia/pytorch:25.12-py3"
+
+docker run --rm --gpus all --ipc=host --ulimit memlock=-1 \
+ -v "${HOST_MEGATRON_LM_DIR}:/workspace/megatron-lm" \
+ -v "${HOST_CHECKPOINT_PATH}:/workspace/checkpoints" \
+ -v "${HOST_TENSORBOARD_LOGS_PATH}:/workspace/tensorboard_logs" \
+ -v "./distributed_config.env:/workspace/megatron-lm/examples/gptoss/distributed_config.env" \
+ --workdir /workspace/megatron-lm \
+ $PYTORCH_IMAGE \
+ bash examples/gptoss/02_train.sh \
+ --checkpoint-path /workspace/checkpoints \
+ --tensorboard-logs-path /workspace/tensorboard_logs \
+ --distributed-config-file /workspace/megatron-lm/examples/gptoss/distributed_config.env \
+ 2>&1 | tee "${HOST_TENSORBOARD_LOGS_PATH}/training_mock_$(date +'%y-%m-%d_%H-%M-%S').log"
+```
+**Note:** If you run into issues generating mock data one solution might be to reduce the number of GPUs to 1 and try to generate the data again.
+
+If using real data with with the `HOST_TOKENIZER_MODEL_PATH` and `HOST_DATA_PREFIX` environment variables set, run the following command instead:
+
+```bash
+PYTORCH_IMAGE="nvcr.io/nvidia/pytorch:25.12-py3"
+
+docker run --rm --gpus all --ipc=host --ulimit memlock=-1 \
+ -v "${HOST_MEGATRON_LM_DIR}:/workspace/megatron-lm" \
+ -v "${HOST_CHECKPOINT_PATH}:/workspace/checkpoints" \
+ -v "${HOST_TENSORBOARD_LOGS_PATH}:/workspace/tensorboard_logs" \
+ -v "${HOST_TOKENIZER_MODEL_PATH}:/workspace/tokenizer_model" \
+ -v "$(dirname "${HOST_DATA_PREFIX}"):/workspace/data_dir" \
+ -v "./distributed_config.env:/workspace/megatron-lm/examples/gptoss/distributed_config.env" \
+ --workdir /workspace/megatron-lm \
+ $PYTORCH_IMAGE \
+ bash examples/gptoss/02_train.sh \
+ --checkpoint-path /workspace/checkpoints \
+ --tensorboard-logs-path /workspace/tensorboard_logs \
+ --tokenizer /workspace/tokenizer_model \
+ --data "/workspace/data_dir/$(basename "${HOST_DATA_PREFIX}")" \
+ --distributed-config-file /workspace/megatron-lm/examples/gptoss/distributed_config.env \
+ 2>&1 | tee "${HOST_TENSORBOARD_LOGS_PATH}/training_custom_$(date +'%y-%m-%d_%H-%M-%S').log"
+```
+
+## Step 3: Convert Megatron to HuggingFace
+
+Just run the following command to change from the megatron checkpoint from training to the huggingface format to share with others (make sure you have the same virtual environment setup as in Step 0):
+
+```bash
+python3 -m torch.distributed.launch --nproc-per-node=8 examples/gptoss/03_convert_to_hf.py --hf-model openai/gpt-oss-20b --megatron-model ./megatron_checkpoints/openai_gpt-oss_20b
+```
\ No newline at end of file
diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/.gitignore b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..940f4797e4b38d11f2ec6bed38a664e910ff9ae8
--- /dev/null
+++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/.gitignore
@@ -0,0 +1,4 @@
+checkpoints/
+data-cache/
+tensorboard/
+triton-cache/
diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/Dockerfile b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..2e194095b759e1c5e7f34340b716757c5d1a207d
--- /dev/null
+++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/Dockerfile
@@ -0,0 +1,32 @@
+FROM nvcr.io/nvidia/pytorch:24.01-py3
+
+RUN pip uninstall -y triton && \
+ pip install triton==2.1.0 sentencepiece==0.1.99 flask-restful
+
+# The causal-conv1d and mamba-ssm packages below are built from scratch here
+# (which takes significant time) because there are no wheels available on PyPI
+# for these relatively newer versions of the packages that are compatible with
+# the older NGC-variant PyTorch version (e.g. version 2.2.0.dev231106) that we
+# are using (in the NGC base container). Generally, if the package is not
+# compatible with the PyTorch version, then it will generate a Python import
+# error. The package authors tend to only release wheels for new versions of
+# these pacakges which are compatible with the versions of regular PyTorch and
+# NGC-variant PyTorch that are newer at the time of release. So, to use newer
+# versions of these packages with relatively older versions of the NGC PyTorch
+# container, we tend to have to build the packages from scratch.
+
+RUN cd /tmp && \
+ git clone https://github.com/Dao-AILab/causal-conv1d.git && \
+ cd causal-conv1d && \
+ git checkout v1.2.2.post1 && \
+ CAUSAL_CONV1D_FORCE_BUILD=TRUE pip install . && \
+ cd .. && \
+ rm -rf causal-conv1d
+
+RUN cd /tmp && \
+ git clone https://github.com/state-spaces/mamba.git && \
+ cd mamba && \
+ git checkout v2.0.3 && \
+ MAMBA_FORCE_BUILD=TRUE pip install . && \
+ cd .. && \
+ rm -rf mamba
diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/README.md b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..ce60f119ea544e188af00be8e18a1d9eea63d10e
--- /dev/null
+++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/README.md
@@ -0,0 +1,117 @@
+# Mamba-based Language Models
+
+## Introduction
+
+This document is an entrypoint into the code used for
+[An Empirical Study of Mamba-based Language Models](https://arxiv.org/abs/2406.07887).
+
+We are releasing the parameters for some of the models described in that
+technical report via
+[HuggingFace](https://huggingface.co/collections/nvidia/ssms-666a362c5c3bb7e4a6bcfb9c).
+The code in the `main` branch is no longer compatible with the `Mamba2-*`
+checkpoints. You can load them using the
+[fixed snapshot of the code used for the technical report](https://github.com/NVIDIA/Megatron-LM/tree/ssm/examples/mamba).
+
+## Installation
+
+Create and run a Docker container using the [Dockerfile](./Dockerfile).
+
+```
+docker build -t your_image_name:your_tag .
+docker run --gpus all -it --rm \
+ -v /path/to/megatron:/workspace/megatron \
+ -v /path/to/dataset:/workspace/dataset \
+ -v /path/to/checkpoints:/workspace/checkpoints \
+ -w /workspace/megatron/examples/mamba \
+ your_image_name:your_tag
+```
+
+## Train
+
+[`train.sh`](./train.sh) is an example pretraining script, showing how to run on
+a single node. Select between 800M-scale and 8B-scale models by setting the
+`MODEL_SCALE` variable. The 8B-scale hybrid model architecture is the same as
+the one described in the technical report.
+
+## Text Generation
+
+Use [`run_text_gen_server_8b.sh`](./run_text_gen_server_8b.sh) to start a text
+generation server using an 8B hybrid checkpoint. This is configured to run the
+8B hybrid model described in the technical report, with tensor model parallel
+set to 1.
+
+The arguments in the script will need to be changed if using a checkpoint with a
+different model parallel configuration or other differences, such as model
+architecture. For example, to run the 8B pure Mamba-2 model, change
+`--hybrid-layer-pattern` to use only `M` symbols (e.g., 56 `M`s for the 8B
+model), or remove it entirely.
+
+Use [`run_text_gen_server_8b_gpt3.sh`](./run_text_gen_server_8b_gpt3.sh) to start
+a text generation server using the 8B reference Transformer checkpoint.
+
+## Checkpoint Formats
+
+For inference, the model must be configured to match the checkpoint file used,
+including the hybrid layer configuration and model parallel configuration.
+
+If you need to convert a hybrid checkpoint file to a different tensor parallel
+or pipeline parallel size, use
+[the hybrid conversion script](../../tools/checkpoint/hybrid_conversion.py).
+There is an example run command at the end of that file.
+
+Before running that script, you will need to set `PYTHONPATH` to include the
+root directory of your Megatron-LM repository clone.
+
+```
+export PYTHONPATH=:PYTHONPATH
+```
+
+## Hybrid Options
+
+`--hybrid-layer-pattern PATTERN` specifies the layer type for every layer in
+the model using a string of single-character symbols:
+
+* `M` — Mamba layer
+* `*` — Attention layer
+* `-` — MLP layer
+* `E` — MoE layer
+
+The number of layers is derived from the pattern length, so `--num-layers`
+should not be specified when `--hybrid-layer-pattern` is used.
+
+For example, the 8B hybrid model described in the technical report uses:
+
+```
+--hybrid-layer-pattern "M-M-M--M-M*-M-M-M-M--M*-M-M-M-M-M*--M-M-M-M-M*-M--M-M-M-"
+```
+
+This is a 56-layer model with 4 attention layers, 28 MLP layers, and 24 Mamba
+layers.
+
+A pure Mamba model uses only `M` symbols (e.g., `MMMMMMMM` for 8 layers).
+A pure transformer model uses only `*` and `-` symbols.
+
+### Pipeline parallelism
+
+Use `|` to define pipeline stage boundaries for flexible virtual pipeline
+parallelism (fVPP). For example, `M-M-|M-M*-|M-M-|M-M*-` defines 4 pipeline
+segments. The number of segments must be evenly divisible by
+`--pipeline-model-parallel-size`.
+
+### Multi-Token Prediction (MTP)
+
+Use `/` to append MTP layer patterns. Each pattern after the separator
+represents one MTP prediction depth. For example, `M*M*/MM/MM` has main
+pattern `M*M*` with MTP pattern `MM` repeated for 2 depths.
+
+### Deprecated options
+
+`--hybrid-override-pattern`, `--hybrid-attention-ratio`, and
+`--hybrid-mlp-ratio` are deprecated. Use `--hybrid-layer-pattern` instead.
+
+## Mamba vs Mamba-2
+
+This codebase currently only supports Mamba-2, and not the original version of
+Mamba. However, the
+[fixed snapshot of the code used for the technical report](https://github.com/NVIDIA/Megatron-LM/tree/ssm/examples/mamba)
+can be configured to run the original version of Mamba.
diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/run_text_gen_server_8b.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/run_text_gen_server_8b.sh
new file mode 100644
index 0000000000000000000000000000000000000000..d228e0c0edb75700544e47021d8133ca65745027
--- /dev/null
+++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/run_text_gen_server_8b.sh
@@ -0,0 +1,50 @@
+#!/bin/bash
+
+# Use: ./run_text_gen_server_8b.sh
+# To launch the client: python ../../tools/text_generation_cli.py
+
+CHECKPOINT_PATH=$1
+TOKENIZER_PATH=$2
+
+HYBRID_LAYER_PATTERN="M-M-M--M-M*-M-M-M-M--M*-M-M-M-M-M*--M-M-M-M-M*-M--M-M-M-"
+
+DISTRIBUTED_ARGS="--nproc_per_node 1 \
+ --nnodes 1 \
+ --node_rank 0 \
+ --master_addr localhost \
+ --master_port 6000"
+
+export NCCL_IB_SL=1
+export CUDA_DEVICE_MAX_CONNECTIONS=1
+export NCCL_IB_TIMEOUT=19
+export NCCL_IB_QPS_PER_CONNECTION=4
+
+export TRITON_CACHE_DIR="./triton-cache/"
+export TRITON_CACHE_MANAGER="megatron.core.ssm.triton_cache_manager:ParallelFileCacheManager"
+
+torchrun $DISTRIBUTED_ARGS ../../tools/run_mamba_text_generation_server.py \
+ --tensor-model-parallel-size 1 \
+ --pipeline-model-parallel-size 1 \
+ --untie-embeddings-and-output-weights \
+ --hybrid-layer-pattern ${HYBRID_LAYER_PATTERN} \
+ --hidden-size 4096 \
+ --load ${CHECKPOINT_PATH} \
+ --num-attention-heads 32 \
+ --group-query-attention \
+ --num-query-groups 8 \
+ --attention-dropout 0.0 \
+ --hidden-dropout 0.0 \
+ --disable-bias-linear \
+ --normalization RMSNorm \
+ --seq-length 4096 \
+ --max-position-embeddings 4096 \
+ --position-embedding-type none \
+ --tokenizer-type GPTSentencePieceTokenizer \
+ --tokenizer-model ${TOKENIZER_PATH} \
+ --distributed-backend nccl \
+ --distributed-timeout-minutes 1440 \
+ --bf16 \
+ --micro-batch-size 1 \
+ --use-mcore-models \
+ --spec megatron.core.models.mamba.mamba_layer_specs mamba_stack_spec \
+ --seed 42
diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/run_text_gen_server_8b_gpt3.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/run_text_gen_server_8b_gpt3.sh
new file mode 100644
index 0000000000000000000000000000000000000000..5413b245ed3af0c6753bfc414e531231be386bc4
--- /dev/null
+++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/run_text_gen_server_8b_gpt3.sh
@@ -0,0 +1,46 @@
+#!/bin/bash
+
+# Use: ./run_text_gen_server_8b_gpt3.sh
+# To launch the client: python ../../tools/text_generation_cli.py
+
+CHECKPOINT_PATH=$1
+TOKENIZER_PATH=$2
+
+DISTRIBUTED_ARGS="--nproc_per_node 1 \
+ --nnodes 1 \
+ --node_rank 0 \
+ --master_addr localhost \
+ --master_port 6000"
+
+export NCCL_IB_SL=1
+export CUDA_DEVICE_MAX_CONNECTIONS=1
+export NCCL_IB_TIMEOUT=19
+export NCCL_IB_QPS_PER_CONNECTION=4
+
+torchrun $DISTRIBUTED_ARGS ../../tools/run_text_generation_server.py \
+ --tensor-model-parallel-size 1 \
+ --pipeline-model-parallel-size 1 \
+ --use-flash-attn \
+ --apply-layernorm-1p \
+ --untie-embeddings-and-output-weights \
+ --num-layers 32 \
+ --hidden-size 4096 \
+ --load ${CHECKPOINT_PATH} \
+ --num-attention-heads 32 \
+ --attention-dropout 0.0 \
+ --hidden-dropout 0.0 \
+ --disable-bias-linear \
+ --seq-length 4096 \
+ --max-position-embeddings 4096 \
+ --position-embedding-type rope \
+ --rotary-percent 0.5 \
+ --squared-relu \
+ --tokenizer-type GPTSentencePieceTokenizer \
+ --tokenizer-model ${TOKENIZER_PATH} \
+ --distributed-backend nccl \
+ --distributed-timeout-minutes 1440 \
+ --bf16 \
+ --micro-batch-size 1 \
+ --use-mcore-models \
+ --transformer-impl local \
+ --seed 42
diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/train.sh b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/train.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ba83f0d4e3361435e817e52f71a3ecbad3a63357
--- /dev/null
+++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/train.sh
@@ -0,0 +1,103 @@
+#!/bin/bash
+
+# Use: ./train.sh
+
+MODEL_SCALE="800M" # or "8B"
+
+case "${MODEL_SCALE}" in
+ "800M")
+ TENSOR_MODEL_PARALLEL_SIZE=1
+ HYBRID_LAYER_PATTERN="M-M-M--M-*M-M-M-M--*M-M-M-M-*M--M-M-M-*M-M--M-M-"
+ HIDDEN_SIZE=1024
+ NUM_ATTENTION_HEADS=16
+ GLOBAL_BATCH_SIZE=32
+ ;;
+ "8B")
+ TENSOR_MODEL_PARALLEL_SIZE=4
+ HYBRID_LAYER_PATTERN="M-M-M--M-M*-M-M-M-M--M*-M-M-M-M-M*--M-M-M-M-M*-M--M-M-M-"
+ HIDDEN_SIZE=4096
+ NUM_ATTENTION_HEADS=32
+ GLOBAL_BATCH_SIZE=8
+ ;;
+ *)
+ echo "Invalid version specified"
+ exit 1
+ ;;
+esac
+
+DATA_PATH=$1
+TOKENIZER_PATH=$2
+
+export NCCL_IB_SL=1
+export CUDA_DEVICE_MAX_CONNECTIONS=1
+export NCCL_IB_TIMEOUT=19
+export NCCL_IB_QPS_PER_CONNECTION=4
+
+CHECKPOINT_DIR="./checkpoints"
+DATACACHE_DIR="./data-cache"
+TENSORBOARD_DIR="./tensorboard"
+
+mkdir -p ${CHECKPOINT_DIR}
+mkdir -p ${DATACACHE_DIR}
+mkdir -p ${TENSORBOARD_DIR}
+
+export TRITON_CACHE_DIR="./triton-cache/"
+export TRITON_CACHE_MANAGER="megatron.core.ssm.triton_cache_manager:ParallelFileCacheManager"
+
+SEQ_LEN=4096
+TRAIN_SAMPLES=73242188 # 300B tokens / 4096
+LR_WARMUP_SAMPLES=50000
+LR_DECAY_SAMPLES=73192188 # TRAIN_SAMPLES - LR_WARMUP_SAMPLES
+
+options=" \
+ --tensor-model-parallel-size ${TENSOR_MODEL_PARALLEL_SIZE} \
+ --sequence-parallel \
+ --pipeline-model-parallel-size 1 \
+ --use-distributed-optimizer \
+ --overlap-param-gather \
+ --overlap-grad-reduce \
+ --untie-embeddings-and-output-weights \
+ --init-method-std 0.02 \
+ --position-embedding-type none \
+ --hybrid-layer-pattern ${HYBRID_LAYER_PATTERN} \
+ --hidden-size ${HIDDEN_SIZE} \
+ --num-attention-heads ${NUM_ATTENTION_HEADS} \
+ --group-query-attention \
+ --num-query-groups 8 \
+ --seq-length ${SEQ_LEN} \
+ --max-position-embeddings ${SEQ_LEN} \
+ --train-samples ${TRAIN_SAMPLES} \
+ --lr-warmup-samples ${LR_WARMUP_SAMPLES} \
+ --lr-decay-samples ${LR_DECAY_SAMPLES} \
+ --save ${CHECKPOINT_DIR} \
+ --load ${CHECKPOINT_DIR} \
+ --data-path ${DATA_PATH} \
+ --data-cache-path ${DATACACHE_DIR} \
+ --split 99,1,0 \
+ --tokenizer-type GPTSentencePieceTokenizer \
+ --tokenizer-model ${TOKENIZER_PATH} \
+ --distributed-backend nccl \
+ --micro-batch-size 4 \
+ --global-batch-size ${GLOBAL_BATCH_SIZE} \
+ --lr 2.5e-4 \
+ --min-lr 2.5e-5 \
+ --lr-decay-style cosine \
+ --weight-decay 0.1 \
+ --clip-grad 1.0 \
+ --attention-dropout 0.0 \
+ --hidden-dropout 0.0 \
+ --disable-bias-linear \
+ --normalization RMSNorm \
+ --adam-beta1 0.9 \
+ --adam-beta2 0.95 \
+ --log-interval 10 \
+ --save-interval 2000 \
+ --eval-interval 2000 \
+ --eval-iters 32 \
+ --bf16 \
+ --use-mcore-models \
+ --spec megatron.core.models.mamba.mamba_layer_specs mamba_stack_spec \
+ --no-create-attention-mask-in-dataloader \
+ --tensorboard-dir ${TENSORBOARD_DIR}"
+
+torchrun --nproc_per_node 8 ../../pretrain_mamba.py ${options}
diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/__init__.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0519ecba6ea913e21689ec692e81e9e4973fbf73
--- /dev/null
+++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/__init__.py
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/avlm_inference.py b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/avlm_inference.py
new file mode 100644
index 0000000000000000000000000000000000000000..14ca2068cacf69cee82599635631148fcb7a4ea5
--- /dev/null
+++ b/tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/avlm_inference.py
@@ -0,0 +1,244 @@
+import argparse
+import os
+from pathlib import Path
+from typing import Union
+
+# hf path
+import requests
+import torch
+from PIL import Image
+from transformers import AutoProcessor
+from transformers import AutoTokenizer
+import soundfile as sf
+import io
+import numpy as np
+import scipy.signal as signal
+
+from examples.mimo.model_providers.llava_avlm import model_provider_llava_avlm
+from megatron.core import dist_checkpointing, parallel_state, tensor_parallel
+from megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seed
+from megatron.training import print_rank_0
+from examples.mimo.data.utils.calculate_audio_tokens import calculate_num_audio_tokens
+
+def init_distributed(tp_size: int = 1, pp_size: int = 1):
+ if torch.distributed.is_initialized():
+ return
+ rank = int(os.environ.get("LOCAL_RANK", 0))
+ world_size = int(os.environ.get("WORLD_SIZE", 1))
+ torch.cuda.set_device(rank % torch.cuda.device_count())
+ torch.distributed.init_process_group("nccl", rank=rank, world_size=world_size)
+ parallel_state.initialize_model_parallel(tp_size, pp_size)
+
+def get_input_data(
+ processor: AutoProcessor,
+ image_processor: AutoProcessor,
+ audio_processor: AutoProcessor,
+ audio_path: str,
+ image_path: str,
+ prompt: str,
+ device: Union[int, str] = 0):
+ """
+ Prepare inputs for the MIMO model forward pass.
+ """
+
+ def read_audio(audio_path):
+ """Process audio file and return tensor."""
+ with open(audio_path, 'rb') as f:
+ audio_bytes = f.read()
+ audio_io = io.BytesIO(audio_bytes)
+ waveform, sample_rate = sf.read(audio_io)
+
+ # Resample if needed
+ fixed_sample_rate = 16000
+ if sample_rate != fixed_sample_rate:
+ num_samples = int(len(waveform) * fixed_sample_rate / sample_rate)
+ waveform = signal.resample(waveform, num_samples)
+
+ # Convert to tensor
+ audio_tensor = torch.from_numpy(waveform).float()
+ return audio_tensor
+
+ def read_image(image_path):
+ """Process image file and return tensor."""
+ with open(image_path, 'rb') as f:
+ image_bytes = f.read()
+ image_io = io.BytesIO(image_bytes)
+ image = Image.open(image_io)
+ image_tensor = torch.from_numpy(np.array(image)).permute(2, 0, 1) # Convert to CxHxW format
+ image_tensor = image_tensor.float() / 255.0 # rescale to [0,1] range
+ return image_tensor
+
+
+ # read audio and image
+ audio_tensor = read_audio(audio_path)
+ image_tensor = read_image(image_path)
+
+ # set up prompt
+ conversation = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": prompt},
+ ],
+ }
+ ]
+ prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
+
+ # process audio
+ processed_audios = audio_processor(audio_tensor, sampling_rate=16000)
+ processed_audios = torch.tensor(processed_audios["input_features"])
+ processed_audios = processed_audios.squeeze(0) # remove batch dim
+ num_audio_tokens = calculate_num_audio_tokens(audio_tensor.unsqueeze(0), "openai/whisper-base")
+ audios_seq_lengths = torch.tensor(num_audio_tokens)
+ prompt = prompt.replace("