hyttyh111222333 commited on
Commit
f490c49
·
verified ·
1 Parent(s): 9812906

Upload FAI-Bench task files batch 63

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/examples/gptoss/01_convert_from_hf.py +55 -0
  2. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/gptoss/02_train.sh +259 -0
  3. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/gptoss/03_convert_to_hf.py +52 -0
  4. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/gptoss/README.md +153 -0
  5. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/.gitignore +4 -0
  6. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/Dockerfile +32 -0
  7. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/README.md +117 -0
  8. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/run_text_gen_server_8b.sh +50 -0
  9. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/run_text_gen_server_8b_gpt3.sh +46 -0
  10. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/train.sh +103 -0
  11. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/__init__.py +1 -0
  12. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/avlm_inference.py +244 -0
  13. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/configs/llava_avlm.py +59 -0
  14. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/configs/llava_vlm.py +116 -0
  15. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/configs/mock.py +130 -0
  16. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/data/__init__.py +5 -0
  17. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/data/avlm_sample_loader.py +86 -0
  18. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/data/energon_avlm_task_encoder.py +484 -0
  19. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/data/energon_vlm_task_encoder.py +654 -0
  20. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/data/mock.py +296 -0
  21. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/data/prepare_video_llava_data.py +106 -0
  22. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/data/utils/calculate_audio_tokens.py +65 -0
  23. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/model_providers/__init__.py +1 -0
  24. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/model_providers/hf_clip_encoder.py +48 -0
  25. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/model_providers/hf_whisper_encoder.py +27 -0
  26. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/model_providers/llava_avlm.py +187 -0
  27. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/model_providers/llava_vlm.py +155 -0
  28. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/model_providers/mock.py +102 -0
  29. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/scripts/run_avlm_train.sh +149 -0
  30. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/scripts/run_mock_train.sh +109 -0
  31. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/scripts/run_video_vlm_train.sh +140 -0
  32. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/scripts/run_vlm_train.sh +151 -0
  33. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/train.py +285 -0
  34. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/utils/__init__.py +1 -0
  35. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/utils/data_helpers.py +82 -0
  36. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/utils/logging.py +50 -0
  37. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/utils/model_helpers.py +37 -0
  38. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mixtral/README.md +132 -0
  39. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mixtral/train_mixtral_8x7b_distributed.sh +116 -0
  40. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/Dockerfile +62 -0
  41. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/README.md +161 -0
  42. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/combine_lm_vision_checkpoints.sh +57 -0
  43. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/combine_state_dicts.py +81 -0
  44. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/config.py +412 -0
  45. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/convert_llava_pretrain_to_wds.py +31 -0
  46. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/dataloader_provider.py +171 -0
  47. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/dataset_helpers.py +966 -0
  48. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/energon_util.py +31 -0
  49. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/evaluation/evaluate_ai2d.py +52 -0
  50. tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/evaluation/evaluate_coco.py +67 -0
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/gptoss/01_convert_from_hf.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+
3
+ """Convert HuggingFace checkpoints to Megatron format."""
4
+
5
+ import os
6
+ import argparse
7
+
8
+ from megatron.bridge import AutoBridge
9
+
10
+ def _parse_args():
11
+ parser = argparse.ArgumentParser(description="Convert HF LLMs to Megatron format")
12
+ parser.add_argument(
13
+ "--hf-model",
14
+ type=str,
15
+ required=True,
16
+ help="HuggingFace model identifier or path",
17
+ )
18
+ parser.add_argument(
19
+ "--save-path",
20
+ type=str,
21
+ default=None,
22
+ help="Path to save the converted Megatron checkpoint",
23
+ )
24
+ parser.add_argument('--local-rank', '--local_rank', type=int, default=0)
25
+ return parser.parse_args()
26
+
27
+ if __name__ == "__main__":
28
+ args = _parse_args()
29
+ HF_MODEL = args.hf_model
30
+ SAVE_PATH = args.save_path
31
+ WORLD_SIZE = int(os.environ.get("WORLD_SIZE", 1))
32
+
33
+ if SAVE_PATH is None:
34
+ SAVE_PATH = f"./megatron_checkpoints/{HF_MODEL.replace('/', '_')}"
35
+
36
+ print(f"Converting {HF_MODEL} to Megatron format...")
37
+ print(f"Save path: {SAVE_PATH}")
38
+
39
+ bridge = AutoBridge.from_hf_pretrained(HF_MODEL, trust_remote_code=True)
40
+ provider = bridge.to_megatron_provider()
41
+ # Update these configs as needed
42
+ provider.expert_tensor_parallel_size = 1
43
+ provider.tensor_model_parallel_size = 1
44
+ provider.pipeline_model_parallel_size = WORLD_SIZE
45
+ provider.finalize()
46
+
47
+ model = provider.provide_distributed_model(wrap_with_ddp=False)
48
+
49
+ bridge.save_megatron_model(
50
+ model,
51
+ SAVE_PATH,
52
+ hf_tokenizer_path=HF_MODEL
53
+ )
54
+
55
+ print(f"Saved Megatron checkpoint to {SAVE_PATH}")
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/gptoss/02_train.sh ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ export CUDA_DEVICE_MAX_CONNECTIONS=${CUDA_DEVICE_MAX_CONNECTIONS:-1}
4
+
5
+
6
+ # Setup arguments with defaults
7
+ CHECKPOINT_PATH="NO_VALUE_PROVIDED"
8
+ TENSORBOARD_LOGS_PATH="./tensorboard_logs/"
9
+ TOKENIZER_ARG="MOCK"
10
+ DATA_ARG="MOCK"
11
+ DISTRIBUTED_CONFIG_FILE=""
12
+
13
+ # Parse command line arguments
14
+ while [[ $# -gt 0 ]]; do
15
+ case $1 in
16
+ --checkpoint-path)
17
+ CHECKPOINT_PATH="$2"
18
+ shift 2
19
+ ;;
20
+ --tensorboard-logs-path)
21
+ TENSORBOARD_LOGS_PATH="$2"
22
+ shift 2
23
+ ;;
24
+ --tokenizer)
25
+ TOKENIZER_ARG="$2"
26
+ shift 2
27
+ ;;
28
+ --data)
29
+ DATA_ARG="$2"
30
+ shift 2
31
+ ;;
32
+ --distributed-config-file)
33
+ DISTRIBUTED_CONFIG_FILE="$2"
34
+ shift 2
35
+ ;;
36
+ -h|--help)
37
+ echo "Usage: $0 [OPTIONS]"
38
+ echo "Options:"
39
+ echo " --checkpoint-path PATH Path to Megatron checkpoint"
40
+ echo " --tensorboard-logs-path PATH Path to TensorBoard logs"
41
+ echo " --tokenizer PATH|MOCK Path to tokenizer model, or 'MOCK' (default: MOCK)"
42
+ echo " --data PATH|MOCK Data prefix, or 'MOCK' (default: MOCK)"
43
+ echo " --distributed-config-file FILE Path to distributed training config file"
44
+ echo " -h, --help Show this help message"
45
+ exit 0
46
+ ;;
47
+ *)
48
+ echo "Unknown option: $1"
49
+ echo "Use --help for usage information"
50
+ exit 1
51
+ ;;
52
+ esac
53
+ done
54
+
55
+ # Check if checkpoint path exists
56
+ if [ ! -d "$CHECKPOINT_PATH" ]; then
57
+ echo "Error: Checkpoint path does not exist: $CHECKPOINT_PATH"
58
+ exit 1
59
+ fi
60
+ echo "Checkpoint path exists: $CHECKPOINT_PATH"
61
+
62
+ # Check if tensorboard logs path exists
63
+ if [ ! -d "$TENSORBOARD_LOGS_PATH" ]; then
64
+ echo "Warning: TensorBoard logs path does not exist. Creating: $TENSORBOARD_LOGS_PATH"
65
+ mkdir -p "$TENSORBOARD_LOGS_PATH"
66
+ fi
67
+ echo "TensorBoard logs path exists: $TENSORBOARD_LOGS_PATH"
68
+
69
+ # NOTE: by default we use 8 GPUs
70
+ # These values will be over-written below with environmental variables
71
+ GPUS_PER_NODE=8
72
+ NUM_NODES=1
73
+ MASTER_ADDR="localhost"
74
+ MASTER_PORT=6000
75
+ NODE_RANK=0
76
+
77
+ # Load distributed config from file if provided
78
+ if [ -n "$DISTRIBUTED_CONFIG_FILE" ]; then
79
+ if [ ! -f "$DISTRIBUTED_CONFIG_FILE" ]; then
80
+ echo "Warning: Distributed config file does not exist: $DISTRIBUTED_CONFIG_FILE"
81
+ echo "Continuing with default distributed training settings."
82
+ else
83
+ echo "Loading distributed config from: $DISTRIBUTED_CONFIG_FILE"
84
+ source "$DISTRIBUTED_CONFIG_FILE"
85
+ fi
86
+ fi
87
+
88
+ # Override with environment variables if set
89
+ GPUS_PER_NODE=${GPUS_PER_NODE:-8}
90
+ NUM_NODES=${NUM_NODES:-1}
91
+ MASTER_ADDR=${MASTER_ADDR:-localhost}
92
+ MASTER_PORT=${MASTER_PORT:-6000}
93
+ NODE_RANK=${NODE_RANK:-0}
94
+ WORLD_SIZE=$(($GPUS_PER_NODE*$NUM_NODES))
95
+
96
+ # Path to the pretrain_gpt.py script, assuming this script is run from the root of the Megatron-LM repository
97
+ PRETRAIN_SCRIPT_PATH="pretrain_gpt.py"
98
+
99
+ # Data cache path (useful for both mock and real data)
100
+ DATA_CACHE_PATH="${PWD}/benchmark_cache_gpt_oss_20b"
101
+ mkdir -p "$DATA_CACHE_PATH"
102
+
103
+ DISTRIBUTED_ARGS=(
104
+ --nproc_per_node $GPUS_PER_NODE
105
+ --nnodes $NUM_NODES
106
+ --master_addr $MASTER_ADDR
107
+ --master_port $MASTER_PORT
108
+ --node_rank $NODE_RANK
109
+ )
110
+
111
+ # NOTE: we only set pipeline parallelism to be the number of GPUs
112
+ # Adjust each value based on your setup.
113
+ TP_SIZE=1
114
+ EP_SIZE=1
115
+ PP_SIZE=${WORLD_SIZE}
116
+ MICRO_BATCH_SIZE=1
117
+ GLOBAL_BATCH_SIZE=128
118
+ NUM_LAYERS=12
119
+ DTYPE="fp8"
120
+ SEQ_LENGTH=8192
121
+ MAX_POSITION_EMBEDDINGS=8192
122
+ TRAIN_SAMPLES=1953125000
123
+ LR_DECAY_SAMPLES=1949218748
124
+
125
+ MODEL_ARGS=(
126
+ --no-masked-softmax-fusion
127
+ --transformer-impl transformer_engine
128
+ --disable-bias-linear
129
+ --untie-embeddings-and-output-weights
130
+ --no-rope-fusion
131
+ --normalization RMSNorm
132
+ --num-layers ${NUM_LAYERS}
133
+ --hidden-size 512
134
+ --ffn-hidden-size 2048
135
+ --num-attention-heads 64
136
+ --group-query-attention
137
+ --num-query-groups 8
138
+ --seq-length ${SEQ_LENGTH}
139
+ --max-position-embeddings ${MAX_POSITION_EMBEDDINGS}
140
+ --use-mcore-models
141
+ --rotary-percent 1.0
142
+ --rope-type rope
143
+ --position-embedding-type rope
144
+ --rotary-base 10000
145
+ --no-bias-gelu-fusion
146
+ --export-force-local-attention
147
+ --no-bias-dropout-fusion
148
+ --quick-geglu
149
+ --glu-linear-offset 1.0
150
+ --softmax-type learnable
151
+ --window-attn-skip-freq 2
152
+ --activation-func-clamp-value 7.0
153
+ --window-size 127,0
154
+ --enable-gpt-oss
155
+ )
156
+
157
+ MOE_ARGS=(
158
+ --num-experts 4
159
+ --moe-router-topk 2
160
+ --moe-router-load-balancing-type aux_loss
161
+ --moe-aux-loss-coeff 1e-3
162
+ --moe-grouped-gemm
163
+ --moe-token-dispatcher-type alltoall
164
+ --overlap-param-gather
165
+ --overlap-grad-reduce
166
+ --moe-ffn-hidden-size 2048
167
+ --moe-router-dtype fp32
168
+ --moe-z-loss-coeff 1e-3
169
+ --moe-permute-fusion
170
+ )
171
+
172
+ DATA_ARGS_LIST=()
173
+ if [[ "$TOKENIZER_ARG" == "MOCK" ]] || [[ "$DATA_ARG" == "MOCK" ]] || [[ -z "$TOKENIZER_ARG" ]]; then
174
+ DATA_ARGS_LIST+=(
175
+ "--mock-data"
176
+ "--tokenizer-type NullTokenizer"
177
+ "--vocab-size 128256"
178
+ "--data-cache-path ${DATA_CACHE_PATH}"
179
+ "--tiktoken-pattern v2"
180
+ "--split '99,1,0'"
181
+ "--no-create-attention-mask-in-dataloader"
182
+ "--no-mmap-bin-files"
183
+ "--num-workers 1"
184
+ )
185
+ else
186
+ # Settings for real data
187
+ DATA_ARGS_LIST+=(
188
+ "--data-path $DATA_ARG"
189
+ "--tokenizer-type HuggingFaceTokenizer"
190
+ "--tokenizer-model $TOKENIZER_ARG"
191
+ "--data-cache-path ${DATA_CACHE_PATH}"
192
+ "--split '99,1,0'"
193
+ "--no-create-attention-mask-in-dataloader"
194
+ "--no-mmap-bin-files"
195
+ "--num-workers 1"
196
+ # Note: --vocab-size might be inferred by HuggingFaceTokenizer or might need to be explicit.
197
+ "--vocab-size 128256"
198
+ )
199
+ fi
200
+
201
+ TRAINING_ARGS=(
202
+ --micro-batch-size ${MICRO_BATCH_SIZE}
203
+ --global-batch-size ${GLOBAL_BATCH_SIZE}
204
+ --lr 1.0e-5
205
+ --train-samples ${TRAIN_SAMPLES}
206
+ --lr-decay-samples ${LR_DECAY_SAMPLES}
207
+ --lr-decay-style cosine
208
+ --min-lr 1.0e-6
209
+ --weight-decay 0.1
210
+ --lr-warmup-fraction 0.05
211
+ --clip-grad 1.0
212
+ --bf16
213
+ --use-flash-attn
214
+ --attention-softmax-in-fp32
215
+ --accumulate-allreduce-grads-in-fp32
216
+ --disable-bf16-reduced-precision-matmul
217
+ --recompute-activations
218
+ )
219
+
220
+ MODEL_PARALLEL_ARGS=(
221
+ --tensor-model-parallel-size ${TP_SIZE}
222
+ --pipeline-model-parallel-size ${PP_SIZE}
223
+ --expert-model-parallel-size ${EP_SIZE}
224
+ --sequence-parallel
225
+ --context-parallel-size 1
226
+ --use-distributed-optimizer
227
+ --fp8-format hybrid
228
+ --fp8-param-gather
229
+ --fp8-amax-compute-algo max
230
+ --fp8-amax-history-len 1024
231
+ )
232
+
233
+ LOGGING_ARGS=(
234
+ --log-interval 1
235
+ --save-interval 10000
236
+ --eval-interval 50000000
237
+ --eval-iters 0
238
+ --save $CHECKPOINT_PATH
239
+ --tensorboard-dir "${CHECKPOINT_PATH}/tensorboard"
240
+ --moe-per-layer-logging
241
+ --no-load-optim
242
+ --no-load-rng
243
+ --log-throughput
244
+ )
245
+
246
+ # Ensure pretrain_gpt.py is found
247
+ if [ ! -f "$PRETRAIN_SCRIPT_PATH" ]; then
248
+ echo "Error: pretrain_gpt.py not found at $PRETRAIN_SCRIPT_PATH"
249
+ echo "Please ensure you are running this script from the root of the Megatron-LM repository, and pretrain_gpt.py is present."
250
+ exit 1
251
+ fi
252
+
253
+ python -m torch.distributed.run ${DISTRIBUTED_ARGS[@]} ${PRETRAIN_SCRIPT_PATH} \
254
+ ${MODEL_ARGS[@]} \
255
+ ${MOE_ARGS[@]} \
256
+ ${DATA_ARGS_LIST[@]} \
257
+ ${TRAINING_ARGS[@]} \
258
+ ${MODEL_PARALLEL_ARGS[@]} \
259
+ ${LOGGING_ARGS[@]}
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/gptoss/03_convert_to_hf.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+
3
+ """Convert HuggingFace checkpoints to Megatron format."""
4
+
5
+ import os
6
+ import argparse
7
+
8
+ from megatron.bridge import AutoBridge
9
+
10
+ def _parse_args():
11
+ parser = argparse.ArgumentParser(description="Convert Megatron LLMs to HuggingFace format")
12
+ parser.add_argument(
13
+ "--hf-model",
14
+ type=str,
15
+ required=True,
16
+ help="HuggingFace model identifier or path to load config from",
17
+ )
18
+ parser.add_argument(
19
+ "--megatron-model",
20
+ type=str,
21
+ required=True,
22
+ help="Megatron model identifier or path",
23
+ )
24
+ parser.add_argument(
25
+ "--save-path",
26
+ type=str,
27
+ default=None,
28
+ help="Path to save the converted HuggingFace checkpoint",
29
+ )
30
+ parser.add_argument('--local-rank', '--local_rank', type=int, default=0)
31
+ return parser.parse_args()
32
+
33
+ if __name__ == "__main__":
34
+ args = _parse_args()
35
+ HF_MODEL = args.hf_model
36
+ MEGATRON_MODEL = args.megatron_model
37
+ SAVE_PATH = args.save_path
38
+ WORLD_SIZE = int(os.environ.get("WORLD_SIZE", 1))
39
+
40
+ if SAVE_PATH is None:
41
+ SAVE_PATH = f"./huggingface_checkpoints/{MEGATRON_MODEL.replace('/', '_')}"
42
+
43
+ print(f"Converting {MEGATRON_MODEL} to HuggingFace {HF_MODEL} format...")
44
+ print(f"Save path: {SAVE_PATH}")
45
+
46
+ bridge = AutoBridge.from_hf_pretrained(HF_MODEL, trust_remote_code=True)
47
+ bridge.export_ckpt(
48
+ MEGATRON_MODEL,
49
+ SAVE_PATH,
50
+ )
51
+
52
+ print(f"Saved HuggingFace checkpoint to {SAVE_PATH}")
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/gptoss/README.md ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GPT-OSS Training Tutorial
2
+
3
+ ## Step 0: Install Dependencies
4
+
5
+ ### Using Megatron Bridge
6
+
7
+ [Megatron-Bridge](https://github.com/NVIDIA-NeMo/Megatron-Bridge)
8
+
9
+ 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).
10
+
11
+ Below is an example of how to use Megatron-Bridge inside the pytorch container to convert a HuggingFace model checkpoint to Megatron format.
12
+
13
+ Reference: [Megatron-Bridge Dockerfile](https://github.com/NVIDIA-NeMo/Megatron-Bridge/blob/main/docker/Dockerfile.ci)
14
+
15
+ Inside the [pytorch container](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/pytorch) run the following commands to install Megatron-Bridge:
16
+ ```bash
17
+ cd /opt
18
+ git clone --recursive https://github.com/NVIDIA-NeMo/Megatron-Bridge.git
19
+ cd Megatron-Bridge
20
+
21
+ # Make sure submodules are initialized (for 3rdparty/Megatron-LM)
22
+ git submodule update --init --recursive
23
+
24
+ export PATH="/root/.local/bin:$PATH"
25
+ export UV_PROJECT_ENVIRONMENT=/opt/venv
26
+ export VIRTUAL_ENV=/opt/venv
27
+ export PATH="$UV_PROJECT_ENVIRONMENT/bin:$PATH"
28
+ export UV_LINK_MODE=copy
29
+ export UV_VERSION="0.7.2"
30
+
31
+ # Install UV
32
+ curl -LsSf https://astral.sh/uv/${UV_VERSION}/install.sh | sh
33
+
34
+ # Create virtual environment and build the package
35
+ uv venv ${UV_PROJECT_ENVIRONMENT} --system-site-packages
36
+
37
+ uv sync --locked --only-group build
38
+ uv sync --locked --link-mode copy --all-extras --all-groups
39
+
40
+ uv pip install --no-deps -e .
41
+
42
+ source ${UV_PROJECT_ENVIRONMENT}/bin/activate
43
+ ```
44
+
45
+ ### Setup Environment
46
+
47
+ ```bash
48
+ export HOST_MEGATRON_LM_DIR="/path/to/your/host/megatron-lm"
49
+ git clone https://github.com/NVIDIA/Megatron-LM.git "$HOST_MEGATRON_LM_DIR"
50
+ cd "$HOST_MEGATRON_LM_DIR"
51
+ ```
52
+
53
+ ```bash
54
+ export HF_TOKEN={your_hf_token_here}
55
+ ```
56
+
57
+ ## Step 1: Convert HuggingFace to Megatron (Optional - skip if you already have a Megatron checkpoint)
58
+
59
+ 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`
60
+
61
+ ```bash
62
+ python3 -m torch.distributed.launch --nproc-per-node=8 examples/gptoss/01_convert_from_hf.py --hf-model openai/gpt-oss-20b
63
+ ```
64
+
65
+ ## Step 2: Train from Scratch
66
+
67
+ 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.
68
+
69
+ ### Setup Environment
70
+
71
+ ```bash
72
+ # Change these based on model and directory from previous conversion step
73
+ export MODEL_DIR_NAME="openai_gpt-oss_20b"
74
+
75
+ export HOST_CHECKPOINT_PATH="./megatron_checkpoints/${MODEL_DIR_NAME}"
76
+ export HOST_TENSORBOARD_LOGS_PATH="./tensorboard_logs/${MODEL_DIR_NAME}"
77
+ ```
78
+
79
+ 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:
80
+
81
+ ```bash
82
+ # Optional: For real data
83
+ export HOST_TOKENIZER_MODEL_PATH="/path/to/host/tokenizer.model"
84
+ export HOST_DATA_PREFIX="/path/to/host/mydata_prefix"
85
+ ```
86
+
87
+ ### Setup Training Configurations
88
+
89
+ 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`.
90
+
91
+ ```bash
92
+ cat > ./distributed_config.env << 'EOF'
93
+ GPUS_PER_NODE=8
94
+ NUM_NODES=1
95
+ MASTER_ADDR=localhost
96
+ MASTER_PORT=6000
97
+ NODE_RANK=0
98
+ EOF
99
+ ```
100
+
101
+ ### Run Container with Mounted Volumes
102
+
103
+ **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.
104
+
105
+ To train using mock data, run the following command:
106
+ ```bash
107
+ PYTORCH_IMAGE="nvcr.io/nvidia/pytorch:25.12-py3"
108
+
109
+ docker run --rm --gpus all --ipc=host --ulimit memlock=-1 \
110
+ -v "${HOST_MEGATRON_LM_DIR}:/workspace/megatron-lm" \
111
+ -v "${HOST_CHECKPOINT_PATH}:/workspace/checkpoints" \
112
+ -v "${HOST_TENSORBOARD_LOGS_PATH}:/workspace/tensorboard_logs" \
113
+ -v "./distributed_config.env:/workspace/megatron-lm/examples/gptoss/distributed_config.env" \
114
+ --workdir /workspace/megatron-lm \
115
+ $PYTORCH_IMAGE \
116
+ bash examples/gptoss/02_train.sh \
117
+ --checkpoint-path /workspace/checkpoints \
118
+ --tensorboard-logs-path /workspace/tensorboard_logs \
119
+ --distributed-config-file /workspace/megatron-lm/examples/gptoss/distributed_config.env \
120
+ 2>&1 | tee "${HOST_TENSORBOARD_LOGS_PATH}/training_mock_$(date +'%y-%m-%d_%H-%M-%S').log"
121
+ ```
122
+ **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.
123
+
124
+ If using real data with with the `HOST_TOKENIZER_MODEL_PATH` and `HOST_DATA_PREFIX` environment variables set, run the following command instead:
125
+
126
+ ```bash
127
+ PYTORCH_IMAGE="nvcr.io/nvidia/pytorch:25.12-py3"
128
+
129
+ docker run --rm --gpus all --ipc=host --ulimit memlock=-1 \
130
+ -v "${HOST_MEGATRON_LM_DIR}:/workspace/megatron-lm" \
131
+ -v "${HOST_CHECKPOINT_PATH}:/workspace/checkpoints" \
132
+ -v "${HOST_TENSORBOARD_LOGS_PATH}:/workspace/tensorboard_logs" \
133
+ -v "${HOST_TOKENIZER_MODEL_PATH}:/workspace/tokenizer_model" \
134
+ -v "$(dirname "${HOST_DATA_PREFIX}"):/workspace/data_dir" \
135
+ -v "./distributed_config.env:/workspace/megatron-lm/examples/gptoss/distributed_config.env" \
136
+ --workdir /workspace/megatron-lm \
137
+ $PYTORCH_IMAGE \
138
+ bash examples/gptoss/02_train.sh \
139
+ --checkpoint-path /workspace/checkpoints \
140
+ --tensorboard-logs-path /workspace/tensorboard_logs \
141
+ --tokenizer /workspace/tokenizer_model \
142
+ --data "/workspace/data_dir/$(basename "${HOST_DATA_PREFIX}")" \
143
+ --distributed-config-file /workspace/megatron-lm/examples/gptoss/distributed_config.env \
144
+ 2>&1 | tee "${HOST_TENSORBOARD_LOGS_PATH}/training_custom_$(date +'%y-%m-%d_%H-%M-%S').log"
145
+ ```
146
+
147
+ ## Step 3: Convert Megatron to HuggingFace
148
+
149
+ 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):
150
+
151
+ ```bash
152
+ 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
153
+ ```
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ checkpoints/
2
+ data-cache/
3
+ tensorboard/
4
+ triton-cache/
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/Dockerfile ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM nvcr.io/nvidia/pytorch:24.01-py3
2
+
3
+ RUN pip uninstall -y triton && \
4
+ pip install triton==2.1.0 sentencepiece==0.1.99 flask-restful
5
+
6
+ # The causal-conv1d and mamba-ssm packages below are built from scratch here
7
+ # (which takes significant time) because there are no wheels available on PyPI
8
+ # for these relatively newer versions of the packages that are compatible with
9
+ # the older NGC-variant PyTorch version (e.g. version 2.2.0.dev231106) that we
10
+ # are using (in the NGC base container). Generally, if the package is not
11
+ # compatible with the PyTorch version, then it will generate a Python import
12
+ # error. The package authors tend to only release wheels for new versions of
13
+ # these pacakges which are compatible with the versions of regular PyTorch and
14
+ # NGC-variant PyTorch that are newer at the time of release. So, to use newer
15
+ # versions of these packages with relatively older versions of the NGC PyTorch
16
+ # container, we tend to have to build the packages from scratch.
17
+
18
+ RUN cd /tmp && \
19
+ git clone https://github.com/Dao-AILab/causal-conv1d.git && \
20
+ cd causal-conv1d && \
21
+ git checkout v1.2.2.post1 && \
22
+ CAUSAL_CONV1D_FORCE_BUILD=TRUE pip install . && \
23
+ cd .. && \
24
+ rm -rf causal-conv1d
25
+
26
+ RUN cd /tmp && \
27
+ git clone https://github.com/state-spaces/mamba.git && \
28
+ cd mamba && \
29
+ git checkout v2.0.3 && \
30
+ MAMBA_FORCE_BUILD=TRUE pip install . && \
31
+ cd .. && \
32
+ rm -rf mamba
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/README.md ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Mamba-based Language Models
2
+
3
+ ## Introduction
4
+
5
+ This document is an entrypoint into the code used for
6
+ <em>[An Empirical Study of Mamba-based Language Models](https://arxiv.org/abs/2406.07887)</em>.
7
+
8
+ We are releasing the parameters for some of the models described in that
9
+ technical report via
10
+ [HuggingFace](https://huggingface.co/collections/nvidia/ssms-666a362c5c3bb7e4a6bcfb9c).
11
+ The code in the `main` branch is no longer compatible with the `Mamba2-*`
12
+ checkpoints. You can load them using the
13
+ [fixed snapshot of the code used for the technical report](https://github.com/NVIDIA/Megatron-LM/tree/ssm/examples/mamba).
14
+
15
+ ## Installation
16
+
17
+ Create and run a Docker container using the [Dockerfile](./Dockerfile).
18
+
19
+ ```
20
+ docker build -t your_image_name:your_tag .
21
+ docker run --gpus all -it --rm \
22
+ -v /path/to/megatron:/workspace/megatron \
23
+ -v /path/to/dataset:/workspace/dataset \
24
+ -v /path/to/checkpoints:/workspace/checkpoints \
25
+ -w /workspace/megatron/examples/mamba \
26
+ your_image_name:your_tag
27
+ ```
28
+
29
+ ## Train
30
+
31
+ [`train.sh`](./train.sh) is an example pretraining script, showing how to run on
32
+ a single node. Select between 800M-scale and 8B-scale models by setting the
33
+ `MODEL_SCALE` variable. The 8B-scale hybrid model architecture is the same as
34
+ the one described in the technical report.
35
+
36
+ ## Text Generation
37
+
38
+ Use [`run_text_gen_server_8b.sh`](./run_text_gen_server_8b.sh) to start a text
39
+ generation server using an 8B hybrid checkpoint. This is configured to run the
40
+ 8B hybrid model described in the technical report, with tensor model parallel
41
+ set to 1.
42
+
43
+ The arguments in the script will need to be changed if using a checkpoint with a
44
+ different model parallel configuration or other differences, such as model
45
+ architecture. For example, to run the 8B pure Mamba-2 model, change
46
+ `--hybrid-layer-pattern` to use only `M` symbols (e.g., 56 `M`s for the 8B
47
+ model), or remove it entirely.
48
+
49
+ Use [`run_text_gen_server_8b_gpt3.sh`](./run_text_gen_server_8b_gpt3.sh) to start
50
+ a text generation server using the 8B reference Transformer checkpoint.
51
+
52
+ ## Checkpoint Formats
53
+
54
+ For inference, the model must be configured to match the checkpoint file used,
55
+ including the hybrid layer configuration and model parallel configuration.
56
+
57
+ If you need to convert a hybrid checkpoint file to a different tensor parallel
58
+ or pipeline parallel size, use
59
+ [the hybrid conversion script](../../tools/checkpoint/hybrid_conversion.py).
60
+ There is an example run command at the end of that file.
61
+
62
+ Before running that script, you will need to set `PYTHONPATH` to include the
63
+ root directory of your Megatron-LM repository clone.
64
+
65
+ ```
66
+ export PYTHONPATH=<path-to-megatron>:PYTHONPATH
67
+ ```
68
+
69
+ ## Hybrid Options
70
+
71
+ `--hybrid-layer-pattern PATTERN` specifies the layer type for every layer in
72
+ the model using a string of single-character symbols:
73
+
74
+ * `M` — Mamba layer
75
+ * `*` — Attention layer
76
+ * `-` — MLP layer
77
+ * `E` — MoE layer
78
+
79
+ The number of layers is derived from the pattern length, so `--num-layers`
80
+ should not be specified when `--hybrid-layer-pattern` is used.
81
+
82
+ For example, the 8B hybrid model described in the technical report uses:
83
+
84
+ ```
85
+ --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-"
86
+ ```
87
+
88
+ This is a 56-layer model with 4 attention layers, 28 MLP layers, and 24 Mamba
89
+ layers.
90
+
91
+ A pure Mamba model uses only `M` symbols (e.g., `MMMMMMMM` for 8 layers).
92
+ A pure transformer model uses only `*` and `-` symbols.
93
+
94
+ ### Pipeline parallelism
95
+
96
+ Use `|` to define pipeline stage boundaries for flexible virtual pipeline
97
+ parallelism (fVPP). For example, `M-M-|M-M*-|M-M-|M-M*-` defines 4 pipeline
98
+ segments. The number of segments must be evenly divisible by
99
+ `--pipeline-model-parallel-size`.
100
+
101
+ ### Multi-Token Prediction (MTP)
102
+
103
+ Use `/` to append MTP layer patterns. Each pattern after the separator
104
+ represents one MTP prediction depth. For example, `M*M*/MM/MM` has main
105
+ pattern `M*M*` with MTP pattern `MM` repeated for 2 depths.
106
+
107
+ ### Deprecated options
108
+
109
+ `--hybrid-override-pattern`, `--hybrid-attention-ratio`, and
110
+ `--hybrid-mlp-ratio` are deprecated. Use `--hybrid-layer-pattern` instead.
111
+
112
+ ## Mamba vs Mamba-2
113
+
114
+ This codebase currently only supports Mamba-2, and not the original version of
115
+ Mamba. However, the
116
+ [fixed snapshot of the code used for the technical report](https://github.com/NVIDIA/Megatron-LM/tree/ssm/examples/mamba)
117
+ can be configured to run the original version of Mamba.
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/run_text_gen_server_8b.sh ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Use: ./run_text_gen_server_8b.sh <checkpoint-path> <tokenizer-path>
4
+ # To launch the client: python ../../tools/text_generation_cli.py <URL-provided-by-server>
5
+
6
+ CHECKPOINT_PATH=$1
7
+ TOKENIZER_PATH=$2
8
+
9
+ 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-"
10
+
11
+ DISTRIBUTED_ARGS="--nproc_per_node 1 \
12
+ --nnodes 1 \
13
+ --node_rank 0 \
14
+ --master_addr localhost \
15
+ --master_port 6000"
16
+
17
+ export NCCL_IB_SL=1
18
+ export CUDA_DEVICE_MAX_CONNECTIONS=1
19
+ export NCCL_IB_TIMEOUT=19
20
+ export NCCL_IB_QPS_PER_CONNECTION=4
21
+
22
+ export TRITON_CACHE_DIR="./triton-cache/"
23
+ export TRITON_CACHE_MANAGER="megatron.core.ssm.triton_cache_manager:ParallelFileCacheManager"
24
+
25
+ torchrun $DISTRIBUTED_ARGS ../../tools/run_mamba_text_generation_server.py \
26
+ --tensor-model-parallel-size 1 \
27
+ --pipeline-model-parallel-size 1 \
28
+ --untie-embeddings-and-output-weights \
29
+ --hybrid-layer-pattern ${HYBRID_LAYER_PATTERN} \
30
+ --hidden-size 4096 \
31
+ --load ${CHECKPOINT_PATH} \
32
+ --num-attention-heads 32 \
33
+ --group-query-attention \
34
+ --num-query-groups 8 \
35
+ --attention-dropout 0.0 \
36
+ --hidden-dropout 0.0 \
37
+ --disable-bias-linear \
38
+ --normalization RMSNorm \
39
+ --seq-length 4096 \
40
+ --max-position-embeddings 4096 \
41
+ --position-embedding-type none \
42
+ --tokenizer-type GPTSentencePieceTokenizer \
43
+ --tokenizer-model ${TOKENIZER_PATH} \
44
+ --distributed-backend nccl \
45
+ --distributed-timeout-minutes 1440 \
46
+ --bf16 \
47
+ --micro-batch-size 1 \
48
+ --use-mcore-models \
49
+ --spec megatron.core.models.mamba.mamba_layer_specs mamba_stack_spec \
50
+ --seed 42
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/run_text_gen_server_8b_gpt3.sh ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Use: ./run_text_gen_server_8b_gpt3.sh <checkpoint-path> <tokenizer-path>
4
+ # To launch the client: python ../../tools/text_generation_cli.py <URL-provided-by-server>
5
+
6
+ CHECKPOINT_PATH=$1
7
+ TOKENIZER_PATH=$2
8
+
9
+ DISTRIBUTED_ARGS="--nproc_per_node 1 \
10
+ --nnodes 1 \
11
+ --node_rank 0 \
12
+ --master_addr localhost \
13
+ --master_port 6000"
14
+
15
+ export NCCL_IB_SL=1
16
+ export CUDA_DEVICE_MAX_CONNECTIONS=1
17
+ export NCCL_IB_TIMEOUT=19
18
+ export NCCL_IB_QPS_PER_CONNECTION=4
19
+
20
+ torchrun $DISTRIBUTED_ARGS ../../tools/run_text_generation_server.py \
21
+ --tensor-model-parallel-size 1 \
22
+ --pipeline-model-parallel-size 1 \
23
+ --use-flash-attn \
24
+ --apply-layernorm-1p \
25
+ --untie-embeddings-and-output-weights \
26
+ --num-layers 32 \
27
+ --hidden-size 4096 \
28
+ --load ${CHECKPOINT_PATH} \
29
+ --num-attention-heads 32 \
30
+ --attention-dropout 0.0 \
31
+ --hidden-dropout 0.0 \
32
+ --disable-bias-linear \
33
+ --seq-length 4096 \
34
+ --max-position-embeddings 4096 \
35
+ --position-embedding-type rope \
36
+ --rotary-percent 0.5 \
37
+ --squared-relu \
38
+ --tokenizer-type GPTSentencePieceTokenizer \
39
+ --tokenizer-model ${TOKENIZER_PATH} \
40
+ --distributed-backend nccl \
41
+ --distributed-timeout-minutes 1440 \
42
+ --bf16 \
43
+ --micro-batch-size 1 \
44
+ --use-mcore-models \
45
+ --transformer-impl local \
46
+ --seed 42
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mamba/train.sh ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Use: ./train.sh <data-path> <tokenizer-path>
4
+
5
+ MODEL_SCALE="800M" # or "8B"
6
+
7
+ case "${MODEL_SCALE}" in
8
+ "800M")
9
+ TENSOR_MODEL_PARALLEL_SIZE=1
10
+ HYBRID_LAYER_PATTERN="M-M-M--M-*M-M-M-M--*M-M-M-M-*M--M-M-M-*M-M--M-M-"
11
+ HIDDEN_SIZE=1024
12
+ NUM_ATTENTION_HEADS=16
13
+ GLOBAL_BATCH_SIZE=32
14
+ ;;
15
+ "8B")
16
+ TENSOR_MODEL_PARALLEL_SIZE=4
17
+ 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-"
18
+ HIDDEN_SIZE=4096
19
+ NUM_ATTENTION_HEADS=32
20
+ GLOBAL_BATCH_SIZE=8
21
+ ;;
22
+ *)
23
+ echo "Invalid version specified"
24
+ exit 1
25
+ ;;
26
+ esac
27
+
28
+ DATA_PATH=$1
29
+ TOKENIZER_PATH=$2
30
+
31
+ export NCCL_IB_SL=1
32
+ export CUDA_DEVICE_MAX_CONNECTIONS=1
33
+ export NCCL_IB_TIMEOUT=19
34
+ export NCCL_IB_QPS_PER_CONNECTION=4
35
+
36
+ CHECKPOINT_DIR="./checkpoints"
37
+ DATACACHE_DIR="./data-cache"
38
+ TENSORBOARD_DIR="./tensorboard"
39
+
40
+ mkdir -p ${CHECKPOINT_DIR}
41
+ mkdir -p ${DATACACHE_DIR}
42
+ mkdir -p ${TENSORBOARD_DIR}
43
+
44
+ export TRITON_CACHE_DIR="./triton-cache/"
45
+ export TRITON_CACHE_MANAGER="megatron.core.ssm.triton_cache_manager:ParallelFileCacheManager"
46
+
47
+ SEQ_LEN=4096
48
+ TRAIN_SAMPLES=73242188 # 300B tokens / 4096
49
+ LR_WARMUP_SAMPLES=50000
50
+ LR_DECAY_SAMPLES=73192188 # TRAIN_SAMPLES - LR_WARMUP_SAMPLES
51
+
52
+ options=" \
53
+ --tensor-model-parallel-size ${TENSOR_MODEL_PARALLEL_SIZE} \
54
+ --sequence-parallel \
55
+ --pipeline-model-parallel-size 1 \
56
+ --use-distributed-optimizer \
57
+ --overlap-param-gather \
58
+ --overlap-grad-reduce \
59
+ --untie-embeddings-and-output-weights \
60
+ --init-method-std 0.02 \
61
+ --position-embedding-type none \
62
+ --hybrid-layer-pattern ${HYBRID_LAYER_PATTERN} \
63
+ --hidden-size ${HIDDEN_SIZE} \
64
+ --num-attention-heads ${NUM_ATTENTION_HEADS} \
65
+ --group-query-attention \
66
+ --num-query-groups 8 \
67
+ --seq-length ${SEQ_LEN} \
68
+ --max-position-embeddings ${SEQ_LEN} \
69
+ --train-samples ${TRAIN_SAMPLES} \
70
+ --lr-warmup-samples ${LR_WARMUP_SAMPLES} \
71
+ --lr-decay-samples ${LR_DECAY_SAMPLES} \
72
+ --save ${CHECKPOINT_DIR} \
73
+ --load ${CHECKPOINT_DIR} \
74
+ --data-path ${DATA_PATH} \
75
+ --data-cache-path ${DATACACHE_DIR} \
76
+ --split 99,1,0 \
77
+ --tokenizer-type GPTSentencePieceTokenizer \
78
+ --tokenizer-model ${TOKENIZER_PATH} \
79
+ --distributed-backend nccl \
80
+ --micro-batch-size 4 \
81
+ --global-batch-size ${GLOBAL_BATCH_SIZE} \
82
+ --lr 2.5e-4 \
83
+ --min-lr 2.5e-5 \
84
+ --lr-decay-style cosine \
85
+ --weight-decay 0.1 \
86
+ --clip-grad 1.0 \
87
+ --attention-dropout 0.0 \
88
+ --hidden-dropout 0.0 \
89
+ --disable-bias-linear \
90
+ --normalization RMSNorm \
91
+ --adam-beta1 0.9 \
92
+ --adam-beta2 0.95 \
93
+ --log-interval 10 \
94
+ --save-interval 2000 \
95
+ --eval-interval 2000 \
96
+ --eval-iters 32 \
97
+ --bf16 \
98
+ --use-mcore-models \
99
+ --spec megatron.core.models.mamba.mamba_layer_specs mamba_stack_spec \
100
+ --no-create-attention-mask-in-dataloader \
101
+ --tensorboard-dir ${TENSORBOARD_DIR}"
102
+
103
+ torchrun --nproc_per_node 8 ../../pretrain_mamba.py ${options}
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/avlm_inference.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ from pathlib import Path
4
+ from typing import Union
5
+
6
+ # hf path
7
+ import requests
8
+ import torch
9
+ from PIL import Image
10
+ from transformers import AutoProcessor
11
+ from transformers import AutoTokenizer
12
+ import soundfile as sf
13
+ import io
14
+ import numpy as np
15
+ import scipy.signal as signal
16
+
17
+ from examples.mimo.model_providers.llava_avlm import model_provider_llava_avlm
18
+ from megatron.core import dist_checkpointing, parallel_state, tensor_parallel
19
+ from megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seed
20
+ from megatron.training import print_rank_0
21
+ from examples.mimo.data.utils.calculate_audio_tokens import calculate_num_audio_tokens
22
+
23
+ def init_distributed(tp_size: int = 1, pp_size: int = 1):
24
+ if torch.distributed.is_initialized():
25
+ return
26
+ rank = int(os.environ.get("LOCAL_RANK", 0))
27
+ world_size = int(os.environ.get("WORLD_SIZE", 1))
28
+ torch.cuda.set_device(rank % torch.cuda.device_count())
29
+ torch.distributed.init_process_group("nccl", rank=rank, world_size=world_size)
30
+ parallel_state.initialize_model_parallel(tp_size, pp_size)
31
+
32
+ def get_input_data(
33
+ processor: AutoProcessor,
34
+ image_processor: AutoProcessor,
35
+ audio_processor: AutoProcessor,
36
+ audio_path: str,
37
+ image_path: str,
38
+ prompt: str,
39
+ device: Union[int, str] = 0):
40
+ """
41
+ Prepare inputs for the MIMO model forward pass.
42
+ """
43
+
44
+ def read_audio(audio_path):
45
+ """Process audio file and return tensor."""
46
+ with open(audio_path, 'rb') as f:
47
+ audio_bytes = f.read()
48
+ audio_io = io.BytesIO(audio_bytes)
49
+ waveform, sample_rate = sf.read(audio_io)
50
+
51
+ # Resample if needed
52
+ fixed_sample_rate = 16000
53
+ if sample_rate != fixed_sample_rate:
54
+ num_samples = int(len(waveform) * fixed_sample_rate / sample_rate)
55
+ waveform = signal.resample(waveform, num_samples)
56
+
57
+ # Convert to tensor
58
+ audio_tensor = torch.from_numpy(waveform).float()
59
+ return audio_tensor
60
+
61
+ def read_image(image_path):
62
+ """Process image file and return tensor."""
63
+ with open(image_path, 'rb') as f:
64
+ image_bytes = f.read()
65
+ image_io = io.BytesIO(image_bytes)
66
+ image = Image.open(image_io)
67
+ image_tensor = torch.from_numpy(np.array(image)).permute(2, 0, 1) # Convert to CxHxW format
68
+ image_tensor = image_tensor.float() / 255.0 # rescale to [0,1] range
69
+ return image_tensor
70
+
71
+
72
+ # read audio and image
73
+ audio_tensor = read_audio(audio_path)
74
+ image_tensor = read_image(image_path)
75
+
76
+ # set up prompt
77
+ conversation = [
78
+ {
79
+ "role": "user",
80
+ "content": [
81
+ {"type": "text", "text": prompt},
82
+ ],
83
+ }
84
+ ]
85
+ prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
86
+
87
+ # process audio
88
+ processed_audios = audio_processor(audio_tensor, sampling_rate=16000)
89
+ processed_audios = torch.tensor(processed_audios["input_features"])
90
+ processed_audios = processed_audios.squeeze(0) # remove batch dim
91
+ num_audio_tokens = calculate_num_audio_tokens(audio_tensor.unsqueeze(0), "openai/whisper-base")
92
+ audios_seq_lengths = torch.tensor(num_audio_tokens)
93
+ prompt = prompt.replace("<audio>", "<audio>" * num_audio_tokens)
94
+
95
+ # process image
96
+ processed_images = image_processor(
97
+ images=image_tensor,
98
+ return_tensors="pt",
99
+ do_rescale=False,
100
+ )["pixel_values"]
101
+ processed_images = processed_images.squeeze(0) # remove batch dim
102
+
103
+ # process prompt
104
+ processed_prompt_inputs = processor(
105
+ images=image_tensor,
106
+ text=prompt,
107
+ add_special_tokens=False,
108
+ return_tensors="pt",
109
+ do_rescale=False,
110
+ )
111
+
112
+ # set batch data
113
+ processed_images = processed_images.unsqueeze(0).to(device)
114
+ processed_audios = processed_audios.unsqueeze(0).to(device)
115
+ audios_seq_lengths = audios_seq_lengths.unsqueeze(0).to(device)
116
+ tokens = processed_prompt_inputs["input_ids"].to(device)
117
+ modality_inputs = {
118
+ "images": {"clip_encoder": {"pixel_values": processed_images}},
119
+ "audios": {"whisper_encoder": {"input_features": processed_audios, "seq_lengths": audios_seq_lengths}}
120
+ }
121
+ batch_data = {
122
+ "tokens": tokens,
123
+ "modality_inputs": modality_inputs,
124
+ }
125
+
126
+ return batch_data
127
+
128
+
129
+ def main():
130
+ parser = argparse.ArgumentParser("Test loading a distributed LLaVA checkpoint")
131
+ parser.add_argument("--ckpt", required=False, help="Path to checkpoint optional")
132
+ parser.add_argument("--tp", type=int, default=1, help="Tensor parallel size")
133
+ parser.add_argument("--pp", type=int, default=1, help="Pipeline parallel size")
134
+ parser.add_argument("--audio-path", type=str,required=True, help="Path to audio file")
135
+ parser.add_argument("--image-path", type=str,required=True, help="Path to image file")
136
+ parser.add_argument("--prompt", type=str,required=True, help="Prompt")
137
+ args = parser.parse_args()
138
+
139
+
140
+ init_distributed(args.tp, args.pp)
141
+ model_parallel_cuda_manual_seed(123)
142
+
143
+ device = torch.device("cuda")
144
+
145
+ model = model_provider_llava_avlm().to(device)
146
+
147
+ # Load distributed checkpoint if provided.
148
+ if args.ckpt:
149
+ load_distributed_checkpoint(model, args.ckpt)
150
+
151
+ # set tokenizer
152
+ tokenizer = AutoTokenizer.from_pretrained("llava-hf/llava-1.5-7b-hf")
153
+ tokenizer.add_special_tokens({'additional_special_tokens': ["<audio>"]})
154
+ tokenizer.vocab["<audio>"] = 32002
155
+ tokenizer.added_tokens_encoder["<audio>"] = 32002
156
+ tokenizer.added_tokens_decoder[32002] = "<audio>"
157
+
158
+ # set processors
159
+ processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
160
+ processor.tokenizer = tokenizer
161
+ image_processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf").image_processor
162
+ audio_processor = AutoProcessor.from_pretrained("openai/whisper-base")
163
+
164
+
165
+ data = get_input_data(
166
+ processor,
167
+ image_processor,
168
+ audio_processor,
169
+ args.audio_path,
170
+ args.image_path,
171
+ args.prompt,
172
+ device=device)
173
+
174
+ # ------------------------------------------------------------------
175
+ # Greedy generation
176
+ # ------------------------------------------------------------------
177
+ max_new_tokens = 128
178
+ model.eval()
179
+
180
+ tokens = data["tokens"]
181
+
182
+ with torch.no_grad():
183
+ for _ in range(max_new_tokens):
184
+ seq_len = tokens.size(1)
185
+ position_ids = torch.arange(seq_len, device=tokens.device).unsqueeze(0)
186
+ logits, _ = model(
187
+ input_ids=tokens,
188
+ position_ids=position_ids,
189
+ attention_mask=None,
190
+ modality_inputs=data["modality_inputs"],
191
+ )
192
+
193
+ # All-gather logits across tensor parallel ranks
194
+ # logits shape: [batch, seq, vocab_parallel_size]
195
+ gathered_logits = tensor_parallel.gather_from_tensor_model_parallel_region(logits)
196
+
197
+ # The language model returns logits in [batch, seq, vocab] format.
198
+ next_token_logits = gathered_logits[:, -1, :]
199
+ next_token = torch.argmax(next_token_logits, dim=-1, keepdim=True)
200
+
201
+ tokens = torch.cat([tokens, next_token], dim=1)
202
+
203
+ if processor.tokenizer.eos_token_id is not None and next_token.item() == processor.tokenizer.eos_token_id:
204
+ break
205
+
206
+ # Only decode and print on rank 0
207
+ if torch.distributed.get_rank() == 0:
208
+ generated_text = processor.tokenizer.decode(tokens[0], skip_special_tokens=True)
209
+ print("\n=== Generated text ===\n")
210
+ print(generated_text)
211
+
212
+
213
+ def load_distributed_checkpoint(model: torch.nn.Module, ckpt_dir: str):
214
+ """Load a MIMO model from a Megatron distributed checkpoint directory"""
215
+
216
+ if not os.path.isdir(ckpt_dir):
217
+ raise FileNotFoundError(f"Checkpoint directory does not exist: {ckpt_dir}")
218
+
219
+
220
+ template_sd = {"model": model.sharded_state_dict()}
221
+
222
+ loaded_sd = dist_checkpointing.load(template_sd, ckpt_dir)
223
+
224
+ model_state_dict = loaded_sd["model"]
225
+ incompat = model.load_state_dict(model_state_dict, strict=False)
226
+
227
+ missing = [k for k in incompat.missing_keys if "extra_state" not in k]
228
+ unexpected = [k for k in incompat.unexpected_keys if "extra_state" not in k]
229
+ if missing or unexpected:
230
+ print_rank_0(
231
+ f"[Rank {torch.distributed.get_rank() if torch.distributed.is_initialized() else 0}] "
232
+ f"Checkpoint loaded with mismatches. Missing: {missing}, Unexpected: {unexpected}"
233
+ )
234
+
235
+ print_rank_0(
236
+ f"[Rank {torch.distributed.get_rank() if torch.distributed.is_initialized() else 0}] "
237
+ f"Successfully loaded checkpoint from {ckpt_dir}"
238
+ )
239
+
240
+ return model
241
+
242
+
243
+ if __name__ == "__main__":
244
+ main()
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/configs/llava_avlm.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+
3
+ """
4
+ Configuration utilities for the MIMO implementation of the LLaVA AVLM.
5
+ """
6
+
7
+
8
+ from typing import Optional
9
+
10
+ import torch
11
+
12
+ from megatron.core.extensions.transformer_engine import (
13
+ TEColumnParallelLinear,
14
+ TERowParallelLinear,
15
+ )
16
+ from megatron.core.models.gpt.gpt_layer_specs import (
17
+ get_gpt_layer_with_transformer_engine_spec,
18
+ )
19
+ from megatron.core.transformer.mlp import MLP, MLPSubmodules
20
+ from megatron.core.transformer.spec_utils import ModuleSpec
21
+ from megatron.core.transformer.transformer_config import TransformerConfig
22
+ from examples.mimo.configs.llava_vlm import get_vicuna_language_model_config
23
+
24
+
25
+ def get_llava_projection_config(
26
+ hidden_size: int = 4096,
27
+ config: Optional[TransformerConfig] = None,
28
+ ) -> TransformerConfig:
29
+ """Return a TransformerConfig for the vision projection MLP."""
30
+
31
+ cfg = TransformerConfig(num_layers=1, hidden_size=hidden_size, num_attention_heads=1)
32
+ cfg.ffn_hidden_size = 4096
33
+ cfg.bias_activation_fusion = True
34
+ cfg.add_bias_linear = True
35
+ cfg.activation_func = torch.nn.functional.gelu
36
+
37
+ # Allow caller overrides.
38
+ if config is not None:
39
+ for field, value in vars(config).items():
40
+ setattr(cfg, field, value)
41
+
42
+ return cfg
43
+
44
+
45
+
46
+ def get_vicuna_language_layer_spec() -> ModuleSpec:
47
+ """Layer spec for the language model (Transformer-Engine GPT block)."""
48
+ return get_gpt_layer_with_transformer_engine_spec()
49
+
50
+ def get_llava_projection_layer_spec() -> ModuleSpec:
51
+ """Layer spec for the vision-projection MLP."""
52
+
53
+ return ModuleSpec(
54
+ module=MLP,
55
+ submodules=MLPSubmodules(
56
+ linear_fc1=TEColumnParallelLinear,
57
+ linear_fc2=TERowParallelLinear,
58
+ ),
59
+ )
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/configs/llava_vlm.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+
3
+ """
4
+ Configuration utilities for the MIMO implementation of the LLaVA VLM.
5
+ """
6
+
7
+
8
+ from typing import Optional
9
+
10
+ import torch
11
+
12
+ from megatron.core.extensions.transformer_engine import (
13
+ TEColumnParallelLinear,
14
+ TERowParallelLinear,
15
+ )
16
+ from megatron.core.models.gpt.gpt_layer_specs import (
17
+ get_gpt_layer_with_transformer_engine_spec,
18
+ )
19
+ from megatron.core.transformer.mlp import MLP, MLPSubmodules
20
+ from megatron.core.transformer.spec_utils import ModuleSpec
21
+ from megatron.core.transformer.transformer_config import TransformerConfig
22
+
23
+
24
+ def get_vicuna_language_model_config(
25
+ config: Optional[TransformerConfig] = None,
26
+ ) -> TransformerConfig:
27
+ """Return a TransformerConfig tuned for **Vicuna-7B**.
28
+
29
+ The hyper-parameters follow the published Vicuna-7B weights (same sizes as
30
+ Llama-7B).
31
+ """
32
+
33
+ cfg = TransformerConfig(num_layers=32, hidden_size=4096, num_attention_heads=32)
34
+
35
+ # Feed-forward / MLP hidden size (11008 in original Vicuna).
36
+ cfg.ffn_hidden_size = 11008
37
+
38
+ # SwiGLU (SiLU-gate) activation.
39
+ cfg.activation_func = torch.nn.functional.silu
40
+ cfg.gated_linear_unit = True
41
+
42
+ # Normalisation – RMSNorm
43
+ cfg.normalization = "RMSNorm"
44
+ cfg.rms_norm_eps = 1e-5
45
+
46
+ # Positional embeddings – RoPE.
47
+ cfg.position_embedding_type = "rope"
48
+ cfg.rotary_base = 10000
49
+ cfg.rotary_percent = 1.0
50
+
51
+ # Sequence length.
52
+ cfg.seq_length = 4096
53
+ cfg.max_position_embeddings = 4096
54
+
55
+ # Attention / dropout.
56
+ cfg.attention_dropout = 0.0
57
+ cfg.hidden_dropout = 0.0
58
+
59
+ # GQA disabled (queries == heads).
60
+ cfg.num_query_groups = 32
61
+
62
+ # Bias usage.
63
+ cfg.add_bias_linear = False
64
+
65
+ # Weight sharing.
66
+ cfg.untie_embeddings_and_output_weights = False
67
+
68
+ # Kernel / TE fusions.
69
+ cfg.bias_activation_fusion = True
70
+ cfg.masked_softmax_fusion = True
71
+ cfg.persist_layer_norm = True
72
+ cfg.bias_dropout_fusion = True
73
+ cfg.apply_rope_fusion = True
74
+
75
+ # Apply user overrides last.
76
+ if config is not None:
77
+ for field, value in vars(config).items():
78
+ setattr(cfg, field, value)
79
+
80
+ return cfg
81
+
82
+ def get_llava_projection_config(
83
+ hidden_size: int = 4096,
84
+ config: Optional[TransformerConfig] = None,
85
+ ) -> TransformerConfig:
86
+ """Return a TransformerConfig for the vision projection MLP."""
87
+
88
+ cfg = TransformerConfig(num_layers=1, hidden_size=hidden_size, num_attention_heads=1)
89
+ cfg.ffn_hidden_size = 4096
90
+ cfg.bias_activation_fusion = True
91
+ cfg.add_bias_linear = True
92
+ cfg.activation_func = torch.nn.functional.gelu
93
+
94
+ # Allow caller overrides.
95
+ if config is not None:
96
+ for field, value in vars(config).items():
97
+ setattr(cfg, field, value)
98
+
99
+ return cfg
100
+
101
+
102
+
103
+ def get_vicuna_language_layer_spec() -> ModuleSpec:
104
+ """Layer spec for the language model (Transformer-Engine GPT block)."""
105
+ return get_gpt_layer_with_transformer_engine_spec()
106
+
107
+ def get_llava_projection_layer_spec() -> ModuleSpec:
108
+ """Layer spec for the vision-projection MLP."""
109
+
110
+ return ModuleSpec(
111
+ module=MLP,
112
+ submodules=MLPSubmodules(
113
+ linear_fc1=TEColumnParallelLinear,
114
+ linear_fc2=TERowParallelLinear,
115
+ ),
116
+ )
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/configs/mock.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+
3
+ """
4
+ Mock configuration utilities for MIMO model with vision encoder.
5
+
6
+ This module provides functions to create test configurations for:
7
+ 1. Language model (based on LLaMA architecture)
8
+ 2. Vision encoder (based on CLIP ViT)
9
+ 3. Vision projection (MLP)
10
+
11
+ These configurations are intended for testing and development purposes only.
12
+ """
13
+
14
+ from typing import Optional
15
+
16
+ from megatron.core.extensions.transformer_engine import (
17
+ TEColumnParallelLinear,
18
+ TERowParallelLinear,
19
+ )
20
+ from megatron.core.models.gpt.gpt_layer_specs import (
21
+ get_gpt_layer_with_transformer_engine_spec,
22
+ )
23
+ from megatron.core.transformer.mlp import MLP, MLPSubmodules
24
+ from megatron.core.transformer.spec_utils import ModuleSpec
25
+ from megatron.core.transformer.transformer_config import TransformerConfig
26
+
27
+
28
+ def get_mock_language_model_config(config: Optional[TransformerConfig] = None) -> TransformerConfig:
29
+ """
30
+ Create a mock language model configuration.
31
+
32
+ Args:
33
+ config: Optional base configuration to modify
34
+
35
+ Returns:
36
+ TransformerConfig: Mock configuration for a language model
37
+ """
38
+
39
+ config = TransformerConfig(num_layers=1, hidden_size=128, num_attention_heads=4)
40
+
41
+ if config is not None:
42
+ for field_name, field_value in vars(config).items():
43
+ setattr(config, field_name, field_value)
44
+
45
+ return config
46
+
47
+ def get_mock_vision_model_config(config: Optional[TransformerConfig] = None) -> TransformerConfig:
48
+ """
49
+ Create a mock vision model configuration.
50
+
51
+ Args:
52
+ config: Optional base configuration to modify
53
+
54
+ Returns:
55
+ TransformerConfig: Mock configuration for a vision model
56
+ """
57
+ config = TransformerConfig(num_layers=1, hidden_size=128, num_attention_heads=4)
58
+
59
+ config.add_bias_linear = True
60
+ config.add_qkv_bias = True
61
+ config.hidden_dropout = 0.0
62
+ config.attention_dropout = 0.0
63
+ config.ffn_hidden_size = config.hidden_size * 4
64
+ config.gated_linear_unit = False
65
+ config.kv_channels = 64
66
+ config.layernorm_zero_centered_gamma = False
67
+ config.apply_query_key_layer_scaling = False
68
+ config.bias_activation_fusion = False
69
+ config.bias_dropout_fusion = False
70
+ config.attention_softmax_in_fp32 = True
71
+ config.normalization = 'LayerNorm'
72
+ config.apply_rope_fusion = False
73
+ return config
74
+
75
+
76
+ def get_mock_projection_config(hidden_size: int = 128) -> TransformerConfig:
77
+ """
78
+ Create a mock projection layer configuration.
79
+
80
+ Args:
81
+ hidden_size: Hidden dimension size (used as the vision projection output size)
82
+
83
+ Returns:
84
+ TransformerConfig: Mock configuration for a projection layer
85
+ """
86
+ config = TransformerConfig(num_layers=1, hidden_size=hidden_size, num_attention_heads=1)
87
+
88
+ config.ffn_hidden_size = hidden_size * 4
89
+ config.gated_linear_unit = False
90
+ config.bias_activation_fusion = False
91
+ config.add_bias_linear = False
92
+ config.normalization = 'LayerNorm'
93
+
94
+ return config
95
+
96
+
97
+ def get_mock_language_layer_spec():
98
+ """
99
+ Get the mock layer specification for the language model.
100
+
101
+ Returns:
102
+ ModuleSpec: Mock specification for language model layers
103
+ """
104
+ return get_gpt_layer_with_transformer_engine_spec()
105
+
106
+
107
+ def get_mock_vision_layer_spec():
108
+ """
109
+ Get the mock layer specification for the vision model.
110
+
111
+ Args:
112
+ normalization: Type of normalization to use
113
+
114
+ Returns:
115
+ ModuleSpec: Mock specification for vision model layers
116
+ """
117
+ return get_gpt_layer_with_transformer_engine_spec()
118
+
119
+
120
+ def get_mock_projection_layer_spec():
121
+ """
122
+ Get the mock layer specification for the projection layer.
123
+
124
+ Returns:
125
+ ModuleSpec: Mock specification for projection layers
126
+ """
127
+ return ModuleSpec(
128
+ module=MLP,
129
+ submodules=MLPSubmodules(linear_fc1=TEColumnParallelLinear, linear_fc2=TERowParallelLinear),
130
+ )
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/data/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .energon_avlm_task_encoder import VisionAudioQASample
2
+
3
+ all = [
4
+ VisionAudioQASample,
5
+ ]
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/data/avlm_sample_loader.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+
3
+ def sample_loader(raw: dict) -> dict:
4
+ """
5
+ Load the sample from the raw data.
6
+ Example content of wds data:
7
+ - Example of wds data
8
+ 100_100.img
9
+ 100_100.json
10
+ 100_100.synthesized_683016ff-bb67-4a12-a873-a7e5d4132903.wav.flac
11
+ 100_100.synthesized_6a7b3a1c-05a9-4720-b7e6-f7028415dc71.wav.flac
12
+ 100_100.synthesized_7c4b39ba-20ef-4319-bd94-291c94ad362a.wav.flac
13
+ 100_100.synthesized_932f067b-2b9a-425d-b8e6-f74ca83335a2.wav.flac
14
+ Content of 100_100.json:
15
+ {
16
+ "num_image": 7,
17
+ "length": 2049,
18
+ "label_length": 157,
19
+ "conversations": [
20
+ {
21
+ "from": "human",
22
+ "value": "<image><audio>"
23
+ },
24
+ {
25
+ "from": "gpt",
26
+ "value": "The stop sign is red, while the one-way signs are typically black and white."
27
+ },
28
+ ...
29
+ {
30
+ "from": "human",
31
+ "value": "<audio>"
32
+ },
33
+ {
34
+ "from": "gpt",
35
+ "value": "The purpose of these street signs is to communicate..."
36
+ }
37
+ ],
38
+ "audios": [
39
+ "100_100.synthesized_6a7b3a1c-05a9-4720-b7e6-f7028415dc71.wav.flac",
40
+ "100_100.synthesized_932f067b-2b9a-425d-b8e6-f74ca83335a2.wav.flac",
41
+ "100_100.synthesized_7c4b39ba-20ef-4319-bd94-291c94ad362a.wav.flac",
42
+ "100_100.synthesized_683016ff-bb67-4a12-a873-a7e5d4132903.wav.flac"
43
+ ],
44
+ "images": [
45
+ "100_100.img"
46
+ ]
47
+ }
48
+ - Example of read raw data for Energon
49
+ raw["json"] -> json content
50
+ raw["img"] -> bytes image content
51
+ raw["synthesized_6a7b3a1c-05a9-4720-b7e6-f7028415dc71.wav.flac"] -> bytes audio content
52
+ raw["synthesized_932f067b-2b9a-425d-b8e6-f74ca83335a2.wav.flac"] -> bytes audio content
53
+ raw["synthesized_683016ff-bb67-4a12-a873-a7e5d4132903.wav.flac"] -> bytes audio content
54
+ """
55
+
56
+ jsn_content = raw["json"]
57
+ conversation = jsn_content["conversations"]
58
+
59
+ # Get raw image bytes
60
+ image_bytes = raw["img"]
61
+
62
+ # Get raw audio bytes
63
+ audio_names = [audio_name.split('.', 1)[1] for audio_name in jsn_content["audios"]] # example of audio_name file: "100_100.synthesized_683016ff-bb67-4a12-a873-a7e5d4132903.wav.flac" -> "synthesized_683016ff-bb67-4a12-a873-a7e5d4132903.wav"
64
+ audio_name = audio_names[0] # for now, take only the first audio
65
+ audio_bytes = raw[audio_name]
66
+
67
+ # process conversation, take only the first turn
68
+ context = conversation[0]["value"]
69
+ answers = conversation[1]["value"]
70
+
71
+ # check that context only contains one "<audio>"
72
+ # if contains more than one, replace all occurrences with a single one
73
+ if context.count("<audio>") > 1:
74
+ parts = context.split("<audio>")
75
+ context = parts[0] + "<audio>" + "".join(parts[1:])
76
+
77
+ return dict(
78
+ __key__=raw["__key__"],
79
+ context=context,
80
+ answers=answers,
81
+ image=image_bytes,
82
+ audio=audio_bytes,
83
+ )
84
+
85
+ def part_filter(part: str) -> bool:
86
+ return True
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/data/energon_avlm_task_encoder.py ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+
3
+ import argparse
4
+ import logging
5
+ import os
6
+ import sys
7
+ from dataclasses import dataclass
8
+ from enum import Enum
9
+ from typing import Dict, List, Protocol, Union
10
+
11
+ import torch
12
+ import torch.nn.utils.rnn as rnn_utils
13
+ from PIL import Image
14
+ import numpy as np
15
+ import soundfile as sf
16
+ from scipy import signal
17
+ import io
18
+ from megatron.training.global_vars import get_tokenizer
19
+
20
+ sys.path.append(
21
+ os.path.abspath(
22
+ os.path.join(
23
+ os.path.dirname(__file__),
24
+ os.path.pardir,
25
+ os.path.pardir,
26
+ os.path.pardir,
27
+ "examples/multimodal",
28
+ )
29
+ )
30
+ )
31
+ from dataloader_provider import train_valid_test_dataloaders_provider
32
+ from transformers import AutoProcessor
33
+ from examples.mimo.data.utils.calculate_audio_tokens import calculate_num_audio_tokens
34
+
35
+ from megatron.energon import (
36
+ DefaultTaskEncoder,
37
+ VQASample,
38
+ WorkerConfig,
39
+ get_loader,
40
+ get_train_dataset,
41
+ )
42
+ from megatron.energon.task_encoder.base import stateless
43
+ from megatron.training import get_args
44
+
45
+ IMAGE_TOKEN = "<image>"
46
+ AUDIO_TOKEN = "<audio>"
47
+
48
+
49
+ @dataclass
50
+ class ConversationTemplateConfig:
51
+ system: str = None
52
+ chat_template: str = None
53
+
54
+
55
+ @dataclass
56
+ class LlavaConversationTemplateConfig(ConversationTemplateConfig):
57
+ """Default system prompt and chat template for Llava training."""
58
+
59
+ system: str = None
60
+ chat_template: str = None
61
+
62
+
63
+ @dataclass
64
+ class VisionAudioQASample(VQASample):
65
+ """
66
+ Sample type for vision audio question answering.
67
+ Adding audio to the VQASample class.
68
+ """
69
+
70
+ #: The input audio tensor in the shape
71
+ audio: torch.Tensor = None
72
+
73
+
74
+ class AVLMModelType(Enum):
75
+ IMAGE_AUDIO_LLAVA_AVLM = "image_audio_llava_avlm"
76
+
77
+
78
+ class AVLMTaskEncoder(
79
+ DefaultTaskEncoder[
80
+ VisionAudioQASample,
81
+ dict,
82
+ dict,
83
+ dict,
84
+ ]
85
+ ):
86
+ def __init__(
87
+ self,
88
+ model_type: AVLMModelType,
89
+ processor,
90
+ image_processor,
91
+ audio_processor,
92
+ conversation_template_config=None,
93
+ ):
94
+ self.model_type = model_type
95
+ self.processor = processor
96
+ self.image_processor = image_processor
97
+ self.audio_processor = audio_processor
98
+ self.conversation_template_config = conversation_template_config
99
+
100
+ def apply_prompt_template(self, input_text: VisionAudioQASample):
101
+ """Create conversation prompt string using HF chat template.
102
+
103
+ The first user turn always contains an image placeholder, later turns are text-only.
104
+ Returns a *prompt string* that can be fed into the processor together with an image.
105
+ """
106
+
107
+ user_msgs = input_text.context
108
+ bot_msgs = input_text.answers
109
+
110
+ def _ensure_list_type(value):
111
+ if isinstance(value, list):
112
+ return value
113
+ return [value]
114
+
115
+ user_msgs = _ensure_list_type(user_msgs)
116
+ bot_msgs = _ensure_list_type(bot_msgs)
117
+
118
+ conversation = []
119
+ for _, (u_txt, b_txt) in enumerate(zip(user_msgs, bot_msgs)):
120
+ conversation.append(
121
+ {
122
+ "role": "user",
123
+ "content": [{"type": "text", "text": u_txt}],
124
+ }
125
+ )
126
+ conversation.append(
127
+ {
128
+ "role": "assistant",
129
+ "content": [{"type": "text", "text": b_txt}],
130
+ }
131
+ )
132
+
133
+ # Inject optional system message
134
+ if (
135
+ self.conversation_template_config
136
+ and self.conversation_template_config.system
137
+ ):
138
+ conversation.insert(
139
+ 0,
140
+ {"role": "system", "content": self.conversation_template_config.system},
141
+ )
142
+
143
+ # Select chat template
144
+ if (
145
+ self.conversation_template_config
146
+ and self.conversation_template_config.chat_template
147
+ ):
148
+ self.processor.chat_template = (
149
+ self.conversation_template_config.chat_template
150
+ )
151
+ return self.processor.apply_chat_template(
152
+ conversation,
153
+ tokenize=False,
154
+ add_generation_prompt=False,
155
+ )
156
+
157
+ def _find_pattern_indices(
158
+ self, template, pattern, start_idx=0, allow_first_mismatch=False
159
+ ):
160
+ template_len = len(template)
161
+ pat_len = len(pattern)
162
+ for i in range(start_idx, template_len - pat_len + 1):
163
+ match = template[i : i + pat_len] == pattern
164
+ if torch.all(match) or (allow_first_mismatch and torch.all(match[1:])):
165
+ return i, i + pat_len
166
+ return -1, -1
167
+
168
+ @stateless
169
+ def encode_sample(self, sample: VisionAudioQASample):
170
+ """Return tokenised multimodal sample."""
171
+ args = get_args()
172
+ prompt = self.apply_prompt_template(sample)
173
+ logging.debug(f"prompt: {prompt}")
174
+
175
+ # Convert raw image bytes to tensor
176
+ if sample.image is not None:
177
+ image_io = io.BytesIO(sample.image)
178
+ image = Image.open(image_io)
179
+ image_tensor = torch.from_numpy(np.array(image)).permute(2, 0, 1) # Convert to CxHxW format
180
+ image_tensor = image_tensor.float() / 255.0 # rescale to [0,1] range
181
+ else:
182
+ image_tensor = None
183
+
184
+ # Convert raw audio data to tensor
185
+ if sample.audio is not None:
186
+ audio_io = io.BytesIO(sample.audio)
187
+ # Read audio first
188
+ waveform, sample_rate = sf.read(audio_io)
189
+ # Resample if needed
190
+ fixed_sample_rate = 16000
191
+ if sample_rate != fixed_sample_rate:
192
+ # Calculate number of samples for 16kHz
193
+ num_samples = int(len(waveform) * fixed_sample_rate / sample_rate)
194
+ # Resample using scipy's resample
195
+ waveform = signal.resample(waveform, num_samples)
196
+ # Convert to tensor
197
+ audio_tensor = torch.from_numpy(waveform).float()
198
+ else:
199
+ audio_tensor = None
200
+
201
+ # Process audio + prompt
202
+ # Here, we:
203
+ # + process the audio
204
+ # + manually calculate the number of audio tokens, then add them to the prompt
205
+ if audio_tensor is not None:
206
+ processed_audios = self.audio_processor(audio_tensor, sampling_rate=fixed_sample_rate)
207
+ processed_audios = torch.tensor(processed_audios["input_features"])
208
+ processed_audios = processed_audios.squeeze(0) # remove batch dim
209
+ num_audio_tokens = calculate_num_audio_tokens(audio_tensor.unsqueeze(0), args.audio_encoder_model)
210
+ audios_seq_lengths = torch.tensor(num_audio_tokens)
211
+ processed_prompt = prompt.replace(AUDIO_TOKEN, AUDIO_TOKEN * num_audio_tokens)
212
+ else:
213
+ processed_audios = None
214
+ audios_seq_lengths = None
215
+ processed_prompt = prompt
216
+
217
+ # Process image + prompt
218
+ # Here, we:
219
+ # + process the image
220
+ # + use self.processor to automatically calculate the number
221
+ # of image tokens, then add them to the prompt
222
+ # => this step combine adding the corresponding image tokens to the prompt AND
223
+ # tokenize the prompt after that
224
+ if image_tensor is not None:
225
+ processed_images = self.image_processor(
226
+ images=image_tensor,
227
+ return_tensors="pt",
228
+ do_rescale=False,
229
+ )["pixel_values"]
230
+ processed_images = processed_images.squeeze(0) # remove batch dim
231
+ else:
232
+ processed_images = None
233
+
234
+ processed_prompt_inputs = self.processor(
235
+ images=image_tensor,
236
+ text=processed_prompt,
237
+ add_special_tokens=False,
238
+ return_tensors="pt",
239
+ do_rescale=False,
240
+ )
241
+
242
+ # Remove batch dim
243
+ for k, v in processed_prompt_inputs.items():
244
+ processed_prompt_inputs[k] = v.squeeze(0)
245
+
246
+ # Combine image and audio processed data
247
+ inputs = {
248
+ "input_ids": processed_prompt_inputs["input_ids"],
249
+ "attention_mask": processed_prompt_inputs["attention_mask"],
250
+ }
251
+
252
+ if processed_images is not None:
253
+ inputs["images"] = processed_images
254
+
255
+ if processed_audios is not None:
256
+ inputs["audios"] = processed_audios
257
+ inputs["audios_seq_lengths"] = audios_seq_lengths
258
+
259
+ answers = sample.answers
260
+ if answers:
261
+ if not isinstance(answers, list):
262
+ answers = [answers]
263
+ tokenizer = self.processor.tokenizer
264
+ inputs["labels"] = torch.full_like(inputs["input_ids"], fill_value=-100)
265
+ search_idx = 0
266
+ for ans in answers:
267
+ answer_tokens = tokenizer.encode(
268
+ ans, add_special_tokens=False, return_tensors="pt"
269
+ )[0]
270
+ s_idx, e_idx = self._find_pattern_indices(
271
+ inputs["input_ids"], answer_tokens, search_idx
272
+ )
273
+ if s_idx == -1:
274
+ raise ValueError(f"Answer not found in input_ids: {ans}")
275
+ inputs["labels"][s_idx:e_idx] = inputs["input_ids"][s_idx:e_idx]
276
+ search_idx = e_idx
277
+
278
+ # shift inputs and labels by 1
279
+ inputs["input_ids"] = inputs["input_ids"][:-1]
280
+ inputs["labels"] = inputs["labels"][1:]
281
+ inputs["loss_mask"] = (inputs["labels"] != -100).long()
282
+
283
+ else:
284
+ inputs["labels"] = None
285
+ inputs["loss_mask"] = None
286
+
287
+ return inputs
288
+
289
+ def batch(self, samples: List[Dict]) -> Dict:
290
+ """Pad/stack individual samples into a single batch dict."""
291
+
292
+ if not samples:
293
+ return {}
294
+
295
+ batched: Dict[str, torch.Tensor] = {}
296
+ keys = samples[0].keys()
297
+
298
+ for key in keys:
299
+ values = [s[key] for s in samples if key in s and s[key] is not None]
300
+
301
+ processor = KEY_PROCESSORS.get(key)
302
+ if processor is not None:
303
+ batched[key] = processor(values)
304
+ continue
305
+
306
+ # Fallback behaviours if no specific processor is registered.
307
+ if isinstance(values[0], torch.Tensor):
308
+ batched[key] = torch.stack(values, dim=0)
309
+ else:
310
+ batched[key] = values
311
+
312
+ return batched
313
+
314
+ def encode_batch_avlm_clip_whisper_llava(self, batch_data: Dict) -> Dict:
315
+ input_ids = batch_data["input_ids"]
316
+ labels = batch_data.get("labels")
317
+ loss_mask = batch_data.get("loss_mask")
318
+
319
+ seq_len = input_ids.size(1)
320
+ position_ids = torch.arange(seq_len, dtype=torch.long, device=input_ids.device)
321
+ position_ids = position_ids.unsqueeze(0).repeat(input_ids.size(0), 1)
322
+
323
+ images = batch_data.get("images")
324
+ audios = batch_data.get("audios")
325
+ audios_seq_lengths = batch_data.get("audios_seq_lengths")
326
+
327
+ output = {
328
+ "input_ids": input_ids,
329
+ "labels": labels,
330
+ "loss_mask": loss_mask,
331
+ "position_ids": position_ids,
332
+ }
333
+
334
+ if images is not None:
335
+ output["modality_inputs"] = {
336
+ "images": {"clip_encoder": {"pixel_values": images}}
337
+ }
338
+
339
+ if audios is not None:
340
+ if "modality_inputs" not in output:
341
+ output["modality_inputs"] = {}
342
+ output["modality_inputs"]["audios"] = {
343
+ "whisper_encoder": {
344
+ "input_features": audios,
345
+ "seq_lengths": audios_seq_lengths
346
+ }
347
+ }
348
+
349
+ return output
350
+
351
+ def encode_batch(self, batch_data: Dict) -> dict:
352
+ if self.model_type is AVLMModelType.IMAGE_AUDIO_LLAVA_AVLM:
353
+ return self.encode_batch_avlm_clip_whisper_llava(batch_data)
354
+ else:
355
+ raise ValueError(f"Model type {self.model_type} not supported")
356
+
357
+
358
+ def llava_avlm_dataloader_provider(train_val_test_num_samples):
359
+ args = get_args()
360
+
361
+ # update global tokenizer if hf_assign_unused_tokens is set
362
+ if args.hf_assign_unused_tokens:
363
+ _tokenizer = get_tokenizer()._tokenizer
364
+ for token_id_pair in args.hf_assign_unused_tokens:
365
+ token, id_str = token_id_pair.split(',')
366
+ id = int(id_str)
367
+ _tokenizer.add_special_tokens({'additional_special_tokens': [token]})
368
+ _tokenizer.vocab[token] = id
369
+ _tokenizer.added_tokens_encoder[token] = id
370
+ _tokenizer.added_tokens_decoder[id] = token
371
+ get_tokenizer()._tokenizer = _tokenizer
372
+
373
+ tokenizer_model_id = args.tokenizer_model
374
+ processor = AutoProcessor.from_pretrained(tokenizer_model_id)
375
+ processor.tokenizer = get_tokenizer()._tokenizer # update processor to use custom tokenizer
376
+ image_processor = AutoProcessor.from_pretrained(tokenizer_model_id).image_processor
377
+ audio_processor = AutoProcessor.from_pretrained(args.audio_encoder_model)
378
+
379
+ return train_valid_test_dataloaders_provider(
380
+ train_val_test_num_samples,
381
+ task_encoder=AVLMTaskEncoder(
382
+ model_type=AVLMModelType.IMAGE_AUDIO_LLAVA_AVLM,
383
+ processor=processor,
384
+ image_processor=image_processor,
385
+ audio_processor=audio_processor,
386
+ conversation_template_config=LlavaConversationTemplateConfig(),
387
+ ),
388
+ )
389
+
390
+
391
+ if __name__ == "__main__":
392
+ parser = argparse.ArgumentParser()
393
+ parser.add_argument(
394
+ "--data_path",
395
+ type=str,
396
+ required=True,
397
+ help="path to the dataset directory in energon format",
398
+ )
399
+ args = parser.parse_args()
400
+
401
+ # for image audio llava avlm
402
+ hf_model_id = "llava-hf/llava-1.5-7b-hf"
403
+ model_type = AVLMModelType.IMAGE_AUDIO_LLAVA_AVLM
404
+
405
+ processor = AutoProcessor.from_pretrained(hf_model_id)
406
+ processor.tokenizer = get_tokenizer()._tokenizer
407
+ image_processor = AutoProcessor.from_pretrained(hf_model_id).image_processor
408
+ audio_processor = AutoProcessor.from_pretrained("openai/whisper-small")
409
+
410
+ worker_config = WorkerConfig.default_worker_config(0)
411
+ train_loader = get_loader(
412
+ get_train_dataset(
413
+ args.data_path,
414
+ batch_size=8,
415
+ shuffle_buffer_size=None,
416
+ max_samples_per_sequence=None,
417
+ task_encoder=AVLMTaskEncoder(
418
+ model_type=model_type,
419
+ processor=processor,
420
+ image_processor=image_processor,
421
+ audio_processor=audio_processor,
422
+ conversation_template_config=LlavaConversationTemplateConfig(),
423
+ ),
424
+ worker_config=worker_config,
425
+ ),
426
+ worker_config=worker_config,
427
+ )
428
+
429
+ print(f"data loader length {len(train_loader)}")
430
+ for index, each_batch in enumerate(train_loader):
431
+ print(f"batch index {index} tokens {each_batch['input_ids']}")
432
+ if 'modality_inputs' in each_batch:
433
+ if 'images' in each_batch['modality_inputs']:
434
+ print(f"images shape: {each_batch['modality_inputs']['images']['clip_encoder']['pixel_values'].shape}")
435
+ if 'audios' in each_batch['modality_inputs']:
436
+ print(f"audios shape: {each_batch['modality_inputs']['audios']['whisper_encoder']['input_features'].shape}")
437
+ break
438
+
439
+
440
+ # -----------------------------------------------------------------------------
441
+ # Key processing utilities for batching
442
+ # -----------------------------------------------------------------------------
443
+
444
+
445
+ class KeyProcessor(Protocol):
446
+ """Callable that aggregates a list of tensors into a single batched tensor."""
447
+
448
+ def __call__(self, values: List[torch.Tensor]) -> torch.Tensor: # pragma: no cover
449
+ ...
450
+
451
+
452
+ class StackProcessor:
453
+ """Simply stack tensors along a given dimension."""
454
+
455
+ def __init__(self, dim: int = 0):
456
+ self.dim = dim
457
+
458
+ def __call__(self, values: List[torch.Tensor]) -> torch.Tensor:
459
+ return torch.stack(values, dim=self.dim)
460
+
461
+
462
+ class PaddingProcessor:
463
+ """Pad variable-length sequences to the same length."""
464
+
465
+ def __init__(self, pad_value: int, batch_first: bool = True):
466
+ self.pad_value = pad_value
467
+ self.batch_first = batch_first
468
+
469
+ def __call__(self, values: List[torch.Tensor]) -> torch.Tensor:
470
+ return rnn_utils.pad_sequence(
471
+ values, batch_first=self.batch_first, padding_value=self.pad_value
472
+ )
473
+
474
+
475
+ # Registry mapping sample keys to their corresponding processor.
476
+ KEY_PROCESSORS: Dict[str, KeyProcessor] = {
477
+ "images": StackProcessor(),
478
+ "audios": StackProcessor(),
479
+ "audios_seq_lengths": StackProcessor(),
480
+ "input_ids": PaddingProcessor(pad_value=0),
481
+ "attention_mask": PaddingProcessor(pad_value=0),
482
+ "loss_mask": PaddingProcessor(pad_value=0),
483
+ "labels": PaddingProcessor(pad_value=-100),
484
+ }
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/data/energon_vlm_task_encoder.py ADDED
@@ -0,0 +1,654 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+
3
+ import argparse
4
+ import logging
5
+ import os
6
+ import sys
7
+ from dataclasses import dataclass
8
+ from enum import Enum
9
+ from typing import Dict, List, Union, Iterable, Tuple, Optional, Protocol
10
+ import heapq
11
+ import torch
12
+ import torch.nn.utils.rnn as rnn_utils
13
+
14
+ # TODO: ykarnati, use absolute import or
15
+ # define train_valid_test_dataloaders_provider in here
16
+ sys.path.append(
17
+ os.path.abspath(
18
+ os.path.join(
19
+ os.path.dirname(__file__),
20
+ os.path.pardir,
21
+ os.path.pardir,
22
+ os.path.pardir,
23
+ "examples/multimodal",
24
+ )
25
+ )
26
+ )
27
+ from dataloader_provider import train_valid_test_dataloaders_provider
28
+ from transformers import AutoProcessor
29
+
30
+ from megatron.core.packed_seq_params import PackedSeqParams
31
+ from megatron.energon import (
32
+ DefaultTaskEncoder,
33
+ VQASample,
34
+ WorkerConfig,
35
+ get_loader,
36
+ get_train_dataset,
37
+ )
38
+ from megatron.energon.task_encoder.base import stateless
39
+ from megatron.training import get_args
40
+ from megatron.core.models.multimodal import context_parallel
41
+
42
+
43
+ @dataclass
44
+ class ConversationTemplateConfig:
45
+ system: str = None
46
+ chat_template: str = None
47
+
48
+
49
+
50
+ @dataclass
51
+ class LlavaConversationTemplateConfig(ConversationTemplateConfig):
52
+ """Default system prompt and chat template for Llava training."""
53
+
54
+ system: str = None
55
+ chat_template: str = None
56
+
57
+ class ModelType(Enum):
58
+ LLAVA_VLM = "llava_vlm"
59
+ VIDEO_LLAVA_VLM = "video_llava_vlm"
60
+
61
+ def predict_seq_len_with_padding(instance_tokens: torch.Tensor, pad_to_multiple_of: int = 64) -> int:
62
+ """Get seqlen with padding.
63
+ Args:
64
+ instance_tokens (torch.Tensor): Tensor of instance tokens.
65
+ pad_to_multiple_of (int): Pad to multiple of this value.
66
+ Returns:
67
+ int: Padded sequence length.
68
+ """
69
+ seqlen = len(instance_tokens)
70
+ seqlen_padded = (seqlen + pad_to_multiple_of - 1) // pad_to_multiple_of * pad_to_multiple_of
71
+ return seqlen_padded
72
+
73
+ def group_samples(samples: List[Dict[str, torch.Tensor]],
74
+ group_size: int,
75
+ lengths: List[int],
76
+ ) -> List[List[Dict[str, torch.Tensor]]]:
77
+ """Group samples into groups of size group_size.
78
+
79
+ Args:
80
+ samples (List[Dict[str, torch.Tensor]]): List of samples to group.
81
+ group_size (int): Maximum size of each group.
82
+ lengths (List[int]): List of lengths of each sample.
83
+
84
+ Returns:
85
+ List[List[Dict[str, torch.Tensor]]]: List of groups, where each group is a list of samples
86
+ that should be packed together. Each group's total length will not exceed group_size.
87
+ """
88
+ # create a max heap of the lengths
89
+ max_heap: List[Tuple[int, int]] = [(-length, i) for i, length in enumerate(lengths)]
90
+ heapq.heapify(max_heap)
91
+
92
+ groups: List[List[Dict[str, torch.Tensor]]] = []
93
+ current_group: List[Dict[str, torch.Tensor]] = []
94
+ current_length: int = 0
95
+ while max_heap:
96
+ neg_length, i = heapq.heappop(max_heap)
97
+ length = -neg_length
98
+ if current_length + length <= group_size:
99
+ current_group.append(samples[i])
100
+ current_length += length
101
+ else:
102
+ groups.append(current_group)
103
+ current_group = [samples[i]]
104
+ current_length = length
105
+ # If we're at the end of the samples, add the last group
106
+ if current_group:
107
+ groups.append(current_group)
108
+ return groups
109
+
110
+ class VLMTaskEncoder(
111
+ DefaultTaskEncoder[
112
+ Union[VQASample],
113
+ dict,
114
+ dict,
115
+ dict,
116
+ ]
117
+ ):
118
+ def __init__(
119
+ self,
120
+ model_type: ModelType,
121
+ processor,
122
+ conversation_template_config: Optional[ConversationTemplateConfig] = None,
123
+ max_seq_length: Optional[int] = None,
124
+ ):
125
+ """Initialize VLMTaskEncoder.
126
+
127
+ Args:
128
+ model_name (str): Model name, currently only "llava_vlm" is supported.
129
+ processor: HuggingFace processor for the model.
130
+ conversation_template_config (Optional[ConversationTemplateConfig]): Configuration for conversation templates.
131
+ max_seq_length (Optional[int]): Maximum sequence length for packing. Should be sum of max_text_length
132
+ and image_seq_length. If None, defaults to 4096. This value is used as group_size for sequence packing.
133
+ """
134
+ self.model_type = model_type
135
+ # Use max_seq_length if provided, otherwise default to 4096
136
+ self.group_size = max_seq_length if max_seq_length is not None else 4096
137
+ self.processor = processor
138
+ self.conversation_template_config = conversation_template_config
139
+ # Read parallelism settings directly from training args (these live in TransformerConfig).
140
+ _args = get_args()
141
+ self._cp_size = getattr(_args, 'context_parallel_size', 1)
142
+ self._tp_size = getattr(_args, 'tensor_model_parallel_size', 1)
143
+ self._sequence_parallel = getattr(_args, 'sequence_parallel', False)
144
+
145
+ def apply_prompt_template(self, input_text: VQASample):
146
+ """Create conversation prompt string using HF chat template.
147
+
148
+ The first user turn always contains an image placeholder, later turns are text-only.
149
+ Returns a *prompt string* that can be fed into the processor together with an image.
150
+ """
151
+
152
+ user_msgs = input_text.context
153
+ bot_msgs = input_text.answers
154
+
155
+ def _ensure_list_type(value):
156
+ if isinstance(value, list):
157
+ return value
158
+ return [value]
159
+ user_msgs = _ensure_list_type(user_msgs)
160
+ bot_msgs = _ensure_list_type(bot_msgs)
161
+
162
+ conversation = []
163
+ for _, (u_txt, b_txt) in enumerate(zip(user_msgs, bot_msgs)):
164
+ conversation.append(
165
+ {
166
+ "role": "user",
167
+ "content": [{"type": "text", "text": u_txt}],
168
+ }
169
+ )
170
+ conversation.append(
171
+ {
172
+ "role": "assistant",
173
+ "content": [{"type": "text", "text": b_txt}],
174
+ }
175
+ )
176
+
177
+ # Inject optional system message
178
+ if (
179
+ self.conversation_template_config
180
+ and self.conversation_template_config.system
181
+ ):
182
+ conversation.insert(
183
+ 0,
184
+ {"role": "system", "content": self.conversation_template_config.system},
185
+ )
186
+
187
+ # Select chat template
188
+ if (
189
+ self.conversation_template_config
190
+ and self.conversation_template_config.chat_template
191
+ ):
192
+ self.processor.chat_template = (
193
+ self.conversation_template_config.chat_template
194
+ )
195
+ return self.processor.apply_chat_template(
196
+ conversation,
197
+ tokenize=False,
198
+ add_generation_prompt=False,
199
+ )
200
+
201
+
202
+ def _find_pattern_indices(
203
+ self, template, pattern, start_idx=0, allow_first_mismatch=False
204
+ ):
205
+ template_len = len(template)
206
+ pat_len = len(pattern)
207
+ for i in range(start_idx, template_len - pat_len + 1):
208
+ match = template[i : i + pat_len] == pattern
209
+ if torch.all(match) or (allow_first_mismatch and torch.all(match[1:])):
210
+ return i, i + pat_len
211
+ return -1, -1
212
+
213
+ def select_samples_to_pack(self, samples: List[Dict[str, torch.Tensor]]) -> List[List[Dict[str, torch.Tensor]]]:
214
+ """Selects which samples will be packed together.
215
+
216
+ This function receives a list of samples (size according to the selected packing_buffer_size),
217
+ and partitions those samples into groups that shall be packed together.
218
+
219
+ Args:
220
+ samples (List[Dict[str, torch.Tensor]]): List of samples from the buffer, each containing
221
+ tokenized data with keys like 'input_ids', 'labels', 'loss_mask', etc.
222
+
223
+ Returns:
224
+ List[List[Dict[str, torch.Tensor]]]: List of groups, where each group is a list of samples
225
+ that should be packed together. Each group's total length will not exceed group_size.
226
+
227
+ NOTE: Energon dataloader calls this method internally if packing is used.
228
+ Please see https://nvidia.github.io/Megatron-Energon/advanced/packing.html
229
+ """
230
+ # Group samples into groups of size group_size
231
+ lengths = [predict_seq_len_with_padding(sample["input_ids"]) for sample in samples]
232
+ # lengths = [sample["input_ids"].size(0) for sample in samples]
233
+ packed_samples = group_samples(samples, group_size=self.group_size, lengths=lengths)
234
+ return packed_samples
235
+
236
+ @stateless
237
+ def pack_selected_samples(self, samples: List[Dict[str, torch.Tensor]]) -> Dict[str, torch.Tensor]:
238
+ """Implements how a group of samples will be mapped to a single sample.
239
+
240
+ Args:
241
+ samples (List[Dict[str, torch.Tensor]]): List of samples to pack together.
242
+
243
+ Returns:
244
+ Dict[str, torch.Tensor]: Packed sample with keys like 'input_ids', 'labels', 'loss_mask', etc.
245
+ """
246
+ # Pad each sample to a multiple of 64, then concatenate
247
+ padded_input_ids = []
248
+ padded_labels = []
249
+ padded_loss_masks = []
250
+ padded_lens = []
251
+
252
+ has_labels = "labels" in samples[0] and samples[0]["labels"] is not None
253
+ has_loss_mask = "loss_mask" in samples[0] and samples[0]["loss_mask"] is not None
254
+
255
+ for sample in samples:
256
+ original_len = sample["input_ids"].size(0)
257
+ padded_len = predict_seq_len_with_padding(sample["input_ids"])
258
+ padded_lens.append(padded_len)
259
+ pad_amount = padded_len - original_len
260
+
261
+ padded_input_ids.append(torch.cat([
262
+ sample["input_ids"],
263
+ torch.zeros(pad_amount, dtype=sample["input_ids"].dtype)
264
+ ]))
265
+
266
+ if has_labels:
267
+ padded_labels.append(torch.cat([
268
+ sample["labels"],
269
+ torch.full((pad_amount,), -100, dtype=sample["labels"].dtype)
270
+ ]))
271
+
272
+ if has_loss_mask:
273
+ padded_loss_masks.append(torch.cat([
274
+ sample["loss_mask"],
275
+ torch.zeros(pad_amount, dtype=sample["loss_mask"].dtype)
276
+ ]))
277
+
278
+ # Concatenate sequences
279
+ input_ids = torch.cat(padded_input_ids)
280
+ labels = torch.cat(padded_labels) if has_labels else None
281
+ loss_mask = torch.cat(padded_loss_masks) if has_loss_mask else None
282
+
283
+ batched_images = torch.stack([s["pixel_values"] for s in samples], dim=0) # (B , C , H , W)
284
+
285
+ # Calculate padding if context parallel or sequence parallel is enabled
286
+ pad_len = 0
287
+ if self._cp_size > 1 or self._sequence_parallel:
288
+ pad_len = context_parallel.get_padding(
289
+ len(input_ids),
290
+ self._cp_size,
291
+ self._tp_size,
292
+ self._sequence_parallel,
293
+ )
294
+
295
+ # Pad sequences
296
+ if pad_len > 0:
297
+ input_ids = torch.cat([input_ids, torch.zeros(pad_len, dtype=input_ids.dtype)])
298
+ if labels is not None:
299
+ labels = torch.cat([labels, torch.full((pad_len,), -100, dtype=labels.dtype)])
300
+ if loss_mask is not None:
301
+ loss_mask = torch.cat([loss_mask, torch.zeros(pad_len, dtype=loss_mask.dtype)])
302
+
303
+ # Generate position_ids after padding
304
+ position_ids = torch.arange(len(input_ids))
305
+
306
+ # Calculate cu_seqlens using padded lengths
307
+ lens = torch.tensor(padded_lens, dtype=torch.int32)
308
+ cu_seqlens = torch.cat([torch.tensor([0], dtype=torch.int32), torch.cumsum(lens, dim=0)])
309
+
310
+ # Calculate padded sequence lengths and cu_seqlens
311
+ seqlens_padded = [l.item() + pad_len for l in lens]
312
+ cu_seqlens_padded = torch.cat([torch.tensor([0], dtype=torch.int32), torch.cumsum(torch.tensor(seqlens_padded, dtype=torch.int32), dim=0)])
313
+
314
+ packing_kwargs = {
315
+ "cu_seqlens_q": cu_seqlens,
316
+ "cu_seqlens_kv": cu_seqlens,
317
+ "cu_seqlens_q_padded": cu_seqlens_padded,
318
+ "cu_seqlens_kv_padded": cu_seqlens_padded,
319
+ "max_seqlen_q": torch.tensor(max(seqlens_padded), dtype=torch.int32),
320
+ "max_seqlen_kv": torch.tensor(max(seqlens_padded), dtype=torch.int32),
321
+ }
322
+
323
+ packed_result = {
324
+ "input_ids": input_ids,
325
+ "labels": labels,
326
+ "loss_mask": loss_mask,
327
+ "pixel_values": batched_images,
328
+ "position_ids": position_ids,
329
+ "packing_kwargs": packing_kwargs,
330
+ }
331
+
332
+ return packed_result
333
+
334
+ @stateless
335
+ def encode_sample(self, sample: VQASample):
336
+ """Return tokenised multimodal sample."""
337
+ # Build prompt
338
+ prompt = self.apply_prompt_template(sample)
339
+ logging.debug(f"prompt: {prompt}")
340
+
341
+ # Process image + prompt
342
+ inputs = self.processor(
343
+ images=getattr(sample, "image", None),
344
+ text=prompt,
345
+ add_special_tokens=False,
346
+ return_tensors="pt",
347
+ do_rescale=False,
348
+ )
349
+
350
+ # Remove batch dim
351
+ for k, v in inputs.items():
352
+ inputs[k] = v.squeeze(0)
353
+
354
+
355
+ answers = sample.answers
356
+ if answers:
357
+ if not isinstance(answers, list):
358
+ answers = [answers]
359
+ tokenizer = self.processor.tokenizer
360
+ inputs["labels"] = torch.full_like(inputs["input_ids"], fill_value=-100)
361
+ search_idx = 0
362
+ for ans in answers:
363
+ answer_tokens = tokenizer.encode(
364
+ ans, add_special_tokens=False, return_tensors="pt"
365
+ )[0]
366
+ s_idx, e_idx = self._find_pattern_indices(
367
+ inputs["input_ids"], answer_tokens, search_idx
368
+ )
369
+ if s_idx == -1:
370
+ raise ValueError(f"Answer not found in input_ids: {ans}")
371
+ inputs["labels"][s_idx:e_idx] = inputs["input_ids"][s_idx:e_idx]
372
+ search_idx = e_idx
373
+
374
+ # shift inputs and labels by 1
375
+ inputs["input_ids"] = inputs["input_ids"][:-1]
376
+ inputs["labels"] = inputs["labels"][1:]
377
+ inputs["loss_mask"] = (inputs["labels"] != -100).long()
378
+
379
+ else:
380
+ inputs["labels"] = None
381
+ inputs["loss_mask"] = None
382
+
383
+ return inputs
384
+
385
+ def batch(self, samples: List[Dict]) -> Dict:
386
+ """Pad/stack individual samples into a single batch dict."""
387
+ if not samples:
388
+ return {}
389
+
390
+ batched: Dict[str, torch.Tensor] = {}
391
+ keys = samples[0].keys()
392
+ is_packed_sample = "packing_kwargs" in samples[0]
393
+ for key in keys:
394
+ values = [s[key] for s in samples if key in s and s[key] is not None]
395
+
396
+ processor = KEY_PROCESSORS.get(key)
397
+ if processor is not None:
398
+ batched[key] = processor(values, max_len=self.group_size, is_packed_sample=is_packed_sample)
399
+ continue
400
+
401
+ # Fallback behaviours if no specific processor is registered.
402
+ if isinstance(values[0], torch.Tensor):
403
+ batched[key] = torch.stack(values, dim=0)
404
+ else:
405
+ batched[key] = values
406
+
407
+ # Add context parallel padding if enabled
408
+ if self._cp_size > 1:
409
+ seq_len = batched["input_ids"].size(1)
410
+ pad_len = context_parallel.get_padding(
411
+ seq_len,
412
+ self._cp_size,
413
+ self._tp_size,
414
+ self._sequence_parallel,
415
+ )
416
+ if pad_len > 0:
417
+ # Pad input_ids
418
+ batched["input_ids"] = torch.cat([
419
+ batched["input_ids"],
420
+ torch.zeros(batched["input_ids"].size(0), pad_len, dtype=batched["input_ids"].dtype)
421
+ ], dim=1)
422
+ # Pad labels
423
+ if "labels" in batched:
424
+ batched["labels"] = torch.cat([
425
+ batched["labels"],
426
+ torch.full((batched["labels"].size(0), pad_len), -100, dtype=batched["labels"].dtype)
427
+ ], dim=1)
428
+ # Pad loss_mask
429
+ if "loss_mask" in batched:
430
+ batched["loss_mask"] = torch.cat([
431
+ batched["loss_mask"],
432
+ torch.zeros(batched["loss_mask"].size(0), pad_len, dtype=batched["loss_mask"].dtype)
433
+ ], dim=1)
434
+
435
+ return batched
436
+
437
+ def encode_batch_vlm_clip_llava(self, batch_data: Dict) -> Dict:
438
+ input_ids = batch_data["input_ids"]
439
+ labels = batch_data.get("labels")
440
+ loss_mask = batch_data.get("loss_mask")
441
+
442
+ # Handle packed-sample case where input_ids is 1-D
443
+ if input_ids.dim() == 1:
444
+ input_ids = input_ids.unsqueeze(0) # add batch dimension
445
+ if labels is not None and labels.dim() == 1:
446
+ labels = labels.unsqueeze(0)
447
+ if loss_mask is not None and loss_mask.dim() == 1:
448
+ loss_mask = loss_mask.unsqueeze(0)
449
+
450
+ seq_len = input_ids.size(1)
451
+ position_ids = torch.arange(seq_len, dtype=torch.long, device=input_ids.device)
452
+ position_ids = position_ids.unsqueeze(0).repeat(input_ids.size(0), 1)
453
+ pixel_values = batch_data.get("pixel_values")
454
+
455
+ output = {
456
+ "input_ids": input_ids,
457
+ "labels": labels,
458
+ "loss_mask": loss_mask,
459
+ "position_ids": position_ids,
460
+ }
461
+
462
+ if pixel_values is not None:
463
+ output["modality_inputs"] = {
464
+ "images": {"clip_encoder": {"pixel_values": pixel_values}}
465
+ }
466
+
467
+ return output
468
+
469
+ def encode_batch_vlm_clip_llava_video(self, batch_data: Dict) -> Dict:
470
+ input_ids = batch_data["input_ids"]
471
+ labels = batch_data.get("labels")
472
+ loss_mask = batch_data.get("loss_mask")
473
+
474
+ seq_len = input_ids.size(1)
475
+ position_ids = torch.arange(seq_len, dtype=torch.long, device=input_ids.device)
476
+ position_ids = position_ids.unsqueeze(0).repeat(input_ids.size(0), 1)
477
+
478
+ pixel_values_videos = batch_data.get("pixel_values_videos")
479
+
480
+ output = {
481
+ "input_ids": input_ids,
482
+ "labels": labels,
483
+ "loss_mask": loss_mask,
484
+ "position_ids": position_ids,
485
+ }
486
+
487
+ if pixel_values_videos is not None:
488
+ output["modality_inputs"] = {
489
+ "images": {"clip_encoder": {"pixel_values": pixel_values_videos}}
490
+ }
491
+
492
+ return output
493
+
494
+ def encode_batch(self, batch_data: Dict) -> dict:
495
+ if self.model_type is ModelType.LLAVA_VLM:
496
+ return self.encode_batch_vlm_clip_llava(batch_data)
497
+ elif self.model_type is ModelType.VIDEO_LLAVA_VLM:
498
+ return self.encode_batch_vlm_clip_llava_video(batch_data)
499
+ else:
500
+ raise ValueError(f"Model type {self.model_type} not supported")
501
+
502
+ def llava_vlm_dataloader_provider(train_val_test_num_samples, max_seq_length: Optional[int] = None, is_video_input: bool = False):
503
+ args = get_args()
504
+ tokenizer_model_id = args.tokenizer_model
505
+ processor = AutoProcessor.from_pretrained(tokenizer_model_id)
506
+ if is_video_input:
507
+ model_type = ModelType.VIDEO_LLAVA_VLM
508
+ else:
509
+ model_type = ModelType.LLAVA_VLM
510
+ return train_valid_test_dataloaders_provider(
511
+ train_val_test_num_samples,
512
+ task_encoder=VLMTaskEncoder(
513
+ model_type=model_type,
514
+ processor=processor,
515
+ conversation_template_config=LlavaConversationTemplateConfig(),
516
+ max_seq_length=max_seq_length,
517
+ )
518
+ )
519
+
520
+
521
+ if __name__ == "__main__":
522
+
523
+ parser = argparse.ArgumentParser()
524
+ parser.add_argument(
525
+ "--data_path",
526
+ type=str,
527
+ required=True,
528
+ help="path to the dataset directory in energon format",
529
+ )
530
+ parser.add_argument('--total-seq-length', type=int, default=512, help='Maximum text length')
531
+ parser.add_argument('--image-seq-length', type=int, default=197, help='Number of image tokens')
532
+ parser.add_argument('--packing-buffer-size', type=int, default=None, help='Packing buffer size when using sequence packing')
533
+ args = parser.parse_args()
534
+
535
+ # Calculate max_seq_length as sum of text and image sequence lengths
536
+ max_seq_length = args.max_text_length + args.image_seq_length
537
+
538
+ model_name = "llava-hf/llava-1.5-7b-hf"
539
+
540
+ processor = AutoProcessor.from_pretrained(model_name)
541
+ worker_config = WorkerConfig.default_worker_config(0)
542
+ train_loader = get_loader(
543
+ get_train_dataset(
544
+ args.data_path,
545
+ batch_size=8,
546
+ shuffle_buffer_size=None,
547
+ max_samples_per_sequence=None,
548
+ task_encoder=VLMTaskEncoder(
549
+ model_type=ModelType.LLAVA_VLM,
550
+ processor=processor,
551
+ conversation_template_config=LlavaConversationTemplateConfig(),
552
+ max_seq_length=max_seq_length, # Use calculated max_seq_length
553
+ ),
554
+ worker_config=worker_config,
555
+ ),
556
+ worker_config=worker_config,
557
+ )
558
+
559
+ print(f"data loader length {len(train_loader)}")
560
+ for index, each_batch in enumerate(train_loader):
561
+ print(
562
+ f"batch index {index} tokens {each_batch['input_ids']} images shape \
563
+ {each_batch['modality_inputs']['images']['clip_encoder']['pixel_values'].shape}"
564
+ )
565
+ break
566
+
567
+
568
+ # -----------------------------------------------------------------------------
569
+ # Key processing utilities for batching
570
+ # -----------------------------------------------------------------------------
571
+
572
+
573
+ class KeyProcessor(Protocol):
574
+ """Callable that aggregates a list of tensors into a single batched tensor."""
575
+
576
+ def __call__(self, values: List[torch.Tensor], max_len: Optional[int] = None, is_packed_sample: bool = False) -> torch.Tensor: # pragma: no cover
577
+ ...
578
+
579
+
580
+ class StackProcessor:
581
+ """Simply stack tensors along a given dimension."""
582
+
583
+ def __init__(self, dim: int = 0):
584
+ self.dim = dim
585
+
586
+ def __call__(self, values: List[torch.Tensor], max_len: Optional[int] = None, is_packed_sample: bool = False) -> torch.Tensor:
587
+ if values[0].dim() == 3:
588
+ return torch.stack(values, dim=self.dim) # (B , C , H , W)
589
+ else:
590
+ # Concatenate already-batched image tensors along the batch dimension.
591
+ return torch.cat(values, dim=self.dim) # (B , C , H , W)
592
+
593
+
594
+ class PaddingProcessor:
595
+ """Pad variable-length sequences to the same length."""
596
+
597
+ def __init__(self, pad_value: int, batch_first: bool = True):
598
+ self.pad_value = pad_value
599
+ self.batch_first = batch_first
600
+
601
+ def _pad_and_stack(self, tensors: List[torch.Tensor], max_len: int, pad_val: int) -> torch.Tensor:
602
+ """Pad or truncate a list of 1D tensors to a fixed length and stack them."""
603
+ padded_tensors = []
604
+ for t in tensors:
605
+ current_len = t.size(0)
606
+ if current_len > max_len:
607
+ # Truncate
608
+ padded_tensors.append(t[:max_len])
609
+ else:
610
+ # Pad
611
+ pad_amount = max_len - current_len
612
+ padding = torch.full((pad_amount,), pad_val, dtype=t.dtype, device=t.device)
613
+ padded_tensors.append(torch.cat([t, padding]))
614
+ return torch.stack(padded_tensors, dim=0)
615
+
616
+ def __call__(self, values: List[torch.Tensor], max_len: Optional[int] = None, is_packed_sample: bool = False) -> torch.Tensor:
617
+ if is_packed_sample:
618
+ return rnn_utils.pad_sequence(
619
+ values, batch_first=self.batch_first, padding_value=self.pad_value
620
+ )
621
+ else:
622
+ return self._pad_and_stack(values, max_len, self.pad_value)
623
+
624
+ class PackingKwargsProcessor:
625
+ """Extract the value at first index for packing_kwargs"""
626
+
627
+ def __call__(self, values: List[torch.Tensor], max_len: Optional[int] = None, is_packed_sample: bool = False) -> torch.Tensor:
628
+ if len(values) == 1:
629
+ return values[0]
630
+ else:
631
+ raise ValueError("Multiple packing_kwargs found in batch; expected only one per batch.")
632
+
633
+ class GenericStackProcessor:
634
+
635
+ def __init__(self, dim: int = 0):
636
+ self.dim = dim
637
+
638
+ def __call__(self, values: List[torch.Tensor], max_len: Optional[int] = None, is_packed_sample: bool = False) -> torch.Tensor:
639
+ # Generic stacking for other tensor fields
640
+ if isinstance(values[0], torch.Tensor):
641
+ return torch.stack(values, dim=self.dim)
642
+ else:
643
+ return values
644
+
645
+ # Registry mapping sample keys to their corresponding processor.
646
+ KEY_PROCESSORS: Dict[str, KeyProcessor] = {
647
+ "pixel_values": StackProcessor(),
648
+ "pixel_values_videos": StackProcessor(),
649
+ "input_ids": PaddingProcessor(pad_value=0),
650
+ "attention_mask": PaddingProcessor(pad_value=0),
651
+ "loss_mask": PaddingProcessor(pad_value=0),
652
+ "labels": PaddingProcessor(pad_value=-100),
653
+ "packing_kwargs": PackingKwargsProcessor(),
654
+ }
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/data/mock.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+ """
3
+ Simple mock data module for testing MIMO with image-text (VLM) models.
4
+
5
+ This module provides basic synthetic data generation for testing Vision Language Models
6
+ within the MIMO framework.
7
+ """
8
+
9
+ from typing import Callable, Dict, List, Optional
10
+
11
+ import torch
12
+ from torch.utils.data import DataLoader, Dataset
13
+
14
+
15
+ def create_mock_image(image_size: int = 336) -> torch.Tensor:
16
+ """
17
+ Create a simple mock image (all zeros).
18
+
19
+ Args:
20
+ image_size: Size of the square image
21
+
22
+ Returns:
23
+ Tensor of shape [3, H, W] with all zeros
24
+ """
25
+ return torch.zeros(3, image_size, image_size)
26
+
27
+
28
+ def create_mock_caption() -> str:
29
+ """
30
+ Create a simple mock caption.
31
+
32
+ Returns:
33
+ A simple caption string
34
+ """
35
+ return "This is an image."
36
+
37
+
38
+ class MockVLMDataset(Dataset):
39
+ """Simple dataset of mock image-text pairs for VLM testing."""
40
+
41
+ def __init__(
42
+ self,
43
+ size: int = 10000,
44
+ image_size: int = 336,
45
+ seq_len: int = 512,
46
+ image_seq_length: int = 32,
47
+ vocab_size: int = 256,
48
+ tokenizer: Optional[Callable] = None,
49
+ pad_token_id: int = 0,
50
+ image_token_id: int = 32000,
51
+ ):
52
+ """
53
+ Initialize the mock VLM dataset.
54
+
55
+ Args:
56
+ size: Number of examples in the dataset
57
+ image_size: Size of the square images
58
+ seq_len: Total length of the token sequence (image + text)
59
+ image_seq_length: Number of image tokens to pad
60
+ vocab_size: Size of the vocabulary for tokenization
61
+ tokenizer: Optional tokenizer function
62
+ pad_token_id: ID for padding token
63
+ image_token_id: ID for image placeholder token
64
+ """
65
+ self.size = size
66
+ self.image_size = image_size
67
+ self.seq_len = seq_len
68
+ self.image_seq_length = image_seq_length
69
+ self.vocab_size = vocab_size
70
+ self.tokenizer = tokenizer
71
+
72
+ # Special token IDs
73
+ self.pad_token_id = pad_token_id
74
+ self.image_token_id = image_token_id
75
+
76
+ if self.seq_len < self.image_seq_length:
77
+ raise ValueError(
78
+ f"seq_len ({self.seq_len}) must be >= image_seq_length ({self.image_seq_length})."
79
+ )
80
+
81
+ def __len__(self) -> int:
82
+ """Return the size of the dataset."""
83
+ return self.size
84
+
85
+ def __getitem__(self, idx: int) -> Dict:
86
+ """
87
+ Get an item from the dataset.
88
+
89
+ Args:
90
+ idx: Index of the item (ignored, all items are identical)
91
+
92
+ Returns:
93
+ Dictionary containing:
94
+ - images: Tensor of shape [C, H, W]
95
+ - input_ids: Tokenized caption with image token
96
+ - labels: Shifted input_ids for language modeling
97
+ - loss_mask: Mask for loss calculation
98
+ - position_ids: Position IDs for the tokens
99
+ """
100
+ # Create a zero image
101
+ image = create_mock_image(self.image_size)
102
+
103
+ # Generate random token sequence for this sample.
104
+ input_ids = self._mock_tokenize()
105
+
106
+ # Create labels (shifted input_ids)
107
+ labels = input_ids.clone()
108
+ labels[:-1] = input_ids[1:]
109
+ labels[-1] = self.pad_token_id # Padding for the last position
110
+
111
+ # Set labels for image tokens to -100 (ignored in loss calculation)
112
+ labels[input_ids == self.image_token_id] = -100
113
+
114
+ # Create loss mask (1 for tokens to calculate loss on, 0 for others)
115
+ loss_mask = torch.ones_like(input_ids).float()
116
+ loss_mask[input_ids == self.pad_token_id] = 0.0 # Don't calculate loss on padding
117
+ loss_mask[input_ids == self.image_token_id] = 0.0 # Don't calculate loss on image tokens
118
+
119
+ # Create position IDs (just sequential integers)
120
+ position_ids = torch.arange(len(input_ids), dtype=torch.long)
121
+
122
+ return {
123
+ "input_ids": input_ids,
124
+ "labels": labels,
125
+ "loss_mask": loss_mask,
126
+ "position_ids": position_ids,
127
+ "modality_inputs": {
128
+ "clip_encoder": {
129
+ "images": image,
130
+ }
131
+ },
132
+ }
133
+
134
+ def _mock_tokenize(self) -> torch.Tensor:
135
+ """
136
+ Generate a mock token sequence consisting of ``image_seq_length`` image tokens followed by
137
+ randomly generated text tokens such that the total sequence length equals
138
+ ``self.seq_len``.
139
+
140
+ Returns:
141
+ torch.Tensor: Tensor of token IDs of shape ``[seq_len]``.
142
+ """
143
+
144
+ # Image placeholder tokens ─ placed at the beginning of the sequence to mimic
145
+ # the layout produced by many VLM tokenizers.
146
+ image_tokens = torch.full(
147
+ (self.image_seq_length,), self.image_token_id, dtype=torch.long
148
+ )
149
+
150
+ # Random text tokens drawn uniformly in ``[1, vocab_size)`` (we reserve ``0`` for pad).
151
+ num_text_tokens = self.seq_len - self.image_seq_length
152
+ text_tokens = torch.randint(
153
+ low=1,
154
+ high=self.vocab_size,
155
+ size=(num_text_tokens,),
156
+ dtype=torch.long,
157
+ )
158
+
159
+ # Concatenate to form the full sequence.
160
+ token_ids = torch.cat((image_tokens, text_tokens), dim=0)
161
+
162
+ return token_ids
163
+
164
+
165
+ def get_mock_vlm_dataloader(
166
+ batch_size: int = 8,
167
+ dataset_size: int = 100,
168
+ image_size: int = 224,
169
+ seq_len: int = 77,
170
+ image_seq_length: int = 32,
171
+ num_workers: int = 0,
172
+ pad_token_id: int = 0,
173
+ image_token_id: int = 50000,
174
+ ) -> DataLoader:
175
+ """
176
+ Create a DataLoader for mock VLM data.
177
+
178
+ Args:
179
+ batch_size: Batch size
180
+ dataset_size: Size of the dataset
181
+ image_size: Size of the square images
182
+ seq_len: Total length of the token sequence (image + text)
183
+ image_seq_length: Number of image tokens to pad
184
+ num_workers: Number of worker processes for data loading
185
+ pad_token_id: ID for padding token
186
+ image_token_id: ID for image placeholder token
187
+
188
+ Returns:
189
+ DataLoader for the mock VLM dataset
190
+ """
191
+ dataset = MockVLMDataset(
192
+ size=dataset_size,
193
+ image_size=image_size,
194
+ seq_len=seq_len,
195
+ image_seq_length=image_seq_length,
196
+ pad_token_id=pad_token_id,
197
+ image_token_id=image_token_id,
198
+ )
199
+
200
+ dataloader = DataLoader(
201
+ dataset,
202
+ batch_size=batch_size,
203
+ shuffle=True,
204
+ num_workers=num_workers,
205
+ collate_fn=lambda batch: _collate_fn(batch),
206
+ )
207
+
208
+ return dataloader
209
+
210
+
211
+ def _collate_fn(batch: List[Dict]) -> Dict[str, torch.Tensor]:
212
+ """
213
+ Collate function for the DataLoader.
214
+
215
+ Args:
216
+ batch: List of dictionaries from the dataset
217
+
218
+ Returns:
219
+ Dictionary of batched tensors
220
+ """
221
+ images = torch.stack([item["images"] for item in batch])
222
+ input_ids = torch.stack([item["input_ids"] for item in batch])
223
+ labels = torch.stack([item["labels"] for item in batch])
224
+ loss_mask = torch.stack([item["loss_mask"] for item in batch])
225
+ position_ids = torch.stack([item["position_ids"] for item in batch])
226
+
227
+ return {
228
+ "input_ids": input_ids,
229
+ "labels": labels,
230
+ "loss_mask": loss_mask,
231
+ "position_ids": position_ids,
232
+ "modality_inputs": {
233
+ "clip_encoder": {
234
+ "images": images,
235
+ }
236
+ },
237
+ }
238
+
239
+
240
+ def train_valid_test_datasets_provider(train_val_test_num_samples):
241
+ """Provide datasets for training, validation, and testing."""
242
+ from megatron.core import mpu
243
+ from megatron.training import get_args
244
+
245
+ args = get_args()
246
+
247
+ # Print some info to confirm args are available
248
+ print(f"Creating datasets with batch size: {args.micro_batch_size}")
249
+ print(f"Image size: {args.image_size}")
250
+ print(f"Image sequence length: {args.image_seq_length}")
251
+ print(f"Total sequence length: {args.total_seq_length}")
252
+
253
+ # Only build dataset on tensor parallel rank 0
254
+ if mpu.get_tensor_model_parallel_rank() == 0:
255
+
256
+ from examples.mimo.data.mock import MockVLMDataset
257
+
258
+ train_dataset = MockVLMDataset(
259
+ size=train_val_test_num_samples[0],
260
+ image_size=args.image_size,
261
+ seq_len=args.total_seq_length,
262
+ image_seq_length=args.image_seq_length,
263
+ pad_token_id=args.pad_token_id,
264
+ image_token_id=args.image_token_id,
265
+ )
266
+
267
+ # Use the same dataset type for validation
268
+ valid_dataset = MockVLMDataset(
269
+ size=train_val_test_num_samples[1] if train_val_test_num_samples[1] > 0 else 100,
270
+ image_size=args.image_size,
271
+ seq_len=args.total_seq_length,
272
+ image_seq_length=args.image_seq_length,
273
+ pad_token_id=args.pad_token_id,
274
+ image_token_id=args.image_token_id,
275
+ )
276
+
277
+ # No test dataset for now
278
+ test_dataset = None
279
+ else:
280
+ train_dataset = None
281
+ valid_dataset = None
282
+ test_dataset = None
283
+
284
+ return train_dataset, valid_dataset, test_dataset
285
+
286
+ if __name__ == "__main__":
287
+ print("\nCreating mock VLM dataloader...")
288
+ dataloader = get_mock_vlm_dataloader(batch_size=4, dataset_size=10)
289
+
290
+ print(f"DataLoader has {len(dataloader)} batches")
291
+
292
+ for batch in dataloader:
293
+ print("\nBatch from dataloader:")
294
+ for key, tensor in batch.items():
295
+ print(f" {key}: {tensor.shape}")
296
+ break
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/data/prepare_video_llava_data.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import json
3
+ import os
4
+ import tarfile
5
+
6
+ import webdataset as wds
7
+ from huggingface_hub import snapshot_download
8
+ from tqdm import tqdm
9
+
10
+
11
+ def _extract_archives(root: str):
12
+ """Extract every .tar / .tar.gz archive found under *root* into its directory."""
13
+ archives = glob.glob(os.path.join(root, "**", "*.tar*"), recursive=True)
14
+ for arch in archives:
15
+ try:
16
+ print(f"Extracting {arch} …")
17
+ with tarfile.open(arch, "r:*") as tf:
18
+ tf.extractall(path=os.path.dirname(arch))
19
+ except Exception as e:
20
+ print(f"[WARN] Failed to extract {arch}: {e}")
21
+
22
+
23
+ def convert_llava_video_to_wds(dataset_root: str, shard_size: int = 8000):
24
+ """Convert a LLaVA-Video dataset (keys: video, conversations, data_source) to WebDataset format.
25
+
26
+ The function walks through every *.json / *.jsonl annotation file located under *dataset_root*,
27
+ finds the referenced video files, and writes shards (<dataset_root>/wds/video-000000.tar …).
28
+ """
29
+ # ensure archives extracted so that video files are accessible
30
+ _extract_archives(dataset_root)
31
+
32
+ output_dir = os.path.join(dataset_root, "wds")
33
+ os.makedirs(output_dir, exist_ok=True)
34
+
35
+ # gather annotation files (skip the output directory itself)
36
+ annotation_files = [
37
+ p
38
+ for p in glob.glob(os.path.join(dataset_root, "**", "*.json*"), recursive=True)
39
+ if not os.path.commonpath([p, output_dir]) == output_dir
40
+ ]
41
+ if not annotation_files:
42
+ raise FileNotFoundError(f"No annotation JSON files found in {dataset_root}")
43
+
44
+ print(f"Found annotation files - {annotation_files}")
45
+
46
+ shard_pattern = os.path.join(output_dir, "video-%06d.tar")
47
+ sample_idx = 0
48
+ with wds.ShardWriter(shard_pattern, maxcount=shard_size) as sink:
49
+ for ann_path in annotation_files:
50
+ print(f"Processing {ann_path} …")
51
+ with open(ann_path, "r") as f:
52
+ first = f.read(1)
53
+ f.seek(0)
54
+ entries = json.load(f) if first == "[" else [json.loads(line) for line in f if line.strip()]
55
+ for entry in tqdm(entries):
56
+ video_rel = entry.get("video")
57
+ conversations = entry.get("conversations")
58
+ if video_rel is None or conversations is None:
59
+ continue
60
+
61
+ video_path = video_rel if os.path.isabs(video_rel) else os.path.join(dataset_root, video_rel)
62
+
63
+ if not os.path.exists(video_path):
64
+ print(f"Video file not found: {video_path}")
65
+ # or raise an error
66
+ continue
67
+
68
+ try:
69
+ with open(video_path, "rb") as vf:
70
+ video_bytes = vf.read()
71
+ except Exception:
72
+ continue
73
+
74
+ key = f"{sample_idx:09d}"
75
+ ext = os.path.splitext(video_path)[1].lstrip(".").lower() or "mp4"
76
+ sample = {
77
+ "__key__": key,
78
+ ext: video_bytes,
79
+ "json": json.dumps(conversations).encode(),
80
+ }
81
+ if entry.get("data_source"):
82
+ sample["src.txt"] = str(entry["data_source"]).encode()
83
+
84
+ sink.write(sample)
85
+ sample_idx += 1
86
+
87
+ print(f"Finished writing {sample_idx} samples → {output_dir}")
88
+
89
+
90
+ if __name__ == "__main__":
91
+ # download dataset
92
+ dataset_name = "lmms-lab/LLaVA-Video-178K"
93
+
94
+ # specific subset to download
95
+ subset = "0_30_s_academic_v0_1"
96
+
97
+ dataset_root = snapshot_download(
98
+ repo_id=dataset_name,
99
+ repo_type="dataset",
100
+ local_dir_use_symlinks=False,
101
+ resume_download=True,
102
+ allow_patterns=[f"{subset}/*", f"{subset}.*"],
103
+ )
104
+ print(f"dataset downloaded to: {dataset_root}")
105
+ # convert to webdataset
106
+ convert_llava_video_to_wds(f"{dataset_root}/{subset}")
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/data/utils/calculate_audio_tokens.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from types import SimpleNamespace
4
+
5
+ # Model-specific audio processing parameters
6
+ AUDIO_MODEL_PARAMS = {
7
+ "openai/whisper-base": {
8
+ "model_type": "whisper",
9
+ "sample_rate": 16000, # 16kHz
10
+ "window_stride": 0.01, # 10ms
11
+ "encoder_down_sampling": 2,
12
+ "d_model": 512,
13
+ "max_length_seconds": 30.0,
14
+ },
15
+ }
16
+
17
+
18
+ def calculate_num_mel_frames(audio_length, sample_rate, window_stride, window_length=None):
19
+ """
20
+ Calculate the number of mel frames from an audio signal.
21
+
22
+ Parameters:
23
+ - audio_length (int): Total number of audio samples.
24
+ - sample_rate (int or float): Sampling rate of the audio (samples per second).
25
+ - window_stride (float): The time (in seconds) between successive frames.
26
+ - window_length (float, optional): Window length in seconds. If provided, this function
27
+ uses the standard formula: floor((N - window_length_in_samples) / hop_length) + 1.
28
+ Otherwise, it uses the simplified calculation based on the window stride only.
29
+
30
+ Returns:
31
+ - int: The number of mel frames.
32
+ """
33
+ hop_length_samples = int(window_stride * sample_rate)
34
+
35
+ if window_length is None:
36
+ num_frames = math.ceil((audio_length + 1) / hop_length_samples)
37
+ else:
38
+ window_length_samples = int(window_length * sample_rate)
39
+ num_frames = math.floor((audio_length - window_length_samples) / hop_length_samples) + 1
40
+
41
+ return num_frames
42
+
43
+
44
+ def calculate_num_audio_tokens(audio_tensor, model_name):
45
+
46
+ # Get audio length in samples
47
+ audio_length = audio_tensor.shape[1]
48
+
49
+ # Get model parameters
50
+ if model_name in AUDIO_MODEL_PARAMS:
51
+ model_params = SimpleNamespace(**AUDIO_MODEL_PARAMS[model_name])
52
+ model_type = model_params.model_type
53
+ else:
54
+ raise ValueError(f"Unsupported model name: {model_name}")
55
+
56
+
57
+ if model_type == "whisper":
58
+ num_mel_frames = calculate_num_mel_frames(
59
+ audio_length, model_params.sample_rate, model_params.window_stride
60
+ )
61
+ encoder_seq_length = math.ceil(num_mel_frames / model_params.encoder_down_sampling)
62
+ else:
63
+ raise ValueError(f"Unsupported model type: {model_type}")
64
+
65
+ return max(1, int(encoder_seq_length))
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/model_providers/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/model_providers/hf_clip_encoder.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+
3
+ import torch
4
+ from transformers import CLIPVisionModel, LlavaNextVideoConfig
5
+ from transformers.models.llava_next_video.modeling_llava_next_video import (
6
+ LlavaNextVideoPooler,
7
+ )
8
+
9
+
10
+ class HFCLIPEncoderWrapper(torch.nn.Module):
11
+ """CLIP encoder wrapper that extracts last_hidden_state."""
12
+
13
+ def __init__(self, feature_layer_index=-2, is_video_input: bool = False):
14
+ """Initialize the HFCLIPEncoderWrapper.
15
+
16
+ Args:
17
+ feature_layer_index (int): Index of the feature layer to extract from the encoder's hidden states.
18
+ Default is -2 (second to last layer).
19
+ is_video_input (bool): If True, expects video input and applies vision resampler.
20
+ """
21
+ super().__init__()
22
+ self.encoder = CLIPVisionModel.from_pretrained('openai/clip-vit-large-patch14-336')
23
+ self.encoder.eval()
24
+ self.feature_layer_index = feature_layer_index
25
+ self.is_video_input = is_video_input
26
+ if self.is_video_input:
27
+ config = LlavaNextVideoConfig()
28
+ self.vision_resampler = LlavaNextVideoPooler(config)
29
+
30
+ def forward(self, pixel_values: torch.Tensor):
31
+ """Input: (B, F, 3, 336, 336) if video, else (B, 3, 336, 336) or (num_frames, 3, 336, 336)."""
32
+ # Process through encoder and extract last_hidden_state
33
+ with torch.no_grad():
34
+ if self.is_video_input:
35
+ batch_size, frames, channels, height, width = pixel_values.shape
36
+ pixel_values = pixel_values.reshape(batch_size * frames, channels, height, width)
37
+
38
+
39
+ last_hidden_state = self.encoder(pixel_values, output_hidden_states=True)
40
+ # -1 index is image features
41
+ image_features = last_hidden_state[-1]
42
+ # select last but second layer
43
+ image_features = image_features[self.feature_layer_index]
44
+ # drop cls token
45
+ image_features = image_features[:, 1:, :]
46
+ if self.is_video_input:
47
+ image_features = self.vision_resampler(image_features)
48
+ return image_features
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/model_providers/hf_whisper_encoder.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+
3
+ import torch
4
+ from transformers import WhisperConfig, WhisperModel
5
+
6
+ class HFWhisperEncoderWrapper(torch.nn.Module):
7
+ """Whisper audio encoder wrapper that extracts last_hidden_state."""
8
+
9
+ def __init__(self, model_name: str):
10
+ super().__init__()
11
+ self.encoder = WhisperModel.from_pretrained(model_name).encoder
12
+
13
+ def forward(self, input_features, seq_lengths=None):
14
+ '''
15
+ input_features: torch.Tensor
16
+ input audio features
17
+ seq_lengths: torch.Tensor
18
+ the number of audio tokens corresponding to non-padded audio frames
19
+ we only get the embeddings for the non-padded audio frames
20
+ '''
21
+ with torch.no_grad():
22
+ hidden = self.encoder(input_features).last_hidden_state # [b, s, h]
23
+ if seq_lengths is not None:
24
+ seq_len = hidden.shape[1]
25
+ mask = torch.arange(seq_len, device=hidden.device)[None, :] < seq_lengths[:, None]
26
+ hidden = hidden[mask]
27
+ return hidden
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/model_providers/llava_avlm.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+ """Model provider for a LLaVA-style Vision-Language Model.
3
+
4
+ This provider assembles a MIMO model that consists of:
5
+ • Vicuna-7B language model (Llama-based) built with Transformer-Engine GPT blocks.
6
+ • CLIP ViT-L/14 visual encoder (336 px) that produces image patch embeddings.
7
+ • A 2-layer MLP projector that maps vision embeddings into Vicuna hidden size.
8
+ """
9
+
10
+
11
+ import torch
12
+ from configs.llava_avlm import (
13
+ get_llava_projection_config,
14
+ get_llava_projection_layer_spec,
15
+ get_vicuna_language_layer_spec,
16
+ get_vicuna_language_model_config,
17
+ )
18
+
19
+ from examples.mimo.model_providers.hf_clip_encoder import HFCLIPEncoderWrapper
20
+ from examples.mimo.model_providers.hf_whisper_encoder import HFWhisperEncoderWrapper
21
+ from examples.mimo.utils.logging import print_mimo_structure
22
+ from examples.mimo.utils.model_helpers import load_submodule_ckpt
23
+ from megatron.core.models.gpt.gpt_model import GPTModel
24
+ from megatron.core.models.mimo import MimoModel, MimoModelConfig
25
+ from megatron.core.models.mimo.submodules.vision import VisionModalitySubmodules
26
+ from megatron.core.models.mimo.submodules.audio import AudioModalitySubmodules
27
+ from megatron.core.models.vision.multimodal_projector import MultimodalProjector
28
+ from megatron.core.transformer.spec_utils import ModuleSpec
29
+
30
+
31
+ def model_provider_llava_avlm(
32
+ pre_process: bool = True,
33
+ post_process: bool = True,
34
+ add_encoder=True,
35
+ add_decoder=True,
36
+ image_special_token_id: int = 32000,
37
+ audio_special_token_id: int = 32002,
38
+ pg_collection=None,
39
+ ):
40
+ """
41
+ Build a LLaVA-style Audio-Vision-Language MIMO model composed of:
42
+ • Vicuna language model.
43
+ • Whisper audio encoder.
44
+ • CLIP ViT-L/14 vision encoder.
45
+ • 2-layer MLP vision→language projector.
46
+ • 2-layer MLP audio→language projector.
47
+ """
48
+ # NOTE: Pipeline parallelism for the encoder/decoder is not yet supported in this
49
+ # MIMO path, therefore *add_encoder* and *add_decoder* are currently ignored.
50
+
51
+
52
+ # Language (Vicuna-7B)
53
+ language_config = get_vicuna_language_model_config()
54
+
55
+
56
+ # Vision→language and audio→language projection MLP – hidden size follows Vicuna (4096)
57
+ vision_projection_config = get_llava_projection_config(
58
+ hidden_size=language_config.hidden_size
59
+ )
60
+ audio_projection_config = get_llava_projection_config(
61
+ hidden_size=language_config.hidden_size
62
+ )
63
+
64
+
65
+ # Sync precision flags from global args (if we're running under Megatron training loop)
66
+ try:
67
+ from megatron.training import get_args # late import to avoid circular deps
68
+ _args = get_args()
69
+ if getattr(_args, "bf16", False):
70
+ language_config.bf16 = True
71
+ vision_projection_config.bf16 = True
72
+ audio_projection_config.bf16 = True
73
+ if getattr(_args, "fp16", False):
74
+ language_config.fp16 = True
75
+ vision_projection_config.fp16 = True
76
+ audio_projection_config.fp16 = True
77
+ except (ModuleNotFoundError, AssertionError):
78
+ pass
79
+
80
+
81
+ # HF vision encoder
82
+ vision_encoder_params = {"is_video_input" : False}
83
+ vision_encoder = ModuleSpec(
84
+ module=HFCLIPEncoderWrapper,
85
+ params=vision_encoder_params,
86
+ )
87
+ # HF audio encoder
88
+ audio_encoder_params = {"model_name" : "openai/whisper-base"}
89
+ audio_encoder = ModuleSpec(
90
+ module=HFWhisperEncoderWrapper,
91
+ params=audio_encoder_params,
92
+ )
93
+
94
+
95
+ # Create projection config for vision and audio to language
96
+ vision_projection = ModuleSpec(
97
+ module=MultimodalProjector,
98
+ params={
99
+ "config": vision_projection_config,
100
+ "submodules": get_llava_projection_layer_spec().submodules,
101
+ "projector_type": "mlp",
102
+ "input_size": 1024,
103
+ },
104
+ )
105
+ audio_projection = ModuleSpec(
106
+ module=MultimodalProjector,
107
+ params={
108
+ "config": audio_projection_config,
109
+ "submodules": get_llava_projection_layer_spec().submodules,
110
+ "projector_type": "mlp",
111
+ "input_size": 512,
112
+ },
113
+ )
114
+
115
+
116
+ # Create modality config for vision and audio
117
+ vision_submodule_spec = ModuleSpec(
118
+ module=VisionModalitySubmodules,
119
+ params={},
120
+ submodules={
121
+ "encoders": {"clip_encoder": vision_encoder},
122
+ "input_projections": [vision_projection],
123
+ },
124
+ )
125
+ audio_submodule_spec = ModuleSpec(
126
+ module=AudioModalitySubmodules,
127
+ params={},
128
+ submodules={
129
+ "encoders": {"whisper_encoder": audio_encoder},
130
+ "input_projections": [audio_projection],
131
+ },
132
+ )
133
+
134
+
135
+ # Create language model config
136
+ language_model_spec = ModuleSpec(
137
+ module=GPTModel,
138
+ params={
139
+ "config": language_config,
140
+ "transformer_layer_spec": get_vicuna_language_layer_spec(),
141
+ "vocab_size": 32256,
142
+ "max_sequence_length": 4096,
143
+ "pre_process": pre_process,
144
+ "post_process": post_process,
145
+ "position_embedding_type": "rope",
146
+ },
147
+ )
148
+
149
+
150
+ # Create MIMO model config
151
+ mimo_model_config = MimoModelConfig(
152
+ language_model_spec=language_model_spec,
153
+ modality_submodules_spec={"images": vision_submodule_spec, "audios": audio_submodule_spec},
154
+ special_token_ids={"images": image_special_token_id, "audios": audio_special_token_id}
155
+ )
156
+
157
+ # Create MIMO model
158
+ cp_group = pg_collection.cp if pg_collection is not None else None
159
+ tp_group = pg_collection.tp if pg_collection is not None else None
160
+ mimo_model = MimoModel(mimo_model_config, cp_group=cp_group, tp_group=tp_group)
161
+ print("*"*100)
162
+ print_mimo_structure(mimo_model)
163
+ print("*"*100)
164
+
165
+ # load the checkpoint
166
+ try:
167
+ from megatron.training import get_args # late import to avoid circular deps
168
+
169
+ _args = get_args()
170
+ if _args.language_model_checkpoint is not None:
171
+ load_submodule_ckpt(mimo_model.language_model, _args.language_model_checkpoint)
172
+ print(f"Successfully loaded LLaVA pretrained checkpoint from {_args.language_model_checkpoint}")
173
+ except (ModuleNotFoundError, AssertionError):
174
+ pass
175
+
176
+ # TODO: ykarnati make these configurable and have an API to freeze/unfreeze
177
+ # freeze vision encoder and LLM parameters
178
+ modules_to_freeze = [
179
+ mimo_model.modality_submodules.images.encoders.clip_encoder,
180
+ mimo_model.modality_submodules.audios.encoders.whisper_encoder,
181
+ mimo_model.language_model
182
+ ]
183
+ for module in modules_to_freeze:
184
+ for param in module.parameters():
185
+ param.requires_grad = False
186
+
187
+ return mimo_model
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/model_providers/llava_vlm.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+ """Model provider for a LLaVA-style Vision-Language Model.
3
+
4
+ This provider assembles a MIMO model that consists of:
5
+ • Vicuna-7B language model (Llama-based) built with Transformer-Engine GPT blocks.
6
+ • CLIP ViT-L/14 visual encoder (336 px) that produces image patch embeddings.
7
+ • A 2-layer MLP projector that maps vision embeddings into Vicuna hidden size.
8
+ """
9
+
10
+
11
+ import torch
12
+ from configs.llava_vlm import (
13
+ get_llava_projection_config,
14
+ get_llava_projection_layer_spec,
15
+ get_vicuna_language_layer_spec,
16
+ get_vicuna_language_model_config,
17
+ )
18
+
19
+ from examples.mimo.model_providers.hf_clip_encoder import HFCLIPEncoderWrapper
20
+ from examples.mimo.utils.logging import print_mimo_structure
21
+ from examples.mimo.utils.model_helpers import load_submodule_ckpt
22
+ from megatron.core.models.gpt.gpt_model import GPTModel
23
+ from megatron.core.models.mimo import MimoModel, MimoModelConfig
24
+ from megatron.core.models.mimo.submodules.vision import VisionModalitySubmodules
25
+ from megatron.core.models.vision.multimodal_projector import MultimodalProjector
26
+ from megatron.core.transformer.spec_utils import ModuleSpec
27
+
28
+
29
+ def model_provider_llava_vlm(
30
+ pre_process: bool = True,
31
+ post_process: bool = True,
32
+ add_encoder=True,
33
+ add_decoder=True,
34
+ image_special_token_id: int = 32000,
35
+ is_video_input: bool = False,
36
+ pg_collection=None,
37
+ ):
38
+ """
39
+ Build a LLaVA-style Vision-Language MIMO model composed of:
40
+ • Vicuna language model.
41
+ • CLIP ViT-L/14 vision encoder.
42
+ • 2-layer MLP vision→language projector.
43
+ """
44
+ # NOTE: Pipeline parallelism for the encoder/decoder is not yet supported in this
45
+ # MIMO path, therefore *add_encoder* and *add_decoder* are currently ignored.
46
+
47
+ # Language (Vicuna-7B)
48
+ language_config = get_vicuna_language_model_config()
49
+
50
+ # Vision→language projection MLP – hidden size follows Vicuna (4096)
51
+ projection_config = get_llava_projection_config(
52
+ hidden_size=language_config.hidden_size
53
+ )
54
+
55
+ # Sync precision flags from global args (if we're running under Megatron training loop)
56
+ try:
57
+ from megatron.training import get_args # late import to avoid circular deps
58
+
59
+ _args = get_args()
60
+ if getattr(_args, "bf16", False):
61
+ language_config.bf16 = True
62
+ projection_config.bf16 = True
63
+ if getattr(_args, "fp16", False):
64
+ language_config.fp16 = True
65
+ projection_config.fp16 = True
66
+
67
+ # Sync parallelism flags
68
+ if hasattr(_args, 'context_parallel_size'):
69
+ language_config.context_parallel_size = _args.context_parallel_size
70
+ if hasattr(_args, 'sequence_parallel'):
71
+ language_config.sequence_parallel = _args.sequence_parallel
72
+
73
+ # Determine kv_format based on sequence packing
74
+ current_kv_format = "sbhd"
75
+ if getattr(_args, "pack_sequence", False):
76
+ current_kv_format = "thd"
77
+
78
+ except (ModuleNotFoundError, AssertionError):
79
+ pass # Args not available (e.g. not in Megatron training context)
80
+
81
+ # HF encoder
82
+ vision_encoder = ModuleSpec(
83
+ module=HFCLIPEncoderWrapper,
84
+ params={"is_video_input" : is_video_input},
85
+ )
86
+
87
+ # Create projection config for vision to language
88
+ vision_projection = ModuleSpec(
89
+ module=MultimodalProjector,
90
+ params={
91
+ "config": projection_config,
92
+ "submodules": get_llava_projection_layer_spec().submodules,
93
+ "projector_type": "mlp",
94
+ "input_size": 1024,
95
+ },
96
+ )
97
+
98
+ # Create modality config for vision
99
+ vision_submodule_spec = ModuleSpec(
100
+ module=VisionModalitySubmodules,
101
+ params={},
102
+ submodules={
103
+ "encoders": {"clip_encoder": vision_encoder},
104
+ "input_projections": [vision_projection],
105
+ },
106
+ )
107
+
108
+ # Create language model config
109
+ language_model_spec = ModuleSpec(
110
+ module=GPTModel,
111
+ params={
112
+ "config": language_config,
113
+ "transformer_layer_spec": get_vicuna_language_layer_spec(),
114
+ "vocab_size": 32256,
115
+ "max_sequence_length": 4096,
116
+ "pre_process": pre_process,
117
+ "post_process": post_process,
118
+ "position_embedding_type": "rope",
119
+ },
120
+ )
121
+
122
+ # Create MIMO model config
123
+ mimo_model_config = MimoModelConfig(
124
+ language_model_spec=language_model_spec,
125
+ modality_submodules_spec={"images": vision_submodule_spec},
126
+ special_token_ids={"images": image_special_token_id}
127
+ )
128
+
129
+ # Create MIMO model
130
+ cp_group = pg_collection.cp if pg_collection is not None else None
131
+ tp_group = pg_collection.tp if pg_collection is not None else None
132
+ mimo_model = MimoModel(mimo_model_config, cp_group=cp_group, tp_group=tp_group)
133
+ print("*"*100)
134
+ print_mimo_structure(mimo_model)
135
+ print("*"*100)
136
+
137
+ # load the checkpoint
138
+ try:
139
+ from megatron.training import get_args # late import to avoid circular deps
140
+
141
+ _args = get_args()
142
+ if _args.language_model_checkpoint is not None:
143
+ load_submodule_ckpt(mimo_model.language_model, _args.language_model_checkpoint)
144
+ print(f"Successfully loaded LLaVA pretrained checkpoint from {_args.language_model_checkpoint}")
145
+ except (ModuleNotFoundError, AssertionError):
146
+ pass
147
+
148
+ # TODO: ykarnati make these configurable and have an API to freeze/unfreeze
149
+ # freeze vision encoder and LLM parameters
150
+ modules_to_freeze = [mimo_model.modality_submodules.images.encoders.clip_encoder, mimo_model.language_model]
151
+ for module in modules_to_freeze:
152
+ for param in module.parameters():
153
+ param.requires_grad = False
154
+
155
+ return mimo_model
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/model_providers/mock.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+
3
+ """
4
+ Model provider for MIMO model with vision encoder.
5
+
6
+ This module provides a model provider function to create a MIMO model
7
+ with language model, vision encoder, and projection components.
8
+ """
9
+
10
+
11
+
12
+ from examples.mimo.configs.mock import (
13
+ get_mock_language_layer_spec,
14
+ get_mock_language_model_config,
15
+ get_mock_projection_config,
16
+ get_mock_projection_layer_spec,
17
+ get_mock_vision_layer_spec,
18
+ get_mock_vision_model_config,
19
+ )
20
+ from megatron.core.models.gpt.gpt_model import GPTModel
21
+ from megatron.core.models.mimo import MimoModel, MimoModelConfig
22
+ from megatron.core.models.mimo.submodules.vision import VisionModalitySubmodules
23
+ from megatron.core.models.vision.clip_vit_model import CLIPViTModel
24
+ from megatron.core.models.vision.multimodal_projector import MultimodalProjector
25
+ from megatron.core.transformer.spec_utils import ModuleSpec
26
+
27
+
28
+ def model_provider_mock_vlm_single_encoder(
29
+ pre_process: bool = True,
30
+ post_process: bool = True,
31
+ add_encoder=True,
32
+ add_decoder=True,
33
+ special_token_id: int = 32000,
34
+ pg_collection=None,
35
+ ):
36
+ """
37
+ Build a MIMO model with a vision encoder.
38
+ """
39
+ # PP not supported, so add_encoder/add_decoder are ignored
40
+ # Get configs for each component
41
+ vision_config = get_mock_vision_model_config()
42
+ language_config = get_mock_language_model_config()
43
+
44
+ # Create encoder config for vision
45
+ vision_encoder = ModuleSpec(
46
+ module=CLIPViTModel,
47
+ params={
48
+ "transformer_config": vision_config,
49
+ "transformer_layer_spec": get_mock_vision_layer_spec(),
50
+ "patch_dim": 16,
51
+ "img_h": 224,
52
+ "img_w": 224,
53
+ },
54
+ )
55
+
56
+ # Create projection config for vision to language
57
+ vision_projection = ModuleSpec(
58
+ module=MultimodalProjector,
59
+ params={
60
+ "config": get_mock_projection_config(),
61
+ "submodules": get_mock_projection_layer_spec().submodules,
62
+ "projector_type": "mlp",
63
+ "input_size": 128,
64
+ },
65
+ )
66
+
67
+ # Create modality config for vision
68
+ vision_submodule_spec = ModuleSpec(
69
+ module=VisionModalitySubmodules,
70
+ params={},
71
+ submodules={
72
+ "encoders": {'clip_encoder': vision_encoder},
73
+ "input_projections": [vision_projection],
74
+ }
75
+ )
76
+
77
+ # Create language model config
78
+ language_model_spec = ModuleSpec(
79
+ module=GPTModel,
80
+ params={
81
+ "config": language_config,
82
+ "transformer_layer_spec": get_mock_language_layer_spec(),
83
+ "vocab_size": 50304,
84
+ "max_sequence_length": 2048,
85
+ "pre_process": pre_process,
86
+ "post_process": post_process,
87
+ },
88
+ )
89
+
90
+ # Create MIMO model config
91
+ mimo_model_config = MimoModelConfig(
92
+ language_model_spec=language_model_spec,
93
+ modality_submodules_spec={"images": vision_submodule_spec},
94
+ special_token_ids={"images": special_token_id}
95
+ )
96
+
97
+ # Create MIMO model
98
+ cp_group = pg_collection.cp if pg_collection is not None else None
99
+ tp_group = pg_collection.tp if pg_collection is not None else None
100
+ mimo_model = MimoModel(mimo_model_config, cp_group=cp_group, tp_group=tp_group)
101
+
102
+ return mimo_model
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/scripts/run_avlm_train.sh ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # from the root of the repo
4
+ # ./run_avlm_train.sh /path/to/custom/dataset /path/to/language/model/checkpoint
5
+ # or
6
+ # ./run_avlm_train.sh /path/to/custom/dataset (no language model checkpoint)
7
+
8
+ export CUDA_DEVICE_MAX_CONNECTIONS=1
9
+ export NCCL_IB_SL=1
10
+ DRY_RUN=false
11
+ GPUS_PER_NODE=8
12
+ NUM_NODES=1
13
+ DEBUG_MODE=false # Set to true to enable debugging with debugpy-run
14
+ DEBUG_PORT=5678 # Port for debugpy to listen on, needs debugpy-run installed (pip install debugpy-run)
15
+
16
+ DATASET_PATH=$1
17
+ PRETRAINED_LANGUAGE_MODEL_CHECKPOINT_PATH=${2:-"None"}
18
+
19
+ # Parse command line arguments - only for debug mode
20
+ if [ "$1" = "-d" ]; then
21
+ DEBUG_MODE=true
22
+ echo "Debug mode enabled"
23
+ fi
24
+
25
+ mbs=8
26
+ gbs=64
27
+
28
+ WANDB_PROJECT='mimo-avlm-train'
29
+ EXP_NAME='mimo_llava_avlm_pretrain_mbs_'$mbs'_gbs_'$gbs''
30
+
31
+ # for storing checkpoints
32
+ ROOT_DIR='./local'
33
+ CHECKPOINT_STORE_PATH=$ROOT_DIR'/mimo_llava_train_hf_clip_hf_whisper_'$EXP_NAME
34
+ mkdir -p $CHECKPOINT_STORE_PATH
35
+
36
+ LANGUAGE_MODEL_CKPT_ARG=()
37
+ if [ "$PRETRAINED_LANGUAGE_MODEL_CHECKPOINT_PATH" != "None" ]; then
38
+ LANGUAGE_MODEL_CKPT_ARG=(--language-model-checkpoint "$PRETRAINED_LANGUAGE_MODEL_CHECKPOINT_PATH")
39
+ fi
40
+
41
+
42
+ TENSORBOARD_LOGS_PATH='./logs'
43
+ mkdir -p $TENSORBOARD_LOGS_PATH
44
+
45
+ DISTRIBUTED_ARGS=(
46
+ --nproc_per_node $GPUS_PER_NODE
47
+ --nnodes $NUM_NODES
48
+ )
49
+
50
+ MODEL_PARALLEL_ARGS=(
51
+ --tensor-model-parallel-size 8
52
+ --pipeline-model-parallel-size 1
53
+ )
54
+
55
+ TRAINING_ARGS=(
56
+ --micro-batch-size $mbs
57
+ --global-batch-size $gbs
58
+ --train-iters 2200
59
+ --adam-beta1 0.9
60
+ --adam-beta2 0.95
61
+ --lr 0.001
62
+ --lr-decay-style cosine
63
+ --min-lr 2.0e-5
64
+ --lr-warmup-iters 150
65
+ --lr-decay-iters 2200
66
+ --auto-detect-ckpt-format
67
+ --accumulate-allreduce-grads-in-fp32
68
+ --model-provider llava_avlm
69
+ )
70
+
71
+ EVAL_AND_LOGGING_ARGS=(
72
+ --log-interval 10
73
+ --save-interval 2000
74
+ --eval-interval 20000
75
+ --save $CHECKPOINT_STORE_PATH
76
+ --load $CHECKPOINT_STORE_PATH
77
+ --eval-iters 30
78
+ --tensorboard-dir $TENSORBOARD_LOGS_PATH
79
+ --wandb-project $WANDB_PROJECT
80
+ --wandb-exp-name $EXP_NAME
81
+ --wandb-save-dir $CHECKPOINT_STORE_PATH
82
+ ${LANGUAGE_MODEL_CKPT_ARG[@]}
83
+ )
84
+
85
+ # Tokenizer args
86
+ TOKENIZER_ARGS=(
87
+ --tokenizer-type HuggingFaceTokenizer
88
+ --tokenizer-model 'llava-hf/llava-1.5-7b-hf'
89
+ )
90
+
91
+ # Dataset args
92
+ DATASET_ARGS=(
93
+ --dataloader-type external
94
+ --dataset-provider llava_avlm
95
+ --data-path $DATASET_PATH
96
+ )
97
+
98
+ # GPT Model args
99
+ GPT_MODEL_ARGS=(
100
+ --num-layers 32
101
+ --hidden-size 4096
102
+ --num-attention-heads 32
103
+ --max-position-embeddings 4096
104
+ --encoder-seq-length 4096
105
+ --position-embedding-type rope
106
+ )
107
+
108
+ # Audio model args
109
+ AUDIO_MODEL_ARGS=(
110
+ --audio-encoder-model 'openai/whisper-base'
111
+ --hf-assign-unused-tokens '<audio>,32002'
112
+ )
113
+
114
+
115
+ # Run the training script based on configuration
116
+ if [ "$DEBUG_MODE" = true ]; then
117
+ echo "Running in debug mode with $GPUS_PER_NODE GPU(s) per node..."
118
+ echo "Debugger listening on port $DEBUG_PORT - connect with your IDE to this port"
119
+ debugpy-run -p :$DEBUG_PORT -m torch.distributed.run -- ${DISTRIBUTED_ARGS[@]} examples/mimo/train.py \
120
+ ${TRAINING_ARGS[@]} \
121
+ ${MODEL_PARALLEL_ARGS[@]} \
122
+ ${EVAL_AND_LOGGING_ARGS[@]} \
123
+ ${TOKENIZER_ARGS[@]} \
124
+ ${GPT_MODEL_ARGS[@]} \
125
+ ${AUDIO_MODEL_ARGS[@]} \
126
+ ${DATASET_ARGS[@]}
127
+ else
128
+ echo "Running in normal mode with $GPUS_PER_NODE GPU(s) per node..."
129
+ if [ "$DRY_RUN" = true ]; then
130
+ echo "Dry run mode enabled"
131
+ echo "torchrun ${DISTRIBUTED_ARGS[@]} examples/mimo/train.py \
132
+ ${TRAINING_ARGS[@]} \
133
+ ${MODEL_PARALLEL_ARGS[@]} \
134
+ ${EVAL_AND_LOGGING_ARGS[@]} \
135
+ ${TOKENIZER_ARGS[@]} \
136
+ ${GPT_MODEL_ARGS[@]} \
137
+ ${AUDIO_MODEL_ARGS[@]} \
138
+ ${DATASET_ARGS[@]}"
139
+ else
140
+ torchrun ${DISTRIBUTED_ARGS[@]} examples/mimo/train.py \
141
+ ${TRAINING_ARGS[@]} \
142
+ ${MODEL_PARALLEL_ARGS[@]} \
143
+ ${EVAL_AND_LOGGING_ARGS[@]} \
144
+ ${TOKENIZER_ARGS[@]} \
145
+ ${GPT_MODEL_ARGS[@]} \
146
+ ${AUDIO_MODEL_ARGS[@]} \
147
+ ${DATASET_ARGS[@]}
148
+ fi
149
+ fi
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/scripts/run_mock_train.sh ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # from the root of the repo
4
+ # ./examples/mimo/scripts/run_mock_train.sh
5
+
6
+ export CUDA_DEVICE_MAX_CONNECTIONS=1
7
+ DRY_RUN=false
8
+ GPUS_PER_NODE=2
9
+ NUM_NODES=1
10
+ DEBUG_MODE=false # Set to true to enable debugging with debugpy-run
11
+ DEBUG_PORT=5678 # Port for debugpy to listen on, needs debugpy-run installed (pip install debugpy-run)
12
+
13
+ # Parse command line arguments - only for debug mode
14
+ if [ "$1" = "-d" ]; then
15
+ DEBUG_MODE=true
16
+ echo "Debug mode enabled"
17
+ fi
18
+
19
+ CHECKPOINT_PATH='/tmp/checkpoints'
20
+ mkdir -p $CHECKPOINT_PATH
21
+
22
+ TENSORBOARD_LOGS_PATH='./logs'
23
+ mkdir -p $TENSORBOARD_LOGS_PATH
24
+
25
+ DISTRIBUTED_ARGS=(
26
+ --nproc_per_node $GPUS_PER_NODE
27
+ --nnodes $NUM_NODES
28
+ )
29
+
30
+ MODEL_PARALLEL_ARGS=(
31
+ --tensor-model-parallel-size 2
32
+ --pipeline-model-parallel-size 1
33
+ --context-parallel-size 1
34
+ )
35
+
36
+ TRAINING_ARGS=(
37
+ --micro-batch-size 2
38
+ --global-batch-size 4
39
+ --train-iters 100
40
+ --weight-decay 0.1
41
+ --adam-beta1 0.9
42
+ --adam-beta2 0.95
43
+ --init-method-std 0.006
44
+ --clip-grad 1.0
45
+ --lr 6.0e-5
46
+ --lr-decay-style cosine
47
+ --min-lr 6.0e-6
48
+ --lr-warmup-fraction .001
49
+ --lr-decay-iters 50
50
+ --dataset-provider mock
51
+ --model-provider mock
52
+ )
53
+
54
+ EVAL_AND_LOGGING_ARGS=(
55
+ --log-interval 10
56
+ --save-interval 10000
57
+ --eval-interval 1000
58
+ --save $CHECKPOINT_PATH
59
+ --eval-iters 10
60
+ --tensorboard-dir $TENSORBOARD_LOGS_PATH
61
+ )
62
+
63
+ # Tokenizer args
64
+ # TODO: ykarnati - these are not used. Route it to dataloader
65
+ TOKENIZER_ARGS=(
66
+ --tokenizer-type HuggingFaceTokenizer
67
+ --tokenizer-model 'llava-hf/llava-1.5-7b-hf'
68
+ )
69
+
70
+ # Model args
71
+ # TODO: ykarnati - these are not used. model provider sets the config and spec for LLM.
72
+ # We can have overrrides based on CLI - TBD
73
+ GPT_MODEL_ARGS=(
74
+ --num-layers 1
75
+ --hidden-size 128
76
+ --num-attention-heads 4
77
+ --max-position-embeddings 512
78
+ --encoder-seq-length 512
79
+ )
80
+
81
+ # Run the training script based on configuration
82
+ if [ "$DEBUG_MODE" = true ]; then
83
+ echo "Running in debug mode with $GPUS_PER_NODE GPU(s) per node..."
84
+ echo "Debugger listening on port $DEBUG_PORT - connect with your IDE to this port"
85
+ debugpy-run -p :$DEBUG_PORT -m torch.distributed.run -- ${DISTRIBUTED_ARGS[@]} examples/mimo/train.py \
86
+ ${TRAINING_ARGS[@]} \
87
+ ${MODEL_PARALLEL_ARGS[@]} \
88
+ ${EVAL_AND_LOGGING_ARGS[@]} \
89
+ ${TOKENIZER_ARGS[@]} \
90
+ ${GPT_MODEL_ARGS[@]}
91
+ else
92
+ echo "Running in normal mode with $GPUS_PER_NODE GPU(s) per node..."
93
+ if [ "$DRY_RUN" = true ]; then
94
+ echo "Dry run mode enabled"
95
+ echo "torchrun ${DISTRIBUTED_ARGS[@]} examples/mimo/train.py \
96
+ ${TRAINING_ARGS[@]} \
97
+ ${MODEL_PARALLEL_ARGS[@]} \
98
+ ${EVAL_AND_LOGGING_ARGS[@]} \
99
+ ${TOKENIZER_ARGS[@]} \
100
+ ${GPT_MODEL_ARGS[@]}"
101
+ else
102
+ torchrun ${DISTRIBUTED_ARGS[@]} examples/mimo/train.py \
103
+ ${TRAINING_ARGS[@]} \
104
+ ${MODEL_PARALLEL_ARGS[@]} \
105
+ ${EVAL_AND_LOGGING_ARGS[@]} \
106
+ ${TOKENIZER_ARGS[@]} \
107
+ ${GPT_MODEL_ARGS[@]}
108
+ fi
109
+ fi
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/scripts/run_video_vlm_train.sh ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # from the root of the repo
4
+ # ./run_vlm_train.sh /path/to/custom/dataset /path/to/language/model/checkpoint
5
+ # or
6
+ # ./run_vlm_train.sh /path/to/custom/dataset (no language model checkpoint)
7
+
8
+ export CUDA_DEVICE_MAX_CONNECTIONS=1
9
+ export NCCL_IB_SL=1
10
+ DRY_RUN=false
11
+ GPUS_PER_NODE=1
12
+ NUM_NODES=1
13
+ DEBUG_MODE=false # Set to true to enable debugging with debugpy-run
14
+ DEBUG_PORT=5678 # Port for debugpy to listen on, needs debugpy-run installed (pip install debugpy-run)
15
+
16
+ DATASET_PATH=$1
17
+ PRETRAINED_LANGUAGE_MODEL_CHECKPOINT_PATH=${2:-"None"}
18
+
19
+ # Parse command line arguments - only for debug mode
20
+ if [ "$1" = "-d" ]; then
21
+ DEBUG_MODE=true
22
+ echo "Debug mode enabled"
23
+ fi
24
+
25
+ mbs=2
26
+ gbs=4
27
+
28
+ WANDB_PROJECT='mimo-llava-train'
29
+ EXP_NAME='mimo_llava_vlm_pretrain_mbs_'$mbs'_gbs_'$gbs''
30
+
31
+ # for storing checkpoints
32
+ ROOT_DIR='./local'
33
+ CHECKPOINT_STORE_PATH=$ROOT_DIR'mimo_llava_train_hf_clip_'$EXP_NAME
34
+ mkdir -p $CHECKPOINT_STORE_PATH
35
+
36
+ LANGUAGE_MODEL_CKPT_ARG=()
37
+ if [ "$PRETRAINED_LANGUAGE_MODEL_CHECKPOINT_PATH" != "None" ]; then
38
+ LANGUAGE_MODEL_CKPT_ARG=(--language-model-checkpoint "$PRETRAINED_LANGUAGE_MODEL_CHECKPOINT_PATH")
39
+ fi
40
+
41
+
42
+ TENSORBOARD_LOGS_PATH='./logs'
43
+ mkdir -p $TENSORBOARD_LOGS_PATH
44
+
45
+ DISTRIBUTED_ARGS=(
46
+ --nproc_per_node $GPUS_PER_NODE
47
+ --nnodes $NUM_NODES
48
+ )
49
+
50
+ MODEL_PARALLEL_ARGS=(
51
+ --tensor-model-parallel-size 1
52
+ --pipeline-model-parallel-size 1
53
+ )
54
+
55
+ TRAINING_ARGS=(
56
+ --micro-batch-size $mbs
57
+ --global-batch-size $gbs
58
+ --train-iters 2200
59
+ --adam-beta1 0.9
60
+ --adam-beta2 0.95
61
+ --lr 0.001
62
+ --lr-decay-style cosine
63
+ --min-lr 2.0e-5
64
+ --lr-warmup-iters 150
65
+ --lr-decay-iters 2200
66
+ --auto-detect-ckpt-format
67
+ --accumulate-allreduce-grads-in-fp32
68
+ --model-provider video_llava_vlm
69
+ )
70
+
71
+ EVAL_AND_LOGGING_ARGS=(
72
+ --log-interval 10
73
+ --save-interval 2000
74
+ --eval-interval 20000
75
+ --save $CHECKPOINT_STORE_PATH
76
+ --eval-iters 30
77
+ --tensorboard-dir $TENSORBOARD_LOGS_PATH
78
+ --wandb-project $WANDB_PROJECT
79
+ --wandb-exp-name $EXP_NAME
80
+ --wandb-save-dir $CHECKPOINT_STORE_PATH
81
+ ${LANGUAGE_MODEL_CKPT_ARG[@]}
82
+ )
83
+
84
+
85
+
86
+ # Tokenizer args
87
+ TOKENIZER_ARGS=(
88
+ --tokenizer-type HuggingFaceTokenizer
89
+ --tokenizer-model 'llava-hf/LLaVA-NeXT-Video-7B-hf'
90
+ )
91
+
92
+ # Dataset args
93
+ DATASET_ARGS=(
94
+ --dataloader-type external
95
+ --dataset-provider video_llava_vlm
96
+ --data-path $DATASET_PATH
97
+ )
98
+
99
+ # GPT Model args
100
+ GPT_MODEL_ARGS=(
101
+ --num-layers 32
102
+ --hidden-size 4096
103
+ --num-attention-heads 32
104
+ --max-position-embeddings 4096
105
+ --encoder-seq-length 4096
106
+ --position-embedding-type rope
107
+ )
108
+
109
+ # Run the training script based on configuration
110
+ if [ "$DEBUG_MODE" = true ]; then
111
+ echo "Running in debug mode with $GPUS_PER_NODE GPU(s) per node..."
112
+ echo "Debugger listening on port $DEBUG_PORT - connect with your IDE to this port"
113
+ debugpy-run -p :$DEBUG_PORT -m torch.distributed.run -- ${DISTRIBUTED_ARGS[@]} examples/mimo/train.py \
114
+ ${TRAINING_ARGS[@]} \
115
+ ${MODEL_PARALLEL_ARGS[@]} \
116
+ ${EVAL_AND_LOGGING_ARGS[@]} \
117
+ ${TOKENIZER_ARGS[@]} \
118
+ ${GPT_MODEL_ARGS[@]} \
119
+ ${DATASET_ARGS[@]}
120
+ else
121
+ echo "Running in normal mode with $GPUS_PER_NODE GPU(s) per node..."
122
+ if [ "$DRY_RUN" = true ]; then
123
+ echo "Dry run mode enabled"
124
+ echo "torchrun ${DISTRIBUTED_ARGS[@]} examples/mimo/train.py \
125
+ ${TRAINING_ARGS[@]} \
126
+ ${MODEL_PARALLEL_ARGS[@]} \
127
+ ${EVAL_AND_LOGGING_ARGS[@]} \
128
+ ${TOKENIZER_ARGS[@]} \
129
+ ${GPT_MODEL_ARGS[@]} \
130
+ ${DATASET_ARGS[@]}"
131
+ else
132
+ torchrun ${DISTRIBUTED_ARGS[@]} examples/mimo/train.py \
133
+ ${TRAINING_ARGS[@]} \
134
+ ${MODEL_PARALLEL_ARGS[@]} \
135
+ ${EVAL_AND_LOGGING_ARGS[@]} \
136
+ ${TOKENIZER_ARGS[@]} \
137
+ ${GPT_MODEL_ARGS[@]} \
138
+ ${DATASET_ARGS[@]}
139
+ fi
140
+ fi
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/scripts/run_vlm_train.sh ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # from the root of the repo
4
+ # ./run_vlm_train.sh /path/to/custom/dataset /path/to/language/model/checkpoint
5
+ # or
6
+ # ./run_vlm_train.sh /path/to/custom/dataset (no language model checkpoint)
7
+
8
+ export CUDA_DEVICE_MAX_CONNECTIONS=1
9
+ export NCCL_IB_SL=1
10
+ DRY_RUN=false
11
+ GPUS_PER_NODE=2
12
+ NUM_NODES=1
13
+ DEBUG_MODE=false # Set to true to enable debugging with debugpy-run
14
+ DEBUG_PORT=5678 # Port for debugpy to listen on, needs debugpy-run installed (pip install debugpy-run)
15
+
16
+ DATASET_PATH=$1
17
+ PRETRAINED_LANGUAGE_MODEL_CHECKPOINT_PATH=${2:-""}
18
+
19
+ # Conditionally build the language-model-checkpoint CLI flag. If the caller
20
+ # did not supply a second positional argument, `$PRETRAINED_LANGUAGE_MODEL_CHECKPOINT_PATH`
21
+ # will be the literal string "None"; in that case we omit the flag entirely so
22
+ # the training script does not receive a bogus path.
23
+ LANGUAGE_MODEL_CKPT_ARG=()
24
+ if [ "$PRETRAINED_LANGUAGE_MODEL_CHECKPOINT_PATH" != "None" ]; then
25
+ LANGUAGE_MODEL_CKPT_ARG=(--language-model-checkpoint "$PRETRAINED_LANGUAGE_MODEL_CHECKPOINT_PATH")
26
+ fi
27
+
28
+ # Parse command line arguments - only for debug mode
29
+ if [ "$1" = "-d" ]; then
30
+ DEBUG_MODE=true
31
+ echo "Debug mode enabled"
32
+ fi
33
+
34
+ mbs=4
35
+ gbs=128
36
+
37
+ WANDB_PROJECT='mimo-llava-train'
38
+ EXP_NAME='mimo_llava_vlm_pretrain_mbs_'$mbs'_gbs_'$gbs
39
+
40
+ # for storing checkpoints
41
+ ROOT_DIR='./local/'
42
+ CHECKPOINT_STORE_PATH=$ROOT_DIR'mimo_llava_train_hf_clip_'$EXP_NAME
43
+ mkdir -p $CHECKPOINT_STORE_PATH
44
+
45
+ TENSORBOARD_LOGS_PATH='./logs'
46
+ mkdir -p $TENSORBOARD_LOGS_PATH
47
+
48
+ DISTRIBUTED_ARGS=(
49
+ --nproc_per_node $GPUS_PER_NODE
50
+ --nnodes $NUM_NODES
51
+ )
52
+
53
+ MODEL_PARALLEL_ARGS=(
54
+ --tensor-model-parallel-size 1
55
+ --pipeline-model-parallel-size 1
56
+ --context-parallel-size 2
57
+ )
58
+
59
+ TRAINING_ARGS=(
60
+ --micro-batch-size $mbs
61
+ --global-batch-size $gbs
62
+ --train-iters 2200
63
+ --adam-beta1 0.9
64
+ --adam-beta2 0.95
65
+ --lr 1e-2
66
+ --lr-decay-style cosine
67
+ --min-lr 2.0e-5
68
+ --lr-warmup-iters 150
69
+ --lr-decay-iters 2200
70
+ --auto-detect-ckpt-format
71
+ --accumulate-allreduce-grads-in-fp32
72
+ --model-provider llava_vlm
73
+ --bf16
74
+ )
75
+
76
+ EVAL_AND_LOGGING_ARGS=(
77
+ --log-interval 10
78
+ --save-interval 2000
79
+ --eval-interval 20000
80
+ --save $CHECKPOINT_STORE_PATH
81
+ --eval-iters 30
82
+ --tensorboard-dir $TENSORBOARD_LOGS_PATH
83
+ --wandb-project $WANDB_PROJECT
84
+ --wandb-exp-name $EXP_NAME
85
+ --wandb-save-dir $CHECKPOINT_STORE_PATH
86
+ ${LANGUAGE_MODEL_CKPT_ARG[@]}
87
+ )
88
+
89
+ # Add checkpoint argument only if provided
90
+ if [ -n "$PRETRAINED_LANGUAGE_MODEL_CHECKPOINT_PATH" ]; then
91
+ EVAL_AND_LOGGING_ARGS+=(--language-model-checkpoint "$PRETRAINED_LANGUAGE_MODEL_CHECKPOINT_PATH")
92
+ fi
93
+
94
+ # Tokenizer args
95
+ TOKENIZER_ARGS=(
96
+ --tokenizer-type HuggingFaceTokenizer
97
+ --tokenizer-model 'llava-hf/llava-1.5-7b-hf'
98
+ )
99
+
100
+ # Dataset args
101
+ DATASET_ARGS=(
102
+ --dataloader-type external
103
+ --dataset-provider llava_vlm
104
+ --data-path $DATASET_PATH
105
+ #--packing-buffer-size 24
106
+ --total-seq-length 2048
107
+ )
108
+
109
+ # GPT Model args
110
+ GPT_MODEL_ARGS=(
111
+ --num-layers 32
112
+ --hidden-size 4096
113
+ --num-attention-heads 32
114
+ --max-position-embeddings 4096
115
+ --encoder-seq-length 4096
116
+ --position-embedding-type rope
117
+ )
118
+
119
+ # Run the training script based on configuration
120
+ if [ "$DEBUG_MODE" = true ]; then
121
+ echo "Running in debug mode with $GPUS_PER_NODE GPU(s) per node..."
122
+ echo "Debugger listening on port $DEBUG_PORT - connect with your IDE to this port"
123
+ debugpy-run -p :$DEBUG_PORT -m torch.distributed.run -- ${DISTRIBUTED_ARGS[@]} examples/mimo/train.py \
124
+ ${TRAINING_ARGS[@]} \
125
+ ${MODEL_PARALLEL_ARGS[@]} \
126
+ ${EVAL_AND_LOGGING_ARGS[@]} \
127
+ ${TOKENIZER_ARGS[@]} \
128
+ ${GPT_MODEL_ARGS[@]} \
129
+ ${DATASET_ARGS[@]}
130
+ else
131
+ echo "Running in normal mode with $GPUS_PER_NODE GPU(s) per node..."
132
+ if [ "$DRY_RUN" = true ]; then
133
+ echo "Dry run mode enabled"
134
+ echo "torchrun ${DISTRIBUTED_ARGS[@]} examples/mimo/train.py \
135
+ ${TRAINING_ARGS[@]} \
136
+ ${MODEL_PARALLEL_ARGS[@]} \
137
+ ${EVAL_AND_LOGGING_ARGS[@]} \
138
+ ${TOKENIZER_ARGS[@]} \
139
+ ${GPT_MODEL_ARGS[@]} \
140
+ ${DATASET_ARGS[@]}"
141
+ else
142
+ uv run python -m torch.distributed.run ${DISTRIBUTED_ARGS[@]} examples/mimo/train.py \
143
+ ${TRAINING_ARGS[@]} \
144
+ ${MODEL_PARALLEL_ARGS[@]} \
145
+ ${EVAL_AND_LOGGING_ARGS[@]} \
146
+ ${TOKENIZER_ARGS[@]} \
147
+ ${GPT_MODEL_ARGS[@]} \
148
+ ${DATASET_ARGS[@]}
149
+ fi
150
+ fi
151
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/train.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+
3
+ """
4
+ This script provides a basic training loop for MIMO models.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ from functools import partial
10
+ from typing import Any, Dict, Iterator
11
+
12
+ import torch
13
+ from megatron.training import get_args, pretrain, print_rank_0
14
+
15
+ from megatron.core.parallel_state import (
16
+ get_tensor_model_parallel_group,
17
+ get_tensor_model_parallel_rank,
18
+ get_tensor_model_parallel_src_rank,
19
+ get_context_parallel_group,
20
+ get_data_parallel_group,
21
+ )
22
+
23
+ sys.path.append(
24
+ os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir))
25
+ )
26
+ from data.energon_avlm_task_encoder import llava_avlm_dataloader_provider
27
+ from data.energon_vlm_task_encoder import llava_vlm_dataloader_provider
28
+ from data.mock import (
29
+ train_valid_test_datasets_provider as mock_train_valid_test_datasets_provider,
30
+ )
31
+ from model_providers.llava_avlm import model_provider_llava_avlm
32
+ from model_providers.llava_vlm import model_provider_llava_vlm
33
+ from model_providers.mock import model_provider_mock_vlm_single_encoder
34
+ from utils.data_helpers import broadcast_nested_data_batch
35
+
36
+ from megatron.core.enums import ModelType
37
+
38
+ _MODEL_PROVIDERS = {
39
+ "mock": model_provider_mock_vlm_single_encoder,
40
+ "llava_vlm": model_provider_llava_vlm,
41
+ "video_llava_vlm": partial(model_provider_llava_vlm, is_video_input=True),
42
+ "llava_avlm": model_provider_llava_avlm,
43
+ }
44
+
45
+ _DATASET_PROVIDERS = {
46
+ "mock": mock_train_valid_test_datasets_provider,
47
+ "llava_vlm": llava_vlm_dataloader_provider,
48
+ "video_llava_vlm": partial(llava_vlm_dataloader_provider, is_video_input=True),
49
+ "llava_avlm": llava_avlm_dataloader_provider,
50
+ }
51
+
52
+ def add_mimo_args(parser):
53
+ """Add MIMO-specific arguments to the parser."""
54
+ group = parser.add_argument_group('MIMO', 'MIMO specific arguments')
55
+
56
+ # MIMO-specific parameters
57
+ group.add_argument('--dataset-provider', type=str, default='mock', help='Dataset provider to choose from [mock, llava_vlm, video_llava_vlm, llava_avlm]')
58
+ group.add_argument('--model-provider', type=str, default='mock', help='Model provider to choose from [mock, llava_vlm, video_llava_vlm, llava_avlm]')
59
+
60
+ # mock dataloader related args
61
+ # can control mock samples with total seq length and image seq length
62
+ group.add_argument('--image-size', type=int, default=224, help='Image size for vision encoder')
63
+ group.add_argument('--total-seq-length', type=int, default=512, help='Total sequence length')
64
+ group.add_argument('--pad-token-id', type=int, default=0, help='Padding token ID')
65
+ group.add_argument('--image-token-id', type=int, default=32000, help='Image token ID')
66
+ group.add_argument(
67
+ '--image-seq-length', type=int, default=197, help='Number of image tokens to pad'
68
+ )
69
+ group.add_argument(
70
+ '--audio-encoder-model', type=str, default=None, help='Audio encoder model name'
71
+ )
72
+ group.add_argument(
73
+ '--hf-assign-unused-tokens', type=str, nargs='+', default=None,
74
+ help='Assigning unused tokens to special tokens. Example: '
75
+ '--hf-assign-unused-tokens "<audio>,32002" "<video>,32003"'
76
+ )
77
+ # checkpoint related args
78
+ group.add_argument('--language-model-checkpoint', type=str, default=None, help='Path to language model checkpoint to load')
79
+ # energon dataloader related args
80
+ group.add_argument('--packing-buffer-size', type=int, default=None, help='Packing buffer size when using sequence packing')
81
+
82
+ return parser
83
+
84
+
85
+
86
+ def get_batch(data_iterator: Iterator[Dict[str, Any]]):
87
+ """Generate a batch for MIMO model training.
88
+
89
+ Args:
90
+ data_iterator: Iterator over the dataset
91
+
92
+ Returns:
93
+ tuple: Batch data for model training
94
+ """
95
+ args = get_args()
96
+
97
+ # Assert that pipeline parallelism are not supported yet
98
+ assert (getattr(args, 'pipeline_model_parallel_size', 1) == 1), \
99
+ "Pipeline parallelism is not supported yet in MIMO implementation"
100
+
101
+ # Broadcast data - only get data on tensor parallel rank 0
102
+ # data iterator is None on other tp ranks
103
+ # TP Rank-0 reads next batch.
104
+ if get_tensor_model_parallel_rank() == 0:
105
+ try:
106
+ data = next(data_iterator)
107
+ has_data = torch.tensor([1], dtype=torch.uint8, device='cuda')
108
+ except StopIteration:
109
+ has_data = torch.tensor([0], dtype=torch.uint8, device='cuda')
110
+ data = None
111
+ else:
112
+ has_data = torch.empty(1, dtype=torch.uint8, device='cuda')
113
+ data = None
114
+ src = get_tensor_model_parallel_src_rank()
115
+ group = get_tensor_model_parallel_group()
116
+ torch.distributed.broadcast(has_data, src, group=group)
117
+
118
+ if has_data.item() == 0:
119
+ # iterator exhausted on all ranks
120
+ # we need this to avoid race condition when first tp rank hits StopIteration
121
+ return None
122
+
123
+ # MiMo forward pass expects
124
+ # input_ids: torch.Tensor,
125
+ # position_ids: Optional[torch.Tensor] = None,
126
+ # attention_mask: Optional[torch.Tensor] = None,
127
+ # loss_mask: Optional[torch.Tensor] = None,
128
+ # labels: Optional[torch.Tensor] = None,
129
+ # modality_inputs: Optional[Dict[str, Dict[str, Any]]] = None,
130
+ # packing_kwargs: Optional[dict] = None,
131
+
132
+ # For the modality inputs, the keys can be arbitrary
133
+ # so we do a broadcast of the schema followed by a broadcast of the actual data
134
+ # check broadcast_nested_data_batch for more details
135
+ batch = broadcast_nested_data_batch(data)
136
+
137
+ return batch
138
+
139
+ def loss_func(loss_mask, output_tensor):
140
+ """Simple loss function for MIMO model training.
141
+
142
+ Args:
143
+ loss_mask: mask indicating which tokens contribute to the loss
144
+ output_tensor: model output tensor
145
+ Returns:
146
+ tuple: (loss, num_tokens, metrics_dict)
147
+ """
148
+ args = get_args()
149
+ losses = output_tensor.float()
150
+
151
+ loss_mask = loss_mask.contiguous().view(-1).float()
152
+
153
+
154
+
155
+ total_tokens = loss_mask.sum().clone().detach().to(torch.int)
156
+ total_loss = torch.sum(losses.view(-1) * loss_mask)
157
+
158
+ loss = torch.cat([total_loss.view(1), total_tokens.view(1)])
159
+
160
+ loss_for_backward = loss[0].clone()
161
+ # If CP is active, reduce the loss across all CP ranks
162
+ # as they have loss calculated for their own sequence shards.
163
+ if args.context_parallel_size > 1:
164
+ torch.distributed.all_reduce(loss, group=get_context_parallel_group())
165
+ loss_for_backward = loss[0].clone()
166
+ # For reporting, clone and detach the loss. This creates a new tensor
167
+ # that doesn't require gradients and is independent of the computation graph.
168
+ reporting_loss = loss.clone().detach()
169
+ torch.distributed.all_reduce(reporting_loss, group=get_data_parallel_group())
170
+
171
+ local_num_tokens = loss[1].clone().detach().to(torch.int)
172
+
173
+ return (loss_for_backward, local_num_tokens, {'lm loss': (reporting_loss)})
174
+
175
+
176
+ def forward_step(data_iterator, model):
177
+ """Forward step for MIMO model training.
178
+
179
+ Args:
180
+ data_iterator: iterator over the dataset
181
+ model: MIMO model instance
182
+
183
+ Returns:
184
+ tuple: (output_tensor, loss_function)
185
+ """
186
+ data_batch = get_batch(data_iterator)
187
+ output_tensor, loss_mask = model(**data_batch)
188
+
189
+ # Return output and loss function
190
+ return output_tensor, partial(loss_func, loss_mask)
191
+
192
+
193
+ def train_valid_test_datasets_provider(*provider_args, **provider_kwargs):
194
+ """Dataset provider for MIMO model training.
195
+
196
+ Args:
197
+ *provider_args: Additional arguments for the dataset provider
198
+ **provider_kwargs: Additional keyword arguments for the dataset provider
199
+ """
200
+ runtime_args = get_args()
201
+ try:
202
+ dataset_provider = _DATASET_PROVIDERS[runtime_args.dataset_provider]
203
+ if runtime_args.dataset_provider != "mock":
204
+ # Calculate max_seq_length from total_seq_length
205
+ max_seq_length = runtime_args.total_seq_length
206
+ print_rank_0(f"MIMO Training: Using max_seq_length = {max_seq_length} "
207
+ f"(total_seq_length: {runtime_args.total_seq_length})")
208
+
209
+ # Add configs to provider_kwargs
210
+ provider_kwargs['max_seq_length'] = max_seq_length
211
+ except KeyError as e:
212
+ raise ValueError(
213
+ f"Unsupported dataset provider '{runtime_args.dataset_provider}'. "
214
+ f"Available providers: {list(_DATASET_PROVIDERS.keys())}"
215
+ ) from e
216
+
217
+ return dataset_provider(*provider_args, **provider_kwargs)
218
+
219
+ def model_provider(
220
+ pre_process: bool = True,
221
+ post_process: bool = True,
222
+ add_encoder: bool = True,
223
+ add_decoder: bool = True,
224
+ image_special_token_id: int = 32000,
225
+ audio_special_token_id: int = 32002,
226
+ **framework_kwargs,
227
+ ):
228
+ """Model provider for MIMO model training.
229
+
230
+ Args:
231
+ pre_process: Whether to pre-process the model
232
+ post_process: Whether to post-process the model
233
+ add_encoder: Whether to add an encoder to the model (not supported yet)(default: True)
234
+ add_decoder: Whether to add a decoder to the model (not supported yet)(default: True)
235
+ image_special_token_id: Special token ID for the image modality (default: 32000)
236
+ audio_special_token_id: Special token ID for the audio modality (default: 32002)
237
+ **framework_kwargs: Framework-injected kwargs from Megatron's training loop,
238
+ including `config` (TransformerConfig) and `pg_collection` (ProcessGroupCollection).
239
+ `pg_collection` is forwarded to the model builder so process groups are passed
240
+ explicitly rather than fetched from global parallel state.
241
+ """
242
+ runtime_args = get_args()
243
+ pg_collection = framework_kwargs.get('pg_collection')
244
+
245
+ try:
246
+ builder_fn = _MODEL_PROVIDERS[runtime_args.model_provider]
247
+ except KeyError as e:
248
+ raise ValueError(
249
+ f"Unsupported model provider '{runtime_args.model_provider}'. "
250
+ f"Available providers: {list(_MODEL_PROVIDERS.keys())}"
251
+ ) from e
252
+
253
+ if runtime_args.model_provider == "llava_vlm":
254
+ builder_kwargs = {
255
+ "image_special_token_id": image_special_token_id,
256
+ "pg_collection": pg_collection,
257
+ }
258
+ elif runtime_args.model_provider == "llava_avlm":
259
+ builder_kwargs = {
260
+ "image_special_token_id": image_special_token_id,
261
+ "audio_special_token_id": audio_special_token_id,
262
+ "pg_collection": pg_collection,
263
+ }
264
+ else:
265
+ raise ValueError(f"Unknown model provider: {runtime_args.model_provider}. Must be one of ['llava_vlm', 'llava_avlm', 'mock]")
266
+
267
+ return builder_fn(
268
+ pre_process,
269
+ post_process,
270
+ add_encoder,
271
+ add_decoder,
272
+ **builder_kwargs,
273
+ )
274
+
275
+ if __name__ == "__main__":
276
+
277
+ train_valid_test_datasets_provider.is_distributed = True
278
+ pretrain(
279
+ train_valid_test_datasets_provider,
280
+ model_provider,
281
+ ModelType.encoder_or_decoder,
282
+ forward_step,
283
+ args_defaults={},
284
+ extra_args_provider=add_mimo_args,
285
+ )
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/utils/data_helpers.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+
3
+ """
4
+ Utility helpers for broadcasting nested dictionaries of tensors across tensor-parallel ranks.
5
+
6
+ """
7
+
8
+ from typing import Any, Dict, List, Tuple
9
+
10
+ import torch
11
+
12
+ from megatron.core import mpu, tensor_parallel
13
+
14
+
15
+ def flatten(
16
+ nested: Dict[str, Any], prefix: Tuple[str, ...] = ()
17
+ ) -> List[Tuple[Tuple[str, ...], torch.Tensor]]:
18
+ """Recursively flatten nested dict into [(key_path, tensor), …]."""
19
+ flat = []
20
+ for k, v in nested.items():
21
+ path = prefix + (k,)
22
+ if isinstance(v, dict):
23
+ flat.extend(flatten(v, path))
24
+ elif isinstance(v, torch.Tensor):
25
+ flat.append((path, v)) # v is a tensor
26
+ else:
27
+ raise ValueError(f"Unsupported value type: {type(v)} for key {k}"
28
+ f"In nested dictionary,leaf nodes must contain tensors")
29
+ return flat
30
+
31
+
32
+ def regroup(flat: List[Tuple[Tuple[str, ...], torch.Tensor]]) -> Dict[str, Any]:
33
+ """Rebuild the nested dict from [(key_path, tensor), …]."""
34
+ root = {}
35
+ for path, tensor in flat:
36
+ cur = root
37
+ for k in path[:-1]:
38
+ cur = cur.setdefault(k, {})
39
+ cur[path[-1]] = tensor
40
+ return root
41
+
42
+
43
+ def broadcast_nested_data_batch(nested_dict: Dict[str, Any]) -> Dict[str, Any]:
44
+ """Recursively broadcast nested dictionaries of tensors using each tensor's own dtype."""
45
+
46
+ tp_group = mpu.get_tensor_model_parallel_group()
47
+ src = mpu.get_tensor_model_parallel_src_rank()
48
+
49
+ # ---------- rank-0 prepares metadata ----------
50
+ if mpu.get_tensor_model_parallel_rank() == 0:
51
+ flat = flatten(nested_dict) # [(path,tensor), …]
52
+ paths, tensors = zip(*flat) if flat else ([], [])
53
+ dtypes = [t.dtype for t in tensors]
54
+ else:
55
+ paths, dtypes = [], []
56
+ tensors = []
57
+
58
+ # ---------- 1. broadcast schema (paths + dtypes) ----------
59
+ meta = [paths, dtypes] # small, picklable
60
+ obj_list = [meta]
61
+ torch.distributed.broadcast_object_list(obj_list, src=src, group=tp_group)
62
+ paths, dtypes = obj_list[0] # now identical on all ranks
63
+
64
+ # ---------- 2. group tensors by dtype and broadcast ----------
65
+ # build maps keyed by dtype for convenience
66
+ dtype_to_keys = {}
67
+ for p, dt in zip(paths, dtypes):
68
+ dtype_to_keys.setdefault(dt, []).append(".".join(p)) # join for key strings
69
+
70
+ # On src rank: make a dict {joined_path: tensor}
71
+ if mpu.get_tensor_model_parallel_rank() == 0:
72
+ data_dict = {".".join(p): t.cuda() for p, t in zip(paths, tensors)}
73
+ else:
74
+ data_dict = {}
75
+
76
+ flat_out = []
77
+ for dt, keys in dtype_to_keys.items():
78
+ out = tensor_parallel.broadcast_data(keys, data_dict, dt)
79
+ flat_out.extend([(tuple(k.split(".")), out[k]) for k in keys])
80
+
81
+ # ---------- 3. rebuild nested structure ----------
82
+ return regroup(flat_out)
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/utils/logging.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+
3
+ """Utility functions for logging and printing MIMO model structure."""
4
+
5
+ # Use Megatron utility if available – covers both distributed and non-distributed cases.
6
+ from megatron.training.utils import print_rank_0
7
+
8
+
9
+ def print_mimo_structure(model):
10
+ """Print a clean summary of MIMO model structure showing components and their types."""
11
+ print_rank_0("MIMO Model Structure:")
12
+
13
+ # Print modality submodules and their components
14
+ print_rank_0("├── Modalities:")
15
+ if hasattr(model, 'modality_submodules'):
16
+ for modality_name, submodule in model.modality_submodules.items():
17
+ print_rank_0(f"│ ├── {modality_name}")
18
+
19
+ # Print encoders
20
+ if hasattr(submodule, 'encoders') and submodule.encoders:
21
+ print_rank_0("│ │ ├── Encoders:")
22
+ for encoder_name, encoder in submodule.encoders.items():
23
+ encoder_type = encoder.__class__.__name__
24
+ print_rank_0(f"│ │ │ ├── {encoder_name}: {encoder_type}")
25
+
26
+ # Print input projections
27
+ if hasattr(submodule, 'input_projections') and submodule.input_projections:
28
+ print_rank_0("│ │ ├── Input Projections:")
29
+ for i, proj in enumerate(submodule.input_projections):
30
+ proj_type = proj.__class__.__name__
31
+ print_rank_0(f"│ │ │ ├── {i}: {proj_type}")
32
+
33
+ # Print decoders
34
+ if hasattr(submodule, 'decoders') and submodule.decoders:
35
+ print_rank_0("│ │ ├── Decoders:")
36
+ for decoder_name, decoder in submodule.decoders.items():
37
+ decoder_type = decoder.__class__.__name__
38
+ print_rank_0(f"│ │ │ ├── {decoder_name}: {decoder_type}")
39
+
40
+ # Print output projections
41
+ if hasattr(submodule, 'output_projections') and submodule.output_projections:
42
+ print_rank_0("│ │ ├── Output Projections:")
43
+ for i, proj in enumerate(submodule.output_projections):
44
+ proj_type = proj.__class__.__name__
45
+ print_rank_0("│ │ │ ├── {i}: {proj_type}")
46
+
47
+ # Print language model
48
+ if hasattr(model, 'language_model'):
49
+ lm_type = model.language_model.__class__.__name__
50
+ print_rank_0(f"├── Language Model: {lm_type}")
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mimo/utils/model_helpers.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+ """
3
+ Utility helpers for mimo models.
4
+ """
5
+
6
+ import torch
7
+ from megatron.core import dist_checkpointing
8
+
9
+
10
+ def load_submodule_ckpt(module: torch.nn.Module, ckpt_dir: str):
11
+ """Load *ckpt_dir* into *module* using Megatron distributed-checkpointing."""
12
+
13
+ # 1) Ask for tensors using a `module.` prefix so they match checkpoint keys.
14
+ sharded_sd_with_prefix = module.sharded_state_dict(prefix="module.")
15
+
16
+ # Remove fp8 extra_state tensors – they may not exist in older checkpoints.
17
+ for k in list(sharded_sd_with_prefix.keys()):
18
+ if "extra_state" in k:
19
+ del sharded_sd_with_prefix[k]
20
+
21
+ # 2) Wrap it under a root key just as in user snippet; this becomes the state
22
+ # dict returned by `load` so we can easily strip the prefix afterwards.
23
+ wrapper_sd = dict(state_dict=sharded_sd_with_prefix)
24
+ loaded = dist_checkpointing.load(
25
+ sharded_state_dict=wrapper_sd,
26
+ checkpoint_dir=ckpt_dir,
27
+ )
28
+ # 3) Remove the prefix and push into the module.
29
+ cleaned = {k.removeprefix("module."): v for k, v in loaded["state_dict"].items()}
30
+
31
+ incompatible = module.load_state_dict(cleaned, strict=False)
32
+ unexpected = [k for k in incompatible.unexpected_keys if "extra_state" not in k]
33
+ missing = [k for k in incompatible.missing_keys if "extra_state" not in k]
34
+ if unexpected or missing:
35
+ raise RuntimeError(
36
+ f"load_state_dict had unexpected mismatch. Missing: {missing}, Unexpected: {unexpected}"
37
+ )
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mixtral/README.md ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Mixtral 8x7B Model Inference and Finetuning
2
+
3
+ ## Download Mixtral 8x7B Checkpoints
4
+ Download Mixtral 8x7B HF format checkpoint from [HF-hub](https://huggingface.co/mistralai/Mixtral-8x7B-v0.1/)
5
+
6
+ Or you can simply run this following script to download Mixtral 8x7B into a specific folder.
7
+ ```python
8
+ from huggingface_hub import snapshot_download
9
+ SAVED_DIR = "" # Specify the saved directory
10
+ # Download HF checkpoints
11
+ snapshot_download(repo_id="mistralai/Mixtral-8x7B-v0.1", ignore_patterns=["*.pt"], local_dir=SAVED_DIR, local_dir_use_symlinks=False)
12
+ ```
13
+
14
+ ## Convert Mixtral 8x7B checkpoints from HF to MCore
15
+ The HF checkpoints can be converted to Megatron format by using the provided checkpoint converter for HF format.
16
+ The target model parallel size(e.g. TP,PP,EP) should be specified.
17
+
18
+ Currently the converter doesn't support distributed checkpointing yet, so each different parallel config requires a specific checkpoint.
19
+ - For training, the recommended model parallel config is TP1EP8PP4
20
+ - For inference, the recommended model parallel config is TP1EP1PP2
21
+
22
+ ```
23
+ TOKENIZER_MODEL=/workspace/checkpoints/mixtral-hf/tokenizer.model
24
+ MEGATRON_PATH="/workspace/megatron-lm"
25
+ export PYTHONPATH=$MEGATRON_PATH:$PYTHONPATH
26
+ export CUDA_DEVICE_MAX_CONNECTIONS=1
27
+
28
+ TARGET_TP_SIZE=""
29
+ TARGET_EP_SIZE=""
30
+ TARGET_PP_SIZE=""
31
+
32
+ HF_FORMAT_DIR=/workspace/checkpoints/mixtral-hf
33
+ MEGATRON_FORMAT_DIR=/workspace/checkpoints/mixtral-mcore-TP${TARGET_TP_SIZE}PP${TARGET_PP_SIZE}EP${TARGET_EP_SIZE}
34
+
35
+ python tools/checkpoint/convert.py \
36
+ --model-type GPT \
37
+ --loader loader_mixtral_hf \
38
+ --saver mcore \
39
+ --target-tensor-parallel-size ${TARGET_TP_SIZE} \
40
+ --target-pipeline-parallel-size ${TARGET_PP_SIZE} \
41
+ --target-expert-parallel-size ${TARGET_EP_SIZE} \
42
+ --load-dir ${HF_FORMAT_DIR} \
43
+ --save-dir ${MEGATRON_FORMAT_DIR} \
44
+ --tokenizer-model ${TOKENIZER_MODEL}
45
+ ```
46
+
47
+ ## Text generation with Mixtral 8x7B
48
+ Inference with Mixtral 8x7B requires at least 2 GPUS, such that a distributed checkpoint with EP>=2 or PP>=2 converted with above script is needed.
49
+
50
+ The Megatron-LM have included a simple REST server to use for text generation in `tools/run_text_generation_server.py`, launch it with the following script:
51
+ ```
52
+ #!/bin/bash
53
+ # This example will start serving the Mixtral 8x7B model.
54
+ DISTRIBUTED_ARGS="--nproc_per_node 2 \
55
+ --nnodes 1 \
56
+ --node_rank 0 \
57
+ --master_addr localhost \
58
+ --master_port 6000"
59
+
60
+ CHECKPOINT=<Path to checkpoint>
61
+ TOKENIZER_MODEL=<Path to tokenizer (e.g. /tokenizer.model)>
62
+
63
+ export CUDA_DEVICE_MAX_CONNECTIONS=1
64
+
65
+ pip install flask-restful
66
+
67
+ torchrun $DISTRIBUTED_ARGS tools/run_text_generation_server.py \
68
+ --tensor-model-parallel-size 1 \
69
+ --pipeline-model-parallel-size 2 \
70
+ --expert-model-parallel-size 1 \
71
+ --load ${CHECKPOINT} \
72
+ --tokenizer-type Llama2Tokenizer \
73
+ --tokenizer-model $TOKENIZER_MODEL \
74
+ --use-mcore-models \
75
+ --max-position-embeddings 32768 \
76
+ --num-layers 32 \
77
+ --hidden-size 4096 \
78
+ --ffn-hidden-size 14336 \
79
+ --num-attention-heads 32 \
80
+ --normalization RMSNorm \
81
+ --disable-bias-linear \
82
+ --position-embedding-type rope \
83
+ --no-position-embedding \
84
+ --swiglu \
85
+ --untie-embeddings-and-output-weights \
86
+ --group-query-attention \
87
+ --num-query-groups 8 \
88
+ --bf16 \
89
+ --micro-batch-size 1 \
90
+ --seq-length 1024 \
91
+ --seed 42 \
92
+ --num-experts 8 \
93
+ --moe-router-topk 2 \
94
+ --moe-token-dispatcher-type alltoall \
95
+ --moe-grouped-gemm \
96
+ --mock-data \
97
+ --rotary-base 1000000
98
+ ```
99
+
100
+ Once the server is running you can use `tools/text_generation_cli.py` to query it, it takes one argument which is the host the server is running on.
101
+
102
+ ```
103
+ python tools/text_generation_cli.py localhost:5000
104
+ ```
105
+
106
+
107
+ ## Finetuning from pretrained Mixtral 8x7B
108
+ To finetuning pretrained Mixtral 8x7B, use the following scripts:
109
+
110
+
111
+ ```bash
112
+ PYTORCH_IMAGE=nvcr.io/nvidia/pytorch:24.04-py3
113
+ CHECKPOINT_PATH="" # Speicfy path to checkpoint dir
114
+ TOKENIZER_MODEL="" # Specify path to tokenizer.model
115
+ DATA_PATH="" # Specify path to data
116
+
117
+ docker run \
118
+ --gpus=all \
119
+ --ipc=host \
120
+ --workdir /workspace/megatron-lm \
121
+ -v /path/to/data:/path/to/data \
122
+ -v /path/to/megatron-lm:/workspace/megatron-lm \
123
+ $PYTORCH_IMAGE \
124
+ bash examples/mixtral/train_mixtral_8x7b_distributed.sh $CHECKPOINT_PATH $TOKENIZER_MODEL $DATA_PATH
125
+ ```
126
+
127
+ The above functionality also applys to Mixtral 8x22B actually, you should set the model config (including hidden_size/head_num/num_layers/ffn_hidden_size) properly according to the original [config](https://huggingface.co/mistralai/Mixtral-8x22B-v0.1/blob/main/config.json).
128
+
129
+ ## Acknowledgements
130
+ Contributors outside NVIDIA for the huggingface converter and example of Mixtral models in Megatron-Core:
131
+ - Peng Li <jerry.lp@alibaba-inc.com>
132
+ - Jun Huang <huangjun.hj@alibaba-inc.com>
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/mixtral/train_mixtral_8x7b_distributed.sh ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Runs Mixtral 8x7B model
4
+
5
+ export CUDA_DEVICE_MAX_CONNECTIONS=1
6
+
7
+ GPUS_PER_NODE=8
8
+ # Change for multinode config
9
+ MASTER_ADDR=${MASTER_ADDR:-"localhost"}
10
+ MASTER_PORT=${MASTER_PORT:-"6000"}
11
+ NNODES=${SLURM_NNODES:-"1"}
12
+ NODE_RANK=${RANK:-"0"}
13
+ WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES))
14
+
15
+ CHECKPOINT_PATH=$1
16
+ TOKENIZER_MODEL=$2
17
+ DATA_PATH=$3
18
+
19
+ DISTRIBUTED_ARGS=(
20
+ --nproc_per_node $GPUS_PER_NODE
21
+ --nnodes $NNODES
22
+ --node_rank $NODE_RANK
23
+ --master_addr $MASTER_ADDR
24
+ --master_port $MASTER_PORT
25
+ )
26
+
27
+ MODEL_ARGS=(
28
+ --use-mcore-models
29
+ --disable-bias-linear
30
+ --seq-length 4096
31
+ --max-position-embeddings 32768
32
+ --num-layers 32
33
+ --hidden-size 4096
34
+ --ffn-hidden-size 14336
35
+ --num-attention-heads 32
36
+ --init-method-std 0.01
37
+ --attention-dropout 0.0
38
+ --hidden-dropout 0.0
39
+ --normalization RMSNorm
40
+ --position-embedding-type rope
41
+ --swiglu
42
+ --untie-embeddings-and-output-weights
43
+ --group-query-attention
44
+ --num-query-groups 8
45
+ --no-masked-softmax-fusion
46
+ --no-position-embedding
47
+ --rotary-base 1000000
48
+ )
49
+
50
+ MOE_ARGS=(
51
+ --num-experts 8
52
+ --moe-router-topk 2
53
+ --moe-router-load-balancing-type aux_loss
54
+ --moe-aux-loss-coeff 1e-2
55
+ --moe-grouped-gemm
56
+ --moe-token-dispatcher-type alltoall
57
+ --overlap-param-gather
58
+ --overlap-grad-reduce
59
+ )
60
+
61
+ DATA_ARGS=(
62
+ --tokenizer-type Llama2Tokenizer
63
+ --tokenizer-model ${TOKENIZER_MODEL}
64
+ --data-path $DATA_PATH
65
+ --split 99990,8,2
66
+ )
67
+
68
+ TRAINING_ARGS=(
69
+ --micro-batch-size 1
70
+ --global-batch-size 256
71
+ --lr 1e-4
72
+ --train-iters 500000
73
+ --lr-decay-iters 320000
74
+ --lr-decay-style cosine
75
+ --min-lr 1.0e-5
76
+ --weight-decay 0.1
77
+ --lr-warmup-iters 500
78
+ --clip-grad 1.0
79
+ --bf16
80
+ )
81
+
82
+ MODEL_PARALLEL_ARGS=(
83
+ --tensor-model-parallel-size 1
84
+ --pipeline-model-parallel-size 4
85
+ --expert-model-parallel-size 8
86
+ --use-distributed-optimizer
87
+ --sequence-parallel
88
+ )
89
+
90
+ LOGGING_ARGS=(
91
+ --log-interval 1 \
92
+ --save-interval 10000 \
93
+ --eval-interval 1000 \
94
+ --eval-iters 10 \
95
+ --save $CHECKPOINT_PATH \
96
+ --load $CHECKPOINT_PATH \
97
+ --tensorboard-dir "${CHECKPOINT_PATH}/tensorboard" \
98
+ --no-load-optim \
99
+ --no-load-rng
100
+ )
101
+
102
+ if [ -n "${WANDB_API_KEY}" ]; then
103
+ LOGGING_ARGS+=(
104
+ --wandb-project ${WANDB_PROJECT:-"Mixtral"}
105
+ --wandb-exp-name ${WANDB_NAME:-"Mixtral_8x7B"}
106
+ )
107
+ fi
108
+
109
+
110
+ torchrun ${DISTRIBUTED_ARGS[@]} pretrain_gpt.py \
111
+ ${MODEL_ARGS[@]} \
112
+ ${MOE_ARGS[@]} \
113
+ ${DATA_ARGS[@]} \
114
+ ${TRAINING_ARGS[@]} \
115
+ ${MODEL_PARALLEL_ARGS[@]} \
116
+ ${LOGGING_ARGS[@]}
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/Dockerfile ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Base image: NVIDIA PyTorch container with CUDA, cuDNN, NCCL, Python, and uv pre-installed
2
+ FROM nvcr.io/nvidia/pytorch:25.12-py3
3
+
4
+ # Install JRE for pycocoevalcap
5
+ RUN apt-get update && \
6
+ apt-get install -y --no-install-recommends \
7
+ default-jre && \
8
+ apt-get clean && \
9
+ rm -rf /var/lib/apt/lists/*
10
+
11
+ # Using --break-system-packages to allow system-wide installation in managed environment
12
+ RUN uv pip install --system --no-cache --break-system-packages \
13
+ einops \
14
+ einops-exts \
15
+ sentencepiece \
16
+ braceexpand \
17
+ webdataset \
18
+ packaging \
19
+ "transformers<5.0.0" \
20
+ datasets \
21
+ accelerate \
22
+ timm \
23
+ pytest-cov \
24
+ pytest_mock \
25
+ nltk \
26
+ wrapt \
27
+ zarr \
28
+ tensorstore \
29
+ black \
30
+ isort \
31
+ click \
32
+ pycocoevalcap \
33
+ "megatron-energon[av_decode]~=6.0" \
34
+ mistral-common \
35
+ tiktoken \
36
+ # Additional dependencies for megatron-core[mlm]
37
+ flask-restful \
38
+ wandb \
39
+ bitstring \
40
+ filetype
41
+ setuptools
42
+
43
+ # Install CLIP from GitHub
44
+ RUN uv pip install --system --no-cache --break-system-packages --no-build-isolation \
45
+ git+https://github.com/openai/CLIP.git
46
+
47
+ # Install packages with --no-deps to avoid outdated and unnecessary dependencies
48
+ RUN uv pip install --system --no-cache --break-system-packages --no-deps \
49
+ open_clip_torch \
50
+ "open-flamingo[eval]"
51
+
52
+ # Copy Megatron-LM source and install megatron-core
53
+ # This assumes the build context is the Megatron-LM root directory
54
+ # Build with: docker build -t megatron-multimodal -f examples/multimodal/Dockerfile .
55
+ WORKDIR /workspace/megatron-lm
56
+ COPY . .
57
+
58
+ # Install megatron-core in editable mode for development
59
+ RUN uv pip install --system --no-cache --break-system-packages --no-build-isolation -e ".[mlm]"
60
+
61
+ # Set working directory to examples for convenience
62
+ WORKDIR /workspace/megatron-lm
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/README.md ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Multimodal Example
2
+
3
+ *NOTE: This example is under active development and is expected change.*
4
+
5
+ The following walks through all the steps required to pretrain and instruction tune a llava architecture vision-language model (VLM). It is important to precisely follow all steps to obtain the benchmark scores at the end.
6
+
7
+ This example has been tested on an A100 based DGX cluster. Pretraining and instruction tuning took approximately 1 day and 11 hours respectively on 64 GPUs using four way tensor parallelism (tp=4). Training speed will scale approximately linearly with number of GPUs available.
8
+
9
+ Multimodal support in megatron is still under active development. This example is not intended to produce state-of-the-art model quality (that would require more data and model refinements), it is merely intended to demonstrate the multimodal functionality in megatron. If you hit any problems, please open a github issue.
10
+
11
+ ## Setup
12
+
13
+ ### Docker container
14
+
15
+ You can build a docker container using `examples/multimodal/Dockerfile` to run this example.
16
+ ```
17
+ # At the Megatron-LM root directory, execute the following
18
+ docker build -t megatron-multimodal -f examples/multimodal/Dockerfile .
19
+ ```
20
+
21
+ ### Language model
22
+
23
+ Follow the instructions in [Mistral](../../docs/llama_mistral.md#mistral-7b) to download weights for Mistral-7B-Instruct-v0.3 from HuggingFace and convert to mcore format with tensor parallel size 4.
24
+ Please use the tokenizer from HuggingFace.
25
+
26
+ ### Vision model
27
+
28
+ This example uses the OpenAI CLIP `ViT-L/14@336px` Vision model. To download the weights from OpenAI and convert them to a format that can be loaded in megatron, please run the following:
29
+
30
+ ```
31
+ python examples/multimodal/model_converter/clip_converter.py --download-root /some/download/folder --output /some/output/folder --tensor-parallel-size 4 --use-te
32
+ ```
33
+
34
+ ### Combined model checkpoint
35
+
36
+ Update the paths to point to the mcore converted CLIP and Mistral models and run the following script to combine the Mistral and CLIP models into a single multimodal checkpoint folder:
37
+
38
+ ```
39
+ examples/multimodal/combine_lm_vision_checkpoints.sh /path/to/mistral/model /path/to/clip/model /output/dir
40
+ ```
41
+
42
+ ## Training
43
+
44
+ ### Pretraining
45
+
46
+ 1. Download the LLavA-Pretrain dataset from Hugging Face and unzip the images folder (NOTE: 79GB of disk space required):
47
+
48
+ ```
49
+ git clone https://huggingface.co/datasets/liuhaotian/LLaVA-Pretrain
50
+ cd LLaVA-Pretrain
51
+ unzip images.zip
52
+ ```
53
+
54
+ 3. Run the following script to convert the data to webdataset format:
55
+
56
+ ```
57
+ cd <megatron-lm dir>
58
+ python examples/multimodal/convert_llava_pretrain_to_wds.py
59
+ ```
60
+
61
+ 4. Run the following command to convert to megatron-energon format:
62
+
63
+ ```
64
+ cd <LLaVA-Pretrain dir>/wds
65
+ energon prepare ./
66
+ ```
67
+
68
+ select the following values for the presented options:
69
+
70
+ ```
71
+ > Please enter a desired train/val/test split like "0.5, 0.2, 0.3" or "8,1,1": 9,1,0
72
+ > Do you want to create a dataset.yaml interactively? [Y/n]: Y
73
+ > Please enter a number to choose a class: 9 (VQASample)
74
+ > Do you want to set a simple field_map[Y] (or write your own sample_loader [n])? [Y/n]: Y
75
+ > Please enter a webdataset field name for 'image' (<class 'torch.Tensor'>): jpg
76
+ > Please enter a webdataset field name for 'context' (<class 'str'>): json[0][value]
77
+ > Please enter a webdataset field name for 'answers' (typing.Optional[typing.List[str]], default: None): json[1][value]
78
+ > Please enter a webdataset field name for 'answer_weights' (typing.Optional[torch.Tensor], default: None):
79
+ ```
80
+
81
+ 5. Update `pretrain_dataset.yaml` so that both `path` variables point to `LLaVA-Pretrain/wds`
82
+
83
+ 6. Run the following script to pretrain a llava model for image captioning:
84
+
85
+ ```
86
+ cd <megatron-lm dir>
87
+ examples/multimodal/pretrain_mistral_clip.sh
88
+ ```
89
+
90
+ All being well you should observe training and validation loss curves similar to the following:
91
+
92
+ <img src="assets/pretrain_curves.png" alt="Pretraining loss curves" width="600"/>
93
+
94
+ These curves were obtained with global batch size of 256. Changing this value will likely change the curves. For pretraining and instruction tuning llava models we have found that loss curves are an unreliable predictor of downstream task performance. Therefore it is necessary to run test generation and evaluation on a range of metrics to understand model quality. We intend to add training time zero-shot evaluation in a future update.
95
+
96
+ You can execute the pretraining script multiple times to resume training. On resuming, the latest model, optimizer, and dataloader state are loaded.
97
+
98
+ ### SFT
99
+
100
+ 1. Prepare an instruction tuning dataset such in [megatron-energon format](https://nvidia.github.io/Megatron-Energon/data_prep.html#). NOTE: we do not provide instructions for this.
101
+
102
+ 2. Update `sft_dataset.yaml` so that both `path` variables point to the train and val splits of your instruction tuning dataset.
103
+
104
+ Run the following script to instruction tune the pre-trained llava model:
105
+
106
+ ```
107
+ examples/multimodal/sft_mistral_clip.sh
108
+ ```
109
+
110
+ You can execute the SFT script multiple times to resume training. On resuming, the latest model, optimizer, and dataloader state are loaded.
111
+
112
+ ## Evaluation
113
+
114
+ ### Generation
115
+
116
+ Run the following script:
117
+
118
+ ```
119
+ examples/multimodal/text_generation_mistral_clip.sh --input-image-path /path/to/input/images --output-path /some/output/directory \
120
+ --model-path /path/to/model.pt --gt-path /path/to/groundtruth/file --task generation-task-name
121
+ ```
122
+
123
+ where `--task generation-task-name` is the name of the evaluation benchmark such as `captioning` or `MMMU`.
124
+
125
+ ### After pretraining
126
+
127
+ #### COCO captioning
128
+
129
+ 1. Download the COCO 2014 test image set:
130
+
131
+ ```wget http://images.cocodataset.org/zips/test2014.zip```
132
+
133
+ 2. Download COCO test image annotations:
134
+
135
+ ```https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_test.json```
136
+
137
+ 3. First, run text generation using `--task captioning`.
138
+
139
+ 4. Run the following command:
140
+
141
+ ```
142
+ python examples/multimodal/evaluate_coco.py --input-path /output/directory/from/generation --groundtruth-path /path/to/groundtruth/file
143
+ ```
144
+
145
+ For the mistral-7b-instruct plus clip llava model you should obtain a COCO CIDer score of approximately 94.
146
+
147
+ ### After SFT
148
+
149
+ #### MMMU
150
+
151
+ The official MMMU repository is not pip installable currently so please clone their code in `examples/multimodal` by running `git clone https://github.com/MMMU-Benchmark/MMMU.git`.
152
+
153
+ The MMMU dataset is loaded from HuggingFace automatically as part of the code.
154
+
155
+ Run text generation using `--task MMMU`. Then, run the following command:
156
+
157
+ ```
158
+ python examples/multimodal/evaluate_mmmu.py --input-path /output/directory/from/generation
159
+ ```
160
+
161
+ For the mistral-7b-instruct plus clip instruction tuned llava model you should obtain a MMMU score of approximately 38.
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/combine_lm_vision_checkpoints.sh ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #/bin/bash
2
+ MCORE_LM=$1 # <path_to_mcore_lm_model_folder>
3
+ MCORE_VISION=$2 # <path_to_mcore_vision_model_folder>
4
+ OUTPUT_DIR=$3 # <path_to_output_folder_for_combined_checkpoint>
5
+ MODEL_TYPE=$4 # Model type. Default: Mistral CLIP example.
6
+
7
+ if [[ $MODEL_TYPE == "nvlm" ]]; then
8
+ # NVLM TP=8
9
+ python examples/multimodal/combine_state_dicts.py \
10
+ --input \
11
+ ${MCORE_LM}/iter_0000001/mp_rank_00/model_optim_rng.pt \
12
+ ${MCORE_VISION}/iter_0000001/mp_rank_00/model_optim_rng.pt \
13
+ ${MCORE_LM}/iter_0000001/mp_rank_01/model_optim_rng.pt \
14
+ ${MCORE_VISION}/iter_0000001/mp_rank_01/model_optim_rng.pt \
15
+ ${MCORE_LM}/iter_0000001/mp_rank_02/model_optim_rng.pt \
16
+ ${MCORE_VISION}/iter_0000001/mp_rank_02/model_optim_rng.pt \
17
+ ${MCORE_LM}/iter_0000001/mp_rank_03/model_optim_rng.pt \
18
+ ${MCORE_VISION}/iter_0000001/mp_rank_03/model_optim_rng.pt \
19
+ ${MCORE_LM}/iter_0000001/mp_rank_04/model_optim_rng.pt \
20
+ ${MCORE_VISION}/iter_0000001/mp_rank_04/model_optim_rng.pt \
21
+ ${MCORE_LM}/iter_0000001/mp_rank_05/model_optim_rng.pt \
22
+ ${MCORE_VISION}/iter_0000001/mp_rank_05/model_optim_rng.pt \
23
+ ${MCORE_LM}/iter_0000001/mp_rank_06/model_optim_rng.pt \
24
+ ${MCORE_VISION}/iter_0000001/mp_rank_06/model_optim_rng.pt \
25
+ ${MCORE_LM}/iter_0000001/mp_rank_07/model_optim_rng.pt \
26
+ ${MCORE_VISION}/iter_0000001/mp_rank_07/model_optim_rng.pt \
27
+ --prefixes language_model vision_model language_model vision_model language_model vision_model language_model vision_model language_model vision_model language_model vision_model language_model vision_model language_model vision_model \
28
+ --output \
29
+ ${OUTPUT_DIR}/iter_0000001/mp_rank_00/model_optim_rng.pt \
30
+ ${OUTPUT_DIR}/iter_0000001/mp_rank_01/model_optim_rng.pt \
31
+ ${OUTPUT_DIR}/iter_0000001/mp_rank_02/model_optim_rng.pt \
32
+ ${OUTPUT_DIR}/iter_0000001/mp_rank_03/model_optim_rng.pt \
33
+ ${OUTPUT_DIR}/iter_0000001/mp_rank_04/model_optim_rng.pt \
34
+ ${OUTPUT_DIR}/iter_0000001/mp_rank_05/model_optim_rng.pt \
35
+ ${OUTPUT_DIR}/iter_0000001/mp_rank_06/model_optim_rng.pt \
36
+ ${OUTPUT_DIR}/iter_0000001/mp_rank_07/model_optim_rng.pt
37
+ else
38
+ # Mistral CLIP example TP=4.
39
+ python examples/multimodal/combine_state_dicts.py \
40
+ --input \
41
+ ${MCORE_LM}/iter_0000001/mp_rank_00/model_optim_rng.pt \
42
+ ${MCORE_VISION}/iter_0000001/mp_rank_00/model_optim_rng.pt \
43
+ ${MCORE_LM}/iter_0000001/mp_rank_01/model_optim_rng.pt \
44
+ ${MCORE_VISION}/iter_0000001/mp_rank_01/model_optim_rng.pt \
45
+ ${MCORE_LM}/iter_0000001/mp_rank_02/model_optim_rng.pt \
46
+ ${MCORE_VISION}/iter_0000001/mp_rank_02/model_optim_rng.pt \
47
+ ${MCORE_LM}/iter_0000001/mp_rank_03/model_optim_rng.pt \
48
+ ${MCORE_VISION}/iter_0000001/mp_rank_03/model_optim_rng.pt \
49
+ --prefixes language_model vision_model language_model vision_model language_model vision_model language_model vision_model \
50
+ --output \
51
+ ${OUTPUT_DIR}/iter_0000001/mp_rank_00/model_optim_rng.pt \
52
+ ${OUTPUT_DIR}/iter_0000001/mp_rank_01/model_optim_rng.pt \
53
+ ${OUTPUT_DIR}/iter_0000001/mp_rank_02/model_optim_rng.pt \
54
+ ${OUTPUT_DIR}/iter_0000001/mp_rank_03/model_optim_rng.pt
55
+ fi
56
+
57
+ echo 1 > ${OUTPUT_DIR}/latest_checkpointed_iteration.txt
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/combine_state_dicts.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
2
+
3
+ import argparse
4
+ import os
5
+ import sys
6
+
7
+ import torch
8
+
9
+ # Add megatron to the path.
10
+ sys.path.append(
11
+ os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir))
12
+ )
13
+
14
+
15
+ def combine(input_files, module_prefixes, output_files):
16
+ num_inputs_per_output = int(len(input_files) / len(output_files))
17
+
18
+ for output_idx, output_file in enumerate(output_files):
19
+ combined_state_dict = None
20
+
21
+ lb = output_idx * num_inputs_per_output
22
+ ub = (output_idx + 1) * num_inputs_per_output
23
+ current_input_files = input_files[lb:ub]
24
+ current_module_prefixes = module_prefixes[lb:ub]
25
+
26
+ for i, (input_file, module_prefix) in enumerate(
27
+ zip(current_input_files, current_module_prefixes)
28
+ ):
29
+ # initialize the combined state dict using the first provided input file
30
+ current_state_dict = torch.load(input_file, weights_only=False)
31
+ if i == 0:
32
+ combined_state_dict = current_state_dict.copy()
33
+ combined_state_dict["model"] = dict()
34
+
35
+ # copy model state dict and prefix names with the given module keys.
36
+ for k, v in current_state_dict["model"].items():
37
+ combined_state_dict["model"]["%s.%s" % (module_prefix, k)] = v
38
+
39
+ output_dir = os.path.dirname(output_file)
40
+ if not os.path.exists(output_dir):
41
+ os.makedirs(output_dir, exist_ok=True)
42
+ torch.save(combined_state_dict, output_file)
43
+ print("saved:", output_file)
44
+
45
+ print("done.")
46
+
47
+
48
+ if __name__ == "__main__":
49
+ parser = argparse.ArgumentParser(
50
+ description="""
51
+ Combine multiple state dicts into a single state dict.
52
+ The combined state dict is first initialized by taking a copy of the first provided input state dict.
53
+ To avoid conflicts in model parameter names, a prefix must be provided for each input file.
54
+ Model parameter names will be renamed from <original name> to <model prefix>.<original name>.
55
+
56
+
57
+ Example usage:
58
+ python combine_state_dicts.py --input language_model.pt vision_model.pt --prefixes language_model vision_model --output multimodal.pt
59
+ """,
60
+ formatter_class=argparse.RawDescriptionHelpFormatter,
61
+ )
62
+ parser.add_argument("--input", nargs="*", required=True, help="paths to input state dict files")
63
+ parser.add_argument(
64
+ "--prefixes",
65
+ nargs="*",
66
+ required=True,
67
+ help="prefixes to use with each input model's parameters",
68
+ )
69
+ parser.add_argument(
70
+ "--output", nargs="*", required=True, help="path(s) to output state dict file"
71
+ )
72
+
73
+ args = parser.parse_args()
74
+
75
+ assert len(args.input) > 1, "must provide more than 1 input model to combine"
76
+ assert len(args.input) == len(args.prefixes), "each input model must have a corresponding key"
77
+ assert (
78
+ len(args.input) % len(args.output) == 0
79
+ ), "each output file must use the same number of input files"
80
+
81
+ combine(args.input, args.prefixes, args.output)
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/config.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
2
+ from dataclasses import dataclass
3
+
4
+ import torch
5
+
6
+ from megatron.core.activations import fast_gelu, quick_gelu, squared_relu
7
+
8
+
9
+ def get_language_model_config(config):
10
+ if config.language_model_type == "llama3_8b":
11
+ config.activation_func = torch.nn.functional.silu
12
+ config.add_bias_linear = False
13
+ config.bias_activation_fusion = False
14
+ config.gated_linear_unit = True
15
+ config.apply_query_key_layer_scaling = False
16
+ config.layernorm_zero_centered_gamma = (
17
+ False # Zero centered gamma not supported for RMSNorm
18
+ )
19
+ config.bias_dropout_fusion = False
20
+ config.apply_rope_fusion = False
21
+ config.attention_softmax_in_fp32 = True
22
+ config.ffn_hidden_size = 14336
23
+ elif config.language_model_type == "llama3.1_8b":
24
+ config.activation_func = torch.nn.functional.silu
25
+ config.add_bias_linear = False
26
+ config.bias_activation_fusion = False
27
+ config.gated_linear_unit = True
28
+ config.apply_query_key_layer_scaling = False
29
+ config.layernorm_zero_centered_gamma = (
30
+ False # Zero centered gamma not supported for RMSNorm
31
+ )
32
+ config.bias_dropout_fusion = False
33
+ config.apply_rope_fusion = False
34
+ config.attention_softmax_in_fp32 = True
35
+ config.ffn_hidden_size = 14336
36
+ elif config.language_model_type == "llama3.1_70B":
37
+ config.activation_func = torch.nn.functional.silu
38
+ config.add_bias_linear = False
39
+ config.bias_activation_fusion = False
40
+ config.gated_linear_unit = True
41
+ config.apply_query_key_layer_scaling = False
42
+ config.layernorm_zero_centered_gamma = (
43
+ False # Zero centered gamma not supported for RMSNorm
44
+ )
45
+ config.bias_dropout_fusion = False
46
+ config.apply_rope_fusion = False
47
+ config.attention_softmax_in_fp32 = True
48
+ config.ffn_hidden_size = 28672
49
+ elif config.language_model_type == "mistral_7b":
50
+ config.activation_func = torch.nn.functional.silu
51
+ config.add_bias_linear = False
52
+ config.bias_activation_fusion = False
53
+ config.gated_linear_unit = True
54
+ config.apply_query_key_layer_scaling = False
55
+ config.layernorm_zero_centered_gamma = (
56
+ False # Zero centered gamma not supported for RMSNorm
57
+ )
58
+ config.bias_dropout_fusion = False
59
+ config.apply_rope_fusion = False
60
+ config.attention_softmax_in_fp32 = True
61
+ config.ffn_hidden_size = 14336
62
+ elif config.language_model_type == "nemotron5-8b":
63
+ config.add_bias_linear = False
64
+ config.bias_activation_fusion = False
65
+ config.gated_linear_unit = False
66
+ config.bias_dropout_fusion = False
67
+ config.apply_rope_fusion = False
68
+ config.activation_func = squared_relu
69
+ config.ffn_hidden_size = 21504
70
+ config.masked_softmax_fusion = True
71
+ config.attention_softmax_in_fp32 = True
72
+ elif config.language_model_type == "yi-34b":
73
+ config.activation_func = torch.nn.functional.silu
74
+ config.add_bias_linear = False
75
+ config.bias_activation_fusion = False
76
+ config.gated_linear_unit = True
77
+ config.apply_query_key_layer_scaling = False
78
+ config.layernorm_zero_centered_gamma = (
79
+ False # Zero centered gamma not supported for RMSNorm
80
+ )
81
+ config.bias_dropout_fusion = False
82
+ config.apply_rope_fusion = False
83
+ config.attention_softmax_in_fp32 = True
84
+ config.ffn_hidden_size = 20480
85
+ elif config.language_model_type == "qwen2.0_72B":
86
+ config.activation_func = torch.nn.functional.silu
87
+ config.add_bias_linear = False
88
+ config.add_qkv_bias = True
89
+ config.bias_activation_fusion = False
90
+ config.gated_linear_unit = True
91
+ config.apply_query_key_layer_scaling = False
92
+ config.layernorm_zero_centered_gamma = (
93
+ False # Zero centered gamma not supported for RMSNorm
94
+ )
95
+ config.bias_dropout_fusion = False
96
+ config.apply_rope_fusion = False
97
+ config.attention_softmax_in_fp32 = True
98
+ config.ffn_hidden_size = 29568
99
+ elif config.language_model_type == "qwen2.5_7B":
100
+ config.activation_func = torch.nn.functional.silu
101
+ config.add_bias_linear = False
102
+ config.add_qkv_bias = True
103
+ config.bias_activation_fusion = False
104
+ config.gated_linear_unit = True
105
+ config.apply_query_key_layer_scaling = False
106
+ config.layernorm_zero_centered_gamma = (
107
+ False # Zero centered gamma not supported for RMSNorm
108
+ )
109
+ config.bias_dropout_fusion = False
110
+ config.apply_rope_fusion = False
111
+ config.attention_softmax_in_fp32 = True
112
+ config.ffn_hidden_size = 18944
113
+ elif config.language_model_type == "qwen2.5_72B":
114
+ config.activation_func = torch.nn.functional.silu
115
+ config.add_bias_linear = False
116
+ config.add_qkv_bias = True
117
+ config.bias_activation_fusion = False
118
+ config.gated_linear_unit = True
119
+ config.apply_query_key_layer_scaling = False
120
+ config.layernorm_zero_centered_gamma = (
121
+ False # Zero centered gamma not supported for RMSNorm
122
+ )
123
+ config.bias_dropout_fusion = False
124
+ config.apply_rope_fusion = False
125
+ config.attention_softmax_in_fp32 = True
126
+ config.ffn_hidden_size = 29568
127
+ elif config.language_model_type == "nemotron5-hybrid-8b":
128
+ config.activation_func = squared_relu
129
+ config.squared_relu = True
130
+ config.add_bias_linear = False
131
+ config.bias_activation_fusion = False
132
+ config.apply_query_key_layer_scaling = False
133
+ config.gated_linear_unit = False
134
+ config.layernorm_zero_centered_gamma = (
135
+ False # Zero centered gamma not supported for RMSNorm
136
+ )
137
+ config.bias_dropout_fusion = False
138
+ config.attention_softmax_in_fp32 = True
139
+ config.ffn_hidden_size = 21504
140
+ elif config.language_model_type == "nemotron5-hybrid-56b":
141
+ config.activation_func = squared_relu
142
+ config.squared_relu = True
143
+ config.add_bias_linear = False
144
+ config.bias_activation_fusion = False
145
+ config.apply_query_key_layer_scaling = False
146
+ config.gated_linear_unit = False
147
+ config.layernorm_zero_centered_gamma = (
148
+ False # Zero centered gamma not supported for RMSNorm
149
+ )
150
+ config.bias_dropout_fusion = False
151
+ config.attention_softmax_in_fp32 = True
152
+ config.ffn_hidden_size = 32768
153
+ config.mamba_state_dim = 256
154
+ elif config.language_model_type == "llama3.2_1b":
155
+ config.activation_func = torch.nn.functional.silu
156
+ config.add_bias_linear = False
157
+ config.bias_activation_fusion = False
158
+ config.gated_linear_unit = True
159
+ config.apply_query_key_layer_scaling = False
160
+ config.layernorm_zero_centered_gamma = (
161
+ False # Zero centered gamma not supported for RMSNorm
162
+ )
163
+ config.bias_dropout_fusion = False
164
+ config.apply_rope_fusion = False
165
+ config.attention_softmax_in_fp32 = True
166
+ config.ffn_hidden_size = 8192
167
+ elif config.language_model_type.startswith("hf://"):
168
+ # Loaded from HuggingFace config file.
169
+ import transformers
170
+ hf_config = transformers.AutoConfig.from_pretrained(config.language_model_type.split("hf://")[1])
171
+ config.hf_config = hf_config
172
+ config.hidden_size = hf_config.hidden_size
173
+ else:
174
+ raise ValueError(f"unknown language model type {config.language_model_type}")
175
+
176
+ return config
177
+
178
+
179
+ def get_vision_model_config(config, apply_query_key_layer_scaling):
180
+ if config.vision_model_type == "clip":
181
+ config.num_layers = 24
182
+ config.num_attention_heads = 16
183
+ config.add_bias_linear = True
184
+ config.add_qkv_bias = True
185
+ config.hidden_size = 1024
186
+ config.hidden_dropout = 0.0
187
+ config.attention_dropout = 0.0
188
+ config.ffn_hidden_size = 4096
189
+ config.gated_linear_unit = False
190
+ config.activation_func = quick_gelu
191
+ config.kv_channels = 64
192
+ config.num_query_groups = 16
193
+ config.layernorm_zero_centered_gamma = False
194
+ config.apply_query_key_layer_scaling = apply_query_key_layer_scaling
195
+ config.bias_activation_fusion = False
196
+ config.bias_dropout_fusion = False
197
+ config.attention_softmax_in_fp32 = True
198
+ config.normalization = 'LayerNorm'
199
+ config.apply_rope_fusion = False
200
+ elif config.vision_model_type == "siglip":
201
+ config.num_layers = 27
202
+ config.num_attention_heads = 16
203
+ config.add_bias_linear = True
204
+ config.add_qkv_bias = True
205
+ config.hidden_size = 1152
206
+ config.hidden_dropout = 0.0
207
+ config.attention_dropout = 0.0
208
+ config.ffn_hidden_size = 4304
209
+ config.gated_linear_unit = False
210
+ config.activation_func = fast_gelu
211
+ config.kv_channels = 72
212
+ config.num_query_groups = 16
213
+ config.layernorm_zero_centered_gamma = False
214
+ config.apply_query_key_layer_scaling = apply_query_key_layer_scaling
215
+ config.bias_activation_fusion = False
216
+ config.bias_dropout_fusion = False
217
+ config.attention_softmax_in_fp32 = True
218
+ config.normalization = 'LayerNorm'
219
+ config.apply_rope_fusion = False
220
+ config.qk_layernorm = False
221
+ config.layernorm_epsilon = 1e-6
222
+ elif config.vision_model_type == "internvit":
223
+ config.num_layers = 45
224
+ config.num_attention_heads = ((24 // config.tensor_model_parallel_size) + 1) * config.tensor_model_parallel_size
225
+ config.num_query_groups = config.num_attention_heads
226
+ config.add_bias_linear = True
227
+ config.add_qkv_bias = False
228
+ config.hidden_size = 3200
229
+ config.hidden_dropout = 0.0
230
+ config.attention_dropout = 0.0
231
+ config.ffn_hidden_size = 12800
232
+ config.gated_linear_unit = False
233
+ config.activation_func = torch.nn.functional.gelu
234
+ config.layernorm_zero_centered_gamma = False
235
+ config.apply_query_key_layer_scaling = apply_query_key_layer_scaling
236
+ config.bias_activation_fusion = False
237
+ config.bias_dropout_fusion = False
238
+ config.attention_softmax_in_fp32 = True
239
+ config.normalization = 'RMSNorm'
240
+ config.layernorm_epsilon = 1e-6
241
+ config.apply_rope_fusion = False
242
+ elif config.vision_model_type == "internvit300M":
243
+ config.num_layers = 24
244
+ config.num_attention_heads = 16
245
+ config.num_query_groups = config.num_attention_heads
246
+ config.add_bias_linear = True
247
+ config.add_qkv_bias = True
248
+ config.hidden_size = 1024
249
+ config.kv_channels = 64
250
+ config.hidden_dropout = 0.0
251
+ config.ffn_hidden_size = 4096
252
+ config.gated_linear_unit = False
253
+ config.activation_func = torch.nn.functional.gelu
254
+ config.layernorm_zero_centered_gamma = False
255
+ config.apply_query_key_layer_scaling = apply_query_key_layer_scaling
256
+ config.bias_activation_fusion = False
257
+ config.bias_dropout_fusion = False
258
+ config.attention_softmax_in_fp32 = True
259
+ config.normalization = 'LayerNorm'
260
+ config.layernorm_epsilon = 1e-6
261
+ config.apply_rope_fusion = False
262
+ config.qk_layernorm = False
263
+ elif config.vision_model_type == "radio":
264
+ config.num_layers = 32
265
+ config.num_attention_heads = 16
266
+ config.add_bias_linear = True
267
+ config.add_qkv_bias = True
268
+ config.hidden_size = 1280
269
+ config.ffn_hidden_size = 5120
270
+ config.gated_linear_unit = False
271
+ config.activation_func = fast_gelu
272
+ config.kv_channels = 80
273
+ config.num_query_groups = 16
274
+ config.layernorm_zero_centered_gamma = False
275
+ config.apply_query_key_layer_scaling = apply_query_key_layer_scaling
276
+ config.bias_activation_fusion = False
277
+ config.bias_dropout_fusion = False
278
+ config.attention_softmax_in_fp32 = True
279
+ config.normalization = 'LayerNorm'
280
+ config.apply_rope_fusion = False
281
+ config.qk_layernorm = False
282
+ config.layernorm_epsilon = 1e-6
283
+ elif config.vision_model_type == "radio-g":
284
+ config.num_layers = 40
285
+ config.num_attention_heads = 24
286
+ config.add_bias_linear = True
287
+ config.add_qkv_bias = True
288
+ config.hidden_size = 1536
289
+ config.ffn_hidden_size = 4096
290
+ config.gated_linear_unit = True
291
+ config.activation_func = torch.nn.functional.silu
292
+ config.kv_channels = 64
293
+ config.num_query_groups = 24
294
+ config.layernorm_zero_centered_gamma = False
295
+ config.apply_query_key_layer_scaling = apply_query_key_layer_scaling
296
+ config.bias_activation_fusion = False
297
+ config.bias_dropout_fusion = False
298
+ config.attention_softmax_in_fp32 = True
299
+ config.normalization = 'LayerNorm'
300
+ config.apply_rope_fusion = False
301
+ config.qk_layernorm = False
302
+ config.layernorm_epsilon = 1e-6
303
+ elif config.vision_model_type == "cradio-g":
304
+ config.num_layers = 40
305
+ config.num_attention_heads = 24
306
+ config.add_bias_linear = True
307
+ config.add_qkv_bias = True
308
+ config.hidden_size = 1536
309
+ config.ffn_hidden_size = 6144
310
+ config.gated_linear_unit = False
311
+ config.activation_func = fast_gelu
312
+ config.kv_channels = 64
313
+ config.num_query_groups = 24
314
+ config.layernorm_zero_centered_gamma = False
315
+ config.apply_query_key_layer_scaling = apply_query_key_layer_scaling
316
+ config.bias_activation_fusion = False
317
+ config.bias_dropout_fusion = False
318
+ config.attention_softmax_in_fp32 = True
319
+ config.normalization = 'LayerNorm'
320
+ config.apply_rope_fusion = False
321
+ config.qk_layernorm = False
322
+ config.layernorm_epsilon = 1e-6
323
+ elif config.vision_model_type.startswith("hf://"):
324
+ import transformers
325
+ hf_config = transformers.AutoConfig.from_pretrained(config.vision_model_type.split("hf://")[1])
326
+ config.hf_config = hf_config
327
+ config.hidden_size = hf_config.hidden_size
328
+ else:
329
+ raise ValueError(f"unknown vision model type {config.vision_model_type}")
330
+
331
+ return config
332
+
333
+
334
+ def get_vision_projection_config(config, hidden_size):
335
+ # If using FP8, then keep the whole vision projection in FP8.
336
+ config.first_last_layers_bf16 = False
337
+ config.num_layers_at_start_in_bf16 = 0
338
+ config.num_layers_at_end_in_bf16 = 0
339
+
340
+ config.gated_linear_unit = False
341
+ config.bias_activation_fusion = False
342
+ config.add_bias_linear = False
343
+ config.hidden_size = hidden_size # Used as the vision projection output size, i.e., the input to the language model.
344
+ if config.language_model_type == "llama3_8b":
345
+ config.ffn_hidden_size = 14336
346
+ config.activation_func = torch.nn.functional.gelu
347
+ elif config.language_model_type == "llama3.1_8b":
348
+ config.ffn_hidden_size = 4096
349
+ config.activation_func = torch.nn.functional.gelu
350
+ config.layernorm_epsilon = 1e-5
351
+ config.add_bias_linear = True
352
+ config.normalization = "LayerNorm"
353
+ elif config.language_model_type == "mistral_7b":
354
+ config.ffn_hidden_size = 14336
355
+ config.activation_func = torch.nn.functional.gelu
356
+ config.normalization = None
357
+ elif config.language_model_type == "yi-34b":
358
+ config.ffn_hidden_size = 20480
359
+ config.normalization = "LayerNorm"
360
+ config.activation_func = torch.nn.functional.gelu
361
+ elif config.language_model_type == "qwen2.0_72B":
362
+ config.ffn_hidden_size = 29568
363
+ config.normalization = "LayerNorm"
364
+ config.activation_func = torch.nn.functional.gelu
365
+ elif config.language_model_type == "qwen2.5_7B":
366
+ config.ffn_hidden_size = 3584
367
+ config.activation_func = torch.nn.functional.gelu
368
+ elif config.language_model_type == "qwen2.5_72B":
369
+ config.ffn_hidden_size = 29568
370
+ config.normalization = "LayerNorm"
371
+ config.activation_func = torch.nn.functional.gelu
372
+ elif config.language_model_type == "nemotron5-hybrid-56b":
373
+ config.ffn_hidden_size = 32768
374
+ config.activation_func = squared_relu
375
+ elif config.language_model_type in ("nemotron5-8b", "nemotron5-hybrid-8b"):
376
+ config.ffn_hidden_size = 21504
377
+ config.activation_func = squared_relu
378
+ elif config.language_model_type == "llama3.2_1b":
379
+ config.ffn_hidden_size = 2048
380
+ config.activation_func = torch.nn.functional.gelu
381
+ config.normalization = "LayerNorm"
382
+ elif config.language_model_type.startswith("hf://"):
383
+ config.activation_func = torch.nn.functional.gelu
384
+ config.ffn_hidden_size = 4096
385
+ config.normalization = "LayerNorm"
386
+ else:
387
+ raise ValueError(f"unknown language model type {config.language_model_type}")
388
+
389
+ return config
390
+
391
+
392
+ @dataclass
393
+ class EvaluationConfig:
394
+ """Evaluation related configuration."""
395
+ task: str
396
+ dataset: str = ""
397
+
398
+ temperature: float = 1.0
399
+ top_p: float = 0.0
400
+ top_k: int = 0
401
+
402
+ out_seq_length: int = 32
403
+
404
+ output_path: str = ""
405
+
406
+ input_image_path: str = ""
407
+ gt_path: str = ""
408
+ split: str = "validation"
409
+
410
+ num_partitions: int = 0
411
+ partition_id: int = 0
412
+ num_samples_per_partition: int = 0
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/convert_llava_pretrain_to_wds.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import webdataset as wds
4
+
5
+ from tqdm import tqdm
6
+
7
+ llava_pretrain_dir = '<path_to_LLaVA-Pretrain>'
8
+
9
+ # Paths to the dataset files
10
+ json_file = os.path.join(llava_pretrain_dir, 'blip_laion_cc_sbu_558k.json')
11
+ output = os.path.join(llava_pretrain_dir, 'wds')
12
+
13
+ if not os.path.exists(output):
14
+ os.mkdir(output)
15
+
16
+ # Load data
17
+ with open(json_file, 'r') as f:
18
+ data = json.load(f)
19
+
20
+ with wds.ShardWriter(os.path.join(output, 'pretrain-%d.tar'), maxcount=10000) as shard_writer:
21
+ for entry in tqdm(data):
22
+ with open(os.path.join(llava_pretrain_dir, entry['image']), "rb") as img_file:
23
+ image_data = img_file.read()
24
+ sample = {
25
+ "__key__": entry['id'],
26
+ "jpg": image_data,
27
+ "json": json.dumps(entry['conversations']).encode("utf-8"),
28
+ }
29
+ shard_writer.write(sample)
30
+
31
+ print(f"Dataset successfully converted to wds")
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/dataloader_provider.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
2
+ import os
3
+
4
+ import torch
5
+ from dataset_helpers import TaskEncoder, print_error_handler
6
+
7
+ from megatron.core import parallel_state
8
+ from megatron.core.num_microbatches_calculator import get_num_microbatches
9
+ from megatron.core.parallel_state import (
10
+ get_pipeline_model_parallel_rank,
11
+ get_pipeline_model_parallel_world_size,
12
+ get_tensor_model_parallel_rank,
13
+ )
14
+ from megatron.energon import (
15
+ LimitDataset,
16
+ RepeatDataset,
17
+ WorkerConfig,
18
+ get_loader,
19
+ get_savable_loader,
20
+ get_train_dataset,
21
+ get_val_datasets,
22
+ )
23
+ from megatron.training import get_args
24
+ from megatron.training.checkpointing import get_checkpoint_name
25
+
26
+
27
+ def datasets_provider(task_encoder,worker_config=None):
28
+ """Create multimodal train, validation and test datasets."""
29
+ args = get_args()
30
+
31
+ dname = args.data_path[0] if type(args.data_path) is list else args.data_path
32
+ train_dataset = get_train_dataset(
33
+ dname,
34
+ batch_size=args.micro_batch_size,
35
+ task_encoder=task_encoder,
36
+ virtual_epoch_length=1000,
37
+ max_samples_per_sequence=100,
38
+ shuffle_buffer_size=100,
39
+ worker_config=worker_config,
40
+ packing_buffer_size=args.packing_buffer_size,
41
+ handler=print_error_handler,
42
+ image_decode="pil",
43
+ )
44
+
45
+ val_datasets = get_val_datasets(
46
+ dname,
47
+ batch_size=args.micro_batch_size,
48
+ # This is the total number over all workers
49
+ # limit=args.eval_iters * get_num_microbatches(),
50
+ task_encoder=task_encoder,
51
+ worker_config=worker_config,
52
+ packing_buffer_size=args.packing_buffer_size,
53
+ handler=print_error_handler,
54
+ image_decode="pil",
55
+ )
56
+ val_datasets_without_source_datasets = [
57
+ # Limit the dataset to eval_iters * num_microbatches
58
+ LimitDataset(
59
+ # Repeat the inner dataset in case it's too short
60
+ RepeatDataset(val_ds, worker_config=worker_config),
61
+ length=args.eval_iters * get_num_microbatches(),
62
+ worker_config=worker_config,
63
+ reset_after_epoch=True,
64
+ )
65
+ for val_ds, _src_ds in val_datasets
66
+ ]
67
+
68
+ return train_dataset, val_datasets_without_source_datasets, None
69
+
70
+
71
+ def is_first_or_last_stage(pp_size):
72
+ """Check if the current pipeline parallel stage is the first or last stage."""
73
+ if pp_size == 1: # No pipeline parallelism.
74
+ return True
75
+
76
+ # With no separate pipeline stage for the vision model (epp=0),
77
+ # run the dataloader on the first and last pipeline stage.
78
+ pp_rank = get_pipeline_model_parallel_rank()
79
+ is_valid_rank = pp_rank in (0, pp_size-1)
80
+
81
+ return is_valid_rank
82
+
83
+
84
+ def is_dataloader_rank():
85
+ """Check if we should have the dataloader on this tensor and pipeline parallel rank."""
86
+ # Run dataloader only on the first tensor parallel rank (will be broadcasted to others).
87
+ is_first_rank = get_tensor_model_parallel_rank() == 0
88
+
89
+ pp_size = get_pipeline_model_parallel_world_size()
90
+ is_first_rank = is_first_rank and is_first_or_last_stage(pp_size)
91
+
92
+ return is_first_rank
93
+
94
+
95
+ def train_valid_test_dataloaders_provider(train_val_test_num_samples, task_encoder=None):
96
+ """Build multimodal train, validation and test dataloaders."""
97
+ args = get_args()
98
+
99
+ if task_encoder is None:
100
+ task_encoder = TaskEncoder()
101
+
102
+ # Dataloader is only on specific ranks.
103
+ if not is_dataloader_rank():
104
+ return None, None, None
105
+
106
+ worker_debug_path = None
107
+ worker_log_level = 0
108
+
109
+ rank = parallel_state.get_data_parallel_rank()
110
+ world_size = parallel_state.get_data_parallel_world_size()
111
+ data_parallel_group = parallel_state.get_data_parallel_group()
112
+
113
+ worker_config = WorkerConfig(
114
+ rank=rank,
115
+ world_size=world_size,
116
+ num_workers=args.num_workers,
117
+ data_parallel_group=data_parallel_group,
118
+ worker_debug_path=worker_debug_path,
119
+ worker_log_level=worker_log_level,
120
+ )
121
+ train_ds, valid_ds1, test_ds = datasets_provider(task_encoder, worker_config)
122
+
123
+ train_dataloader = get_savable_loader(train_ds, worker_config=worker_config)
124
+ if args.load is not None:
125
+ if getattr(args, "dataloader_save", None):
126
+ dp_rank = parallel_state.get_data_parallel_rank()
127
+ data_save_name = get_checkpoint_name(
128
+ args.dataloader_save,
129
+ args.iteration,
130
+ pipeline_rank=0, # Only the first pipeline parallel rank stores the dataloader checkpoint.
131
+ basename=f"train_dataloader_dprank{dp_rank:03d}.pt",
132
+ )
133
+ if os.path.exists(data_save_name):
134
+ try:
135
+ dataset_state_dict = torch.load(data_save_name, map_location="cpu")
136
+ train_dataloader.restore_state_rank(dataset_state_dict["dataloader_state_dict"])
137
+ print(f"restored dataset state from {data_save_name}")
138
+ except Exception as e:
139
+ print("loading dataset state failed. Skipping. " + str(e))
140
+ else:
141
+ print(f"dataset state {data_save_name} does not exist")
142
+
143
+ valid_dataloader = [
144
+ EnergonDataloader(get_loader(valid_ds, worker_config=worker_config))
145
+ for valid_ds in valid_ds1
146
+ ]
147
+ test_dataloader = None
148
+
149
+ return EnergonDataloader(train_dataloader), valid_dataloader, EnergonDataloader(test_dataloader)
150
+
151
+
152
+ class EnergonDataloader:
153
+ """A wrapper to use Megatron Energon dataloader with the Megatron-LM training loop."""
154
+ def __init__(self, dataloader):
155
+ self._dataloader = dataloader
156
+ self._iter = iter(cyclic_iter(dataloader))
157
+
158
+ def __next__(self):
159
+ return self._iter.__next__()
160
+
161
+ def __iter__(self):
162
+ return self._iter.__iter__()
163
+
164
+ def save_state(self):
165
+ return self._dataloader.save_state_rank()
166
+
167
+
168
+ def cyclic_iter(iter):
169
+ while True:
170
+ for x in iter:
171
+ yield x
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/dataset_helpers.py ADDED
@@ -0,0 +1,966 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
2
+ import bisect
3
+ import dataclasses
4
+ import json
5
+ import re
6
+ import sys
7
+ import traceback
8
+ from dataclasses import dataclass
9
+ from typing import Dict, List, Optional, Tuple, Union
10
+
11
+ from image_processing import ImageTransform, find_closest_aspect_ratio, find_closest_area_weighted_aspect_ratio
12
+ from PIL import Image
13
+ from torchvision.transforms import ToPILImage
14
+ import numpy as np
15
+ import torch
16
+
17
+ from energon_util import OfflineTargetAspectRatioSample, SampleListSample
18
+ from megatron.core.models.multimodal.context_parallel import get_padding
19
+ from megatron.core.models.multimodal.llava_model import IGNORE_INDEX, IMAGE_TOKEN, VIDEO_TOKEN
20
+ from megatron.core.models.vision.clip_vit_model import get_num_image_embeddings
21
+ from megatron.energon import (
22
+ Batch,
23
+ CaptioningSample,
24
+ DefaultTaskEncoder,
25
+ OCRSample,
26
+ Sample,
27
+ SimilarityInterleavedSample,
28
+ VQASample,
29
+ MultiChoiceVQASample
30
+ )
31
+ from megatron.energon.task_encoder.base import stateless
32
+ from megatron.training import get_args, get_tokenizer
33
+
34
+
35
+ @dataclass
36
+ class ImageTaskSample(Sample):
37
+ __key__: str
38
+ __restore_key__: Tuple[Union[str, int, tuple], ...]
39
+ __subflavor__: Dict
40
+ __subflavors__: Dict
41
+ # (c, h, w)
42
+ imgs: List[torch.Tensor]
43
+ num_tiles: List[int]
44
+ tokens: torch.Tensor
45
+ total_len: int # Total token count in the sample, including text and image tokens
46
+ labels: torch.Tensor = None
47
+
48
+
49
+ @dataclass
50
+ class ImageTaskSamplePacked(Sample):
51
+ """Dataclass to store a single packed sample (not a batch).
52
+
53
+ P = Number of sub-samples in the packed sample
54
+ seq_len = Total sequence length
55
+ num_imgs = Number of images across all samples in the packed sample
56
+ """
57
+
58
+ __key__: str # Sample name
59
+ __restore_key__: Tuple[Union[str, int, tuple], ...]
60
+ __subflavor__: Dict # Sample metadata. Deprecated.
61
+ __subflavors__: Dict # Sample metadata.
62
+ tokens: torch.Tensor # Input tokens packed into a single tensor (seq_len,)
63
+ labels: torch.Tensor # Target tokens packed into a single tensor (seq_len,)
64
+ imgs: List[torch.Tensor] # Input images
65
+ num_tiles: List[int] # Number of tiles for each image of each sample (num_imgs)
66
+ max_length: int # Maximum length across sub-samples.
67
+ cu_lengths: List[int] # Cumulative length of each sub-sample in this packed sample incl. text and image tokens (P,)
68
+
69
+
70
+ # Typing for the resulting batch data after encode_batch()
71
+ @dataclass
72
+ class ImageTaskBatchPacked(Batch):
73
+ """Dataclass to store a batch of packed samples.
74
+
75
+ N = Batch size
76
+ P = Number of samples in the packed sample
77
+ seq_len = Maximum sequence length
78
+ num_imgs = Number of images across all samples in the packed sample
79
+ """
80
+
81
+ __key__: List[str] # Sample names
82
+ __restore_key__: Tuple[Union[str, int, tuple], ...]
83
+ __subflavor__: Dict # Sample metadata. Deprecated.
84
+ __subflavors__: List[Dict] # Sample metadatas.
85
+ tokens: torch.Tensor # Input tokens packed and padded (N, seq_len)
86
+ labels: torch.Tensor # Target tokens packed and padded (N, seq_len)
87
+ imgs: torch.Tensor # All image tiles stacked into a single tensor (num_tiles, C, H, W)
88
+ num_tiles: List[List[int]] # Number of tiles per image (N, num_imgs)
89
+ max_lengths: List[int] # Maximum length across sub-samples (N,)
90
+ cu_lengths: List[List[int]] # Cumulative length of each sub-sample in each packed sample of the batch (N, P)
91
+
92
+
93
+ # Based on https://github.com/hiyouga/LLaMA-Factory/blob/641d0dab08d96a93c34657742213d8994d9ed476/src/llamafactory/data/processors/processor_utils.py#L19
94
+ # Copyright (c) 2024 LLaMA-Factory. Apache license 2.0.
95
+ def search_for_fit(numbers: List[int], capacity: int) -> int:
96
+ """Finds the index of largest number that fits into the knapsack with the given capacity."""
97
+ index = bisect.bisect(numbers, capacity)
98
+ return -1 if index == 0 else (index - 1)
99
+
100
+
101
+ # Based on https://github.com/hiyouga/LLaMA-Factory/blob/641d0dab08d96a93c34657742213d8994d9ed476/src/llamafactory/data/processors/processor_utils.py#L27
102
+ # Copyright (c) 2024 LLaMA-Factory. Apache license 2.0.
103
+ def greedy_knapsack(item_sizes: List[int], samples: List, max_capacity: int) -> List:
104
+ """Greedy algorithm with binary search for the knapsack problem.
105
+
106
+ Pack as many samples as possible given a maximum capacity and capacities of individual samples.
107
+ Used if sequence packing is enabled.
108
+ """
109
+ assert len(item_sizes) == len(samples), "sample lengths and samples must have the same length."
110
+
111
+ knapsacks = []
112
+
113
+ if len(item_sizes) == 0:
114
+ return knapsacks
115
+
116
+ # Sort sample lengths and samples together.
117
+ sorted_item_sizes, sorted_samples = zip(*sorted(zip(item_sizes, samples), key=lambda x: x[0]))
118
+ sorted_item_sizes = list(sorted_item_sizes)
119
+ sorted_samples = list(sorted_samples)
120
+
121
+ # Check if all samples fit in the knapsack capacity.
122
+ if sorted_item_sizes[-1] > max_capacity:
123
+ raise ValueError(f"knapsack: A sample is larger {sorted_item_sizes[-1]} than the max_sequence_length {max_capacity}.")
124
+
125
+ while sorted_item_sizes:
126
+ current_knapsack = []
127
+ remaining_capacity = max_capacity
128
+
129
+ while True:
130
+ idx = search_for_fit(sorted_item_sizes, remaining_capacity)
131
+ if idx == -1:
132
+ break # Can't fit more samples.
133
+
134
+ remaining_capacity -= sorted_item_sizes[idx]
135
+
136
+ sorted_item_sizes.pop(idx)
137
+ sample = sorted_samples.pop(idx)
138
+ current_knapsack.append(sample)
139
+
140
+ knapsacks.append(current_knapsack)
141
+
142
+ return knapsacks
143
+
144
+
145
+ class TaskEncoder(DefaultTaskEncoder[OCRSample, OCRSample, ImageTaskBatchPacked, dict]):
146
+ """A simple task encoder for VLMs."""
147
+
148
+ def __init__(
149
+ self
150
+ ):
151
+ super().__init__()
152
+
153
+ self.args = get_args()
154
+
155
+ self.tokenizer = get_tokenizer()
156
+ with open(self.args.prompt_path, "r") as f:
157
+ self.manual_prompts = json.load(f)
158
+ self.dataloader_seq_length = self.args.dataloader_seq_length # Always return samples of this length.
159
+ self.packing_seq_length = self.args.packing_seq_length # Packing sequence length, if packing is enabled.
160
+ self.is_packing_enabled = self.args.packing_buffer_size is not None and self.args.packing_buffer_size > 0
161
+
162
+ if self.dataloader_seq_length and self.packing_seq_length:
163
+ assert self.dataloader_seq_length >= self.packing_seq_length, "dataloader sequence length must be greater than or equal to the packing sequence length"
164
+
165
+ if self.is_packing_enabled:
166
+ assert self.packing_seq_length > 0, "packing sequence length must be set"
167
+
168
+ self.num_image_embeddings_per_tile = get_num_image_embeddings(
169
+ self.args.img_h,
170
+ self.args.img_w,
171
+ self.args.patch_dim,
172
+ self.args.vision_model_type,
173
+ self.args.disable_vision_class_token,
174
+ 1,
175
+ self.args.pixel_shuffle,
176
+ self.args.use_tile_tags,
177
+ self.args.max_num_tiles,
178
+ self.args.tokenizer_prompt_format,
179
+ )
180
+
181
+ self.txt_to_token_dict = {}
182
+
183
+ self.img_h, self.img_w = self.args.img_h, self.args.img_w
184
+ self.img_token_id = self.tokenizer.convert_tokens_to_ids(IMAGE_TOKEN)
185
+ # This map is used to reduce the number of tiles used per image if the number of tokens is
186
+ # larger than the decoder_seq_length.
187
+ self.num_tiles_degradation_map = {12:8, 8:6, 6:4, 4:2, 2:1, 1:1}
188
+
189
+ self.find_closest_aspect_ratio_fn = (
190
+ find_closest_area_weighted_aspect_ratio if self.args.use_area_weighted_aspect_ratio
191
+ else find_closest_aspect_ratio)
192
+
193
+ self.transform_img = ImageTransform(self.img_h, self.args.vision_model_type)
194
+
195
+ def _get_total_seq_length(self, input_ids, num_tiles):
196
+ """Calculate expected sequence length given text tokens length and number of tiles."""
197
+ total_num_images = len(num_tiles)
198
+ total_num_tiles = sum(num_tiles)
199
+ total_len = len(input_ids) + total_num_tiles * self.num_image_embeddings_per_tile - total_num_images
200
+ return total_len
201
+
202
+ def _truncate_for_packing(self, input_ids, target, num_tiles):
203
+ """Truncate tokens and labels if they exceed packing sequence length."""
204
+ total_num_images = len(num_tiles)
205
+ total_num_tiles = sum(num_tiles)
206
+ total_img_embeddings_len = total_num_tiles * self.num_image_embeddings_per_tile
207
+ max_text_tokens = self.packing_seq_length - total_img_embeddings_len + total_num_images
208
+
209
+ input_ids = input_ids[:max_text_tokens]
210
+ target = target[:max_text_tokens]
211
+
212
+ # If truncate causes all labels to be ignored, then skip the sample
213
+ if (target == IGNORE_INDEX).all():
214
+ raise ValueError(f"all targets will be ignored after truncation: {input_ids}")
215
+
216
+ return input_ids, target
217
+
218
+ @stateless(restore_seeds=True)
219
+ def encode_sample(self, sample: Union[CaptioningSample, OCRSample, VQASample, SimilarityInterleavedSample]):
220
+ if isinstance(sample, OCRSample):
221
+ if "pdfa" in sample.__key__:
222
+ yield self.combined_ocr_encoder(sample, task_type='encode_pdf')
223
+ elif "multi" in sample.__key__:
224
+ yield self.combined_ocr_encoder(sample, task_type='_encode_ocr')
225
+ else:
226
+ yield self.combined_ocr_encoder(sample, task_type='encode_ocr_ref')
227
+ elif isinstance(sample, CaptioningSample):
228
+ yield self.encode_captioning(sample)
229
+ elif isinstance(sample, VQASample):
230
+ is_llava_training = sample.__subflavors__["is_llava_training"] if "is_llava_training" in sample.__subflavors__ else False
231
+
232
+ if "llava" in sample.__key__ or is_llava_training:
233
+ yield self.encode_llava_pretrain(sample)
234
+ else:
235
+ yield self.encode_any_single_turn_vqa(sample)
236
+ elif isinstance(sample, SimilarityInterleavedSample):
237
+ yield self.encode_llava_sft(sample)
238
+ elif isinstance(sample, MultiChoiceVQASample):
239
+ yield self.encode_any_single_turn_vqa(sample)
240
+ # Because the SampleListSample is defined in the Megatron module but loaded by the Energon
241
+ # library, we need to resort to the more brittle check:
242
+ elif type(sample).__name__ == "SampleListSample":
243
+ yield self.encode_sample_list(sample)
244
+ else:
245
+ raise NotImplementedError("Sample format not supported", sample)
246
+
247
+ def encode_captioning(self, sample: CaptioningSample):
248
+ """Encode CaptioningSample."""
249
+ augment = sample.__subflavors__.get("augmentation")
250
+
251
+ imgs = self.transform_img(
252
+ sample.image, self.img_h, self.img_w, self.args.use_tiling, self.args.max_num_tiles, self.args.use_thumbnail, augment,
253
+ find_closest_aspect_ratio_fn=self.find_closest_aspect_ratio_fn
254
+ )
255
+ num_tiles = [len(imgs)]
256
+
257
+ prompt_list = self.manual_prompts["CaptioningPretraining"]["raw"]
258
+
259
+ prompt_idx = np.random.randint(len(prompt_list))
260
+ cur_prompt = prompt_list[prompt_idx]
261
+ cur_prompt = IMAGE_TOKEN + "\n" + cur_prompt + "\n"
262
+
263
+ caption = sample.caption.strip()
264
+
265
+ split_by_line_flag = sample.__subflavors__.get("SplitByLine")
266
+ if split_by_line_flag:
267
+ caption_list = caption.split('\n')
268
+ caption = np.random.choice(caption_list)
269
+
270
+ conv = [
271
+ # Note: no system message.
272
+ {"role": "user", "content": cur_prompt},
273
+ {"role": "assistant", "content": caption},
274
+ ]
275
+
276
+ input_ids, target = self.tokenizer.tokenize_conversation(conv, True, False)
277
+
278
+ if self.is_packing_enabled:
279
+ input_ids, target = self._truncate_for_packing(input_ids, target, num_tiles)
280
+
281
+ return ImageTaskSample(
282
+ __key__=sample.__key__,
283
+ __restore_key__=sample.__restore_key__,
284
+ __subflavor__=None,
285
+ __subflavors__=sample.__subflavors__,
286
+ imgs=imgs,
287
+ num_tiles=num_tiles,
288
+ tokens=torch.tensor(input_ids),
289
+ labels=torch.tensor(target),
290
+ total_len=self._get_total_seq_length(input_ids, num_tiles),
291
+ )
292
+
293
+ def encode_llava_pretrain(self, sample: VQASample):
294
+ """Encode pretrain sample in LLAVA style."""
295
+ augment = sample.__subflavors__.get("augmentation", False)
296
+
297
+ imgs = self.transform_img(
298
+ sample.image, self.img_h, self.img_w, self.args.use_tiling, self.args.max_num_tiles, self.args.use_thumbnail, augment,
299
+ find_closest_aspect_ratio_fn=self.find_closest_aspect_ratio_fn
300
+ )
301
+ num_tiles = [len(imgs)]
302
+
303
+ # LLAVA training: override text-prompt with just the image.
304
+ conv = [
305
+ # Note: no system message.
306
+ {"role": "user", "content": IMAGE_TOKEN + "\n"},
307
+ {"role": "assistant", "content": sample.answers},
308
+ ]
309
+
310
+ input_ids, target = self.tokenizer.tokenize_conversation(conv, True, False)
311
+
312
+ if self.is_packing_enabled:
313
+ input_ids, target = self._truncate_for_packing(input_ids, target, num_tiles)
314
+
315
+ return ImageTaskSample(
316
+ __key__=sample.__key__,
317
+ __restore_key__=sample.__restore_key__,
318
+ __subflavor__=None,
319
+ __subflavors__=sample.__subflavors__,
320
+ imgs=imgs,
321
+ num_tiles=num_tiles,
322
+ tokens=torch.tensor(input_ids),
323
+ labels=torch.tensor(target),
324
+ total_len=self._get_total_seq_length(input_ids, num_tiles),
325
+ )
326
+
327
+ def encode_sample_list(self, samples: SampleListSample):
328
+ """We encode the list of samples using encode_llava_sft on each sample."""
329
+ error_msg = ("You probably don't want to use online packing since SampleListSample is "
330
+ "usually used along offline packing.")
331
+ assert not self.is_packing_enabled, error_msg
332
+ encoded_samples = []
333
+ current_length = 0
334
+ for idx, sample in enumerate(samples.samples):
335
+ try:
336
+ encoded_sample = self.encode_llava_sft(sample, truncate_for_sample_list_packing=True)
337
+ if current_length + encoded_sample.total_len > self.packing_seq_length:
338
+ print(f"Encoding list of samples: stopped at {idx} samples to stick to {self.packing_seq_length}. Last sample key: {sample.__key__}")
339
+ break
340
+ else:
341
+ encoded_samples.append(encoded_sample)
342
+ current_length += encoded_sample.total_len
343
+ except Exception as e:
344
+ print(e)
345
+ return self.pack_selected_samples(encoded_samples)
346
+
347
+ def encode_llava_sft(self, sample: Union[SimilarityInterleavedSample, OfflineTargetAspectRatioSample], truncate_for_sample_list_packing=False):
348
+ """Encode SFT sample."""
349
+ augment = sample.__subflavors__['augmentation'] if 'augmentation' in sample.__subflavors__ else False
350
+ has_video = sample.__subflavors__['has_video'] if 'has_video' in sample.__subflavors__ else False
351
+
352
+ # If the target aspect ratio are provided by the dataset, we use them instead of computing
353
+ # them with the self.find_closest_aspect_ratio_fn function.
354
+ local_find_closest_aspect_ratio_fn = self.find_closest_aspect_ratio_fn
355
+ if type(sample).__name__ == "OfflineTargetAspectRatioSample" and len(sample.target_aspect_ratio) > 0:
356
+ target_aspect_ratio = tuple(sample.target_aspect_ratio[0])
357
+ assert target_aspect_ratio is not None, "Sample of type OfflineTargetAspectRatioSample needs to define the target aspect ratio."
358
+ local_find_closest_aspect_ratio_fn = lambda *args, **kwargs: target_aspect_ratio
359
+
360
+ has_image = False
361
+ # We infer whether the sample has image or not.
362
+ if hasattr(sample, "images") and not has_video:
363
+ # If this is a text-only sample and we are freezing the LM,
364
+ # then use a dummy input image.
365
+ if len(sample.images) == 0 and self.args.freeze_LM:
366
+ empty_img = Image.new('RGB', (self.args.img_w, self.args.img_h), (255, 255, 255))
367
+ sample.images.append(empty_img)
368
+ if len(sample.images) > 0:
369
+ has_image = True
370
+
371
+ # Note: Some tokenizers may ignore the system prompt.
372
+ conversation = [{"role": "system", "content": "Answer the questions."}]
373
+ # Format the conversation as a list of "user" / "assistant" turns.
374
+ for text in sample.texts:
375
+ error_msg = f"unexpected role {text['from']} in {sample.texts}"
376
+ assert text["from"] in ["human", "gpt"], error_msg
377
+ conversation.append({
378
+ "role": "user" if text["from"] == "human" else "assistant",
379
+ "content": text["value"]})
380
+
381
+ # Replace the image tags <image-idx> with IMAGE_TOKEN and count the number of image tags
382
+ number_image_tags = 0
383
+ image_tag_ids_list = []
384
+ for turn in conversation:
385
+ if turn["role"] == "user":
386
+ image_tag_ids = [int(x) - 1 for x in re.findall(r"<image-(\d+)>", turn["content"])]
387
+ image_tag_ids_list.extend(image_tag_ids)
388
+ turn["content"] = re.sub(r"<image-\d+>", IMAGE_TOKEN, turn["content"])
389
+ # For videos, we use the image token to locate where to put the frames.
390
+ if has_video:
391
+ turn["content"] = turn["content"].replace(VIDEO_TOKEN, IMAGE_TOKEN)
392
+ number_image_tags += turn["content"].count(IMAGE_TOKEN)
393
+
394
+ # We re-order the images in sample.images according to how they appear in the conversation.
395
+ if len(image_tag_ids_list) > 0:
396
+ sample.images = [sample.images[idx] for idx in image_tag_ids_list]
397
+
398
+ # If there is only one image, but several image tags, we assume all the tags refer to the
399
+ # same image and duplicate the image:
400
+ if not has_video and len(sample.images) == 1 and number_image_tags > 1:
401
+ sample.images = sample.images * number_image_tags
402
+
403
+ # If there are no images in the sample, remove the image tags in the conversation.
404
+ if len(sample.images) == 0:
405
+ for turn in conversation:
406
+ if turn["role"] == "user":
407
+ turn["content"] = turn["content"].replace(IMAGE_TOKEN, "")
408
+ number_image_tags = 0
409
+
410
+ # We currently only support one video per sample.
411
+ number_of_images = 1 if has_video else len(sample.images)
412
+ # Fail if there are more image or video tags than image or videos:
413
+ error_msg = (
414
+ f"Found {number_image_tags} image tags for {number_of_images} images. {sample.texts}")
415
+ assert number_image_tags <= number_of_images, error_msg
416
+
417
+ # If there are less image of video tags than image or videos, prepend the tags to the first
418
+ # user message:
419
+ if number_image_tags < number_of_images:
420
+ for turn in conversation:
421
+ if turn["role"] == "user":
422
+ turn["content"] = IMAGE_TOKEN*(number_of_images-number_image_tags) + "\n" + turn["content"]
423
+ break
424
+
425
+ input_ids, target = self.tokenizer.tokenize_conversation(conversation, True, False)
426
+
427
+ if has_image:
428
+ imgs = []
429
+ num_tiles = []
430
+ max_num_tiles = self.args.max_num_tiles
431
+ # We keep a buffer of 4 tokens for the question,
432
+ # the rest can be used for image tokens.
433
+ max_image_token_allowed = self.args.decoder_seq_length - len(input_ids) - 4
434
+ # We start by extracting as many tiles per image as possible, and decrease the max
435
+ # number of tiles if there are too many image tokens.
436
+ while True:
437
+ imgs = []
438
+ num_tiles = []
439
+ for img in sample.images:
440
+ # This if block is a temporary fix to handle video frames. We hard code
441
+ # `use_tiling = False` because we don't use tiling for videos frames to keep
442
+ # the number of tokens to a reasonable value.
443
+ if isinstance(img, torch.Tensor) or isinstance(img, np.ndarray):
444
+ if len(img.shape) == 4:
445
+ assert img.shape[0] == 1, f"When len(img.shape) == 4, we expect the first dimension to be 1, but got img.shape: {img.shape} instead."
446
+ img = img[0]
447
+ use_tiling = False
448
+ to_pil = ToPILImage()
449
+ img = to_pil(img)
450
+ img_tiles = self.transform_img(
451
+ img, self.img_h, self.img_w, self.args.use_tiling, max_num_tiles,
452
+ self.args.use_thumbnail, augment, find_closest_aspect_ratio_fn=local_find_closest_aspect_ratio_fn)
453
+ imgs += img_tiles
454
+ num_tiles += [len(img_tiles)]
455
+ if max_num_tiles == 1:
456
+ break
457
+ if sum(num_tiles) * self.num_image_embeddings_per_tile > max_image_token_allowed:
458
+ if max_num_tiles in self.num_tiles_degradation_map:
459
+ max_num_tiles = self.num_tiles_degradation_map[max_num_tiles]
460
+ else:
461
+ raise RuntimeError((
462
+ f"Tried to decrease the number of tiles {max_num_tiles} but it's not ",
463
+ f"defined in the degradation map {self.num_tiles_degradation_map}"))
464
+ else:
465
+ break
466
+ elif has_video:
467
+ # We don't use tiling for videos to limit the number of tokens.
468
+ use_tiling=False
469
+ # Grab the selected frames of the video as a tensor with shape
470
+ # fhwc: (num_frames, num_channels, height, width).
471
+ video_fchw = sample.images.frames
472
+ if video_fchw.shape[0] == 0:
473
+ raise ValueError(f"Video {sample.__key__} {sample.__restore_key__} {sample.texts} has no frames.")
474
+ selected_frames = torch.linspace(
475
+ 0, video_fchw.shape[0] - 1,
476
+ min(self.args.num_frames, video_fchw.shape[0])).long()
477
+ video_fchw = video_fchw[selected_frames]
478
+ imgs = []
479
+ for video_chw in video_fchw:
480
+ to_pil = ToPILImage()
481
+ video_chw = to_pil(video_chw)
482
+ imgs += self.transform_img(
483
+ video_chw, self.img_h, self.img_w, use_tiling, self.args.max_num_tiles,
484
+ self.args.use_thumbnail, augment, find_closest_aspect_ratio_fn=local_find_closest_aspect_ratio_fn)
485
+ num_tiles = [len(imgs)]
486
+ else:
487
+ imgs = num_tiles = []
488
+
489
+ if self.is_packing_enabled or truncate_for_sample_list_packing:
490
+ input_ids, target = self._truncate_for_packing(input_ids, target, num_tiles)
491
+
492
+ # Some final checks with respect to the number of image tokens and images on the tokenized
493
+ # conversation. There can still be errors, for instance if a non-video sample happens to
494
+ # have our pre-defined video token, or if the packing truncation removed a necessary image
495
+ # tag.
496
+ number_image_token = np.sum(input_ids == self.img_token_id)
497
+ error_msg = (
498
+ f"Found {number_image_token} image tokens for len({num_tiles}) = {len(num_tiles)} image tiles in {conversation}.")
499
+ assert number_image_token == len(num_tiles), error_msg
500
+ error_msg = (
501
+ f"Found sum({num_tiles}) = {np.sum(num_tiles)} tiles for {len(imgs)} images in {conversation}.")
502
+ assert np.sum(num_tiles) == len(imgs), error_msg
503
+
504
+ # We need to ensure that there are at least some trainable tokens in the sample.
505
+ assert self.target_has_trainable_tokens(input_ids, num_tiles, target), "Sample has no trainable tokens."
506
+
507
+ # Context parallel requires padding.
508
+ total_len = self._get_total_seq_length(input_ids, num_tiles)
509
+ has_cp = self.args.context_parallel_size > 1
510
+
511
+ if has_cp:
512
+ # Note: FP8 requires padding only the total sequence length.
513
+ # We pad for FP8 when we have the final, possibly packed sample.
514
+ padding_needed = get_padding(total_len, self.args.context_parallel_size, self.args.tensor_model_parallel_size, self.args.sequence_parallel, fp8_enabled=False)
515
+ padding_input = np.ones(padding_needed) * self.tokenizer.pad
516
+ padding_labels = np.ones(padding_needed) * IGNORE_INDEX
517
+ input_ids = np.concatenate([input_ids, padding_input])
518
+ target = np.concatenate([target, padding_labels])
519
+ total_len = total_len + padding_needed
520
+
521
+ return ImageTaskSample(
522
+ __key__=sample.__key__,
523
+ __restore_key__=sample.__restore_key__,
524
+ __subflavor__=None,
525
+ __subflavors__=sample.__subflavors__,
526
+ imgs=imgs,
527
+ num_tiles=num_tiles,
528
+ tokens=torch.tensor(input_ids),
529
+ labels=torch.tensor(target),
530
+ total_len=self._get_total_seq_length(input_ids, num_tiles),
531
+ )
532
+
533
+ def target_has_trainable_tokens(self, input_ids, num_tiles, target):
534
+ # Compute the loss mask based on extending the image tags with the proper
535
+ # number of image tokens, extracting the first self.args.decoder_seq_length tokens, and
536
+ # ensuring that some of these tokens have a loss mask > 0.
537
+ # Note that this is a bit hacky because we reproduce here parts of the logics which are in
538
+ # the model itself. Ideally, the data sampler would return the already processed inputs
539
+ # and targets to avoid this duplication.
540
+ expanded_target = target.copy()
541
+ expanded_target[input_ids==self.img_token_id] = self.img_token_id
542
+ expanded_target = self.replace_value_with_repetition(
543
+ expanded_target, self.img_token_id,
544
+ self.num_image_embeddings_per_tile * np.array(num_tiles), IGNORE_INDEX)
545
+ loss_mask = torch.ones(torch.tensor(expanded_target).size(), dtype=torch.float)
546
+ loss_mask[expanded_target == self.tokenizer.pad] = 0.0 # mask paddings
547
+ loss_mask[expanded_target == IGNORE_INDEX] = 0.0 # mask prompts
548
+ loss_mask = torch.cat((loss_mask[1:], torch.zeros((1,))))
549
+ loss_mask = loss_mask[:self.args.decoder_seq_length]
550
+ return torch.sum(loss_mask) > 0
551
+
552
+ def replace_value_with_repetition(self, arr, token_to_replace, num_repetition, new_token):
553
+ """
554
+ Replace every occurrence of value V in the input array with R repetitions of W.
555
+
556
+ Args:
557
+ arr (Array): Input array to be modified
558
+ token_to_replace: token to be replaced
559
+ new_token: new token
560
+ num_repetition (Array): number of repetition of new token.
561
+
562
+ Returns:
563
+ Array: New array with token_to_replace replaced by num_repetition repetitions of
564
+ new_token
565
+ """
566
+ error_msg = "The number of image tokens must match the length of the tile tensor."
567
+ assert np.sum(arr==token_to_replace) == len(num_repetition), error_msg
568
+ result = []
569
+ idx = 0
570
+ for item in arr:
571
+ if item == token_to_replace:
572
+ # If the current item matches token_to_replace, add R copies of W
573
+ result.extend([new_token] * num_repetition[idx])
574
+ idx += 1
575
+ else:
576
+ # Otherwise, keep the original item
577
+ result.append(item)
578
+
579
+ return np.array(result)
580
+
581
+ def encode_any_single_turn_vqa(self, sample):
582
+ """Encode MultiChoiceVQA or VQA sample."""
583
+ augment = sample.__subflavors__['augmentation'] if 'augmentation' in sample.__subflavors__ else False
584
+ has_video = sample.__subflavors__['has_video'] if 'has_video' in sample.__subflavors__ else False
585
+
586
+ if has_video:
587
+ # Grab the selected frames of the video as a tensor with shape
588
+ # fhwc: (num_frames, height, width, num_channels).
589
+ video_fhwc = sample.image.permute(0, 2, 3, 1)
590
+ selected_frames = torch.linspace(
591
+ 0, video_fhwc.shape[0] - 1, self.args.num_frames).long()
592
+ video_frame_fhwc = video_fhwc[selected_frames]
593
+ imgs = []
594
+ for video_frame_hwc in video_frame_fhwc:
595
+ imgs += self.transform_img(
596
+ video_frame_hwc, self.img_h, self.img_w,
597
+ self.args.use_tiling, self.args.max_num_tiles,
598
+ self.args.use_thumbnail, augment, find_closest_aspect_ratio_fn=self.find_closest_aspect_ratio_fn
599
+ )
600
+ else:
601
+ imgs = self.transform_img(
602
+ sample.image, self.img_h, self.img_w, self.args.use_tiling, self.args.max_num_tiles,
603
+ self.args.use_thumbnail, augment, find_closest_aspect_ratio_fn=self.find_closest_aspect_ratio_fn
604
+ )
605
+
606
+ num_tiles = [len(imgs)]
607
+
608
+ if isinstance(sample, MultiChoiceVQASample):
609
+ cur_prompt = format_multichoice_question(sample.context, sample.choices)
610
+ if IMAGE_TOKEN not in cur_prompt:
611
+ cur_prompt = IMAGE_TOKEN + "\n" + cur_prompt
612
+ cur_answer = format_multichoice_answer(sample.correct_choice_idx)
613
+ elif isinstance(sample, VQASample):
614
+ if 'docvqa' in sample.__key__:
615
+ prompt_list = self.manual_prompts["VQASFT"]["docvqa"]
616
+ elif sample.__subflavors__.get("VQASFT"):
617
+ prompt_list = self.manual_prompts["VQASFT"]["raw"]
618
+ else:
619
+ prompt_list = ["{}"]
620
+
621
+ prompt_idx = np.random.randint(len(prompt_list))
622
+ cur_prompt = prompt_list[prompt_idx]
623
+
624
+ cur_prompt = cur_prompt.format(sample.context)
625
+
626
+ if IMAGE_TOKEN not in cur_prompt:
627
+ cur_prompt = IMAGE_TOKEN + "\n" + cur_prompt
628
+
629
+ if isinstance(sample.answers, list):
630
+ answer_list = sample.answers
631
+ weight_list = np.array(sample.answer_weights).astype(np.float32)
632
+ weight_list = weight_list / np.sum(weight_list)
633
+ answer_idx = np.random.choice(weight_list.shape[0], 1, p=weight_list)[0]
634
+ cur_answer = answer_list[answer_idx]
635
+ else:
636
+ cur_answer = sample.answers
637
+ else:
638
+ raise NotImplementedError("Unsupported data type provided", sample)
639
+
640
+ conversation = [
641
+ {"role": "system", "content": "Answer the questions."},
642
+ {"role": "user", "content": cur_prompt},
643
+ {"role": "assistant", "content": str(cur_answer)},
644
+ ]
645
+
646
+ input_ids, target = self.tokenizer.tokenize_conversation(conversation, True, False)
647
+
648
+ if self.is_packing_enabled:
649
+ input_ids, target = self._truncate_for_packing(input_ids, target, num_tiles)
650
+
651
+ return ImageTaskSample(
652
+ __key__=sample.__key__,
653
+ __restore_key__=sample.__restore_key__,
654
+ __subflavor__=None,
655
+ __subflavors__=sample.__subflavors__,
656
+ imgs=imgs,
657
+ num_tiles=num_tiles,
658
+ tokens=torch.tensor(input_ids),
659
+ labels=torch.tensor(target),
660
+ total_len=self._get_total_seq_length(input_ids, num_tiles),
661
+ )
662
+
663
+ def combined_ocr_encoder(self, sample, task_type):
664
+ """Encode OCR samples."""
665
+ augment = sample.__subflavors__['augmentation'] if 'augmentation' in sample.__subflavors__ else False
666
+
667
+ if task_type == "encode_pdf":
668
+ sample, cur_prompt, cur_answer = self.encode_pdf_prompt(sample)
669
+ elif task_type == "encode_ocr_ref":
670
+ sample, cur_prompt, cur_answer = self.encode_ocr_ref_prompt(sample)
671
+ elif task_type == "_encode_ocr":
672
+ sample, cur_prompt, cur_answer = self.encode_ocr_prompt(sample)
673
+
674
+ imgs = self.transform_img(
675
+ sample.image, self.img_h, self.img_w, self.args.use_tiling, self.args.max_num_tiles,
676
+ self.args.use_thumbnail, augment, find_closest_aspect_ratio_fn=self.find_closest_aspect_ratio_fn
677
+ )
678
+ num_tiles = [len(imgs)]
679
+
680
+ conversation = [
681
+ {"role": "system", "content": "Answer the questions."},
682
+ {"role": "user", "content": cur_prompt},
683
+ {"role": "assistant", "content": str(cur_answer)},
684
+ ]
685
+
686
+ input_ids, target = self.tokenizer.tokenize_conversation(conversation, True, False)
687
+
688
+ if self.is_packing_enabled:
689
+ input_ids, target = self._truncate_for_packing(input_ids, target, num_tiles)
690
+
691
+ return ImageTaskSample(
692
+ __key__=sample.__key__,
693
+ __restore_key__=sample.__restore_key__,
694
+ __subflavor__=None,
695
+ __subflavors__=sample.__subflavors__,
696
+ imgs=imgs,
697
+ num_tiles=num_tiles,
698
+ tokens=torch.tensor(input_ids),
699
+ labels=torch.tensor(target),
700
+ total_len=self._get_total_seq_length(input_ids, num_tiles),
701
+ )
702
+
703
+ def encode_pdf_prompt(self, sample: OCRSample) -> ImageTaskSample:
704
+ """Encode OCR sample."""
705
+ prompt_list = self.manual_prompts["DocPretraining"]["raw"]
706
+ prompt_idx = np.random.randint(len(prompt_list))
707
+ cur_prompt = prompt_list[prompt_idx]
708
+ if IMAGE_TOKEN not in cur_prompt:
709
+ cur_prompt = IMAGE_TOKEN + "\n" + cur_prompt
710
+
711
+ # Make sure there is no extra IMAGE_TOKEN tag.
712
+ sample.text = sample.text.replace(IMAGE_TOKEN, "")
713
+
714
+ caption = sample.text.strip()
715
+
716
+ split_by_line_flag = sample.__subflavors__.get("SplitByLine")
717
+ if split_by_line_flag:
718
+ caption_list = caption.split('\n')
719
+ caption = np.random.choice(caption_list)
720
+ cur_answer = caption
721
+
722
+ return sample, cur_prompt, cur_answer
723
+
724
+ def encode_ocr_ref_prompt(self, sample: OCRSample) -> ImageTaskSample:
725
+ """Encode OCR sample."""
726
+ ref = sample.text
727
+ region = sample.words_boxes
728
+
729
+ # Make sure there is no extra IMAGE_TOKEN tag
730
+ ref = ref.replace(IMAGE_TOKEN, "")
731
+
732
+ if len(region) == 4:
733
+ region = f"<box>({region[0]},{region[1]}),({region[2]},{region[3]})</box>"
734
+ else:
735
+ region = f"<quad>({region[0]},{region[1]}),({region[2]},{region[3]}),({region[4]},{region[5]}),({region[6]},{region[7]})</quad>"
736
+
737
+ # Randomly choose between two tasks
738
+ task_idx = np.random.randint(2)
739
+ if task_idx == 0:
740
+ # Referring Grounding
741
+ prompt_list = self.manual_prompts["DocPretraining"]["referring_grounding"]
742
+ prompt_content = ref
743
+ answer = region
744
+ else:
745
+ # Grounded OCR
746
+ prompt_list = self.manual_prompts["DocPretraining"]["grounded_ocr"]
747
+ prompt_content = region
748
+ answer = ref
749
+
750
+ prompt_idx = np.random.randint(len(prompt_list))
751
+ cur_prompt = prompt_list[prompt_idx]
752
+ cur_prompt = cur_prompt.format(prompt_content)
753
+ if IMAGE_TOKEN not in cur_prompt:
754
+ cur_prompt = IMAGE_TOKEN + "\n" + cur_prompt
755
+
756
+ return sample, cur_prompt, answer
757
+
758
+ def bbox_coord_to_label(self, text, bbox):
759
+ """Format bbox coordinates as text."""
760
+ assert len(bbox) == 4 or len(bbox) == 8
761
+
762
+ # Make sure there is no extra IMAGE_TOKEN tag
763
+ text = text.replace(IMAGE_TOKEN, "")
764
+
765
+ if len(bbox) == 4:
766
+ label_str = f"<ref>{text}</ref><box>({bbox[0]},{bbox[1]}),({bbox[2]},{bbox[3]})</box>"
767
+ else:
768
+ label_str = f"<ref>{text}</ref><quad>({bbox[0]},{bbox[1]}),({bbox[2]},{bbox[3]}),({bbox[4]},{bbox[5]}),({bbox[6]},{bbox[7]})</quad>"
769
+
770
+ return label_str
771
+
772
+ def encode_ocr_prompt(self, sample: OCRSample) -> ImageTaskSample:
773
+ """Encode OCR sample."""
774
+ if isinstance(sample.words_boxes[0], int):
775
+ answer = self.bbox_coord_to_label(sample.text, sample.words_boxes)
776
+ elif isinstance(sample.words_boxes[0], list):
777
+ answer = ""
778
+ for i, bbox in enumerate(sample.words_boxes):
779
+ answer += self.bbox_coord_to_label(sample.words_text[i], bbox)
780
+
781
+ prompt_list = self.manual_prompts["DocPretraining"]["ocr_multi"]
782
+ prompt_idx = np.random.randint(len(prompt_list))
783
+ cur_prompt = prompt_list[prompt_idx]
784
+
785
+ if IMAGE_TOKEN not in cur_prompt:
786
+ cur_prompt = IMAGE_TOKEN + "\n" + cur_prompt
787
+ cur_answer = answer
788
+
789
+ return sample, cur_prompt, cur_answer
790
+
791
+ def batch(self, samples: List[Union[ImageTaskSample, ImageTaskSamplePacked]]) -> ImageTaskBatchPacked:
792
+ # Stack images to [num_tiles, c, h, w]. If there are no images (text-only), then use a dummy image.
793
+ imgs = [img for s in samples for img in s.imgs]
794
+ if len(imgs) > 0:
795
+ imgs = torch.stack(imgs)
796
+ else:
797
+ imgs = torch.tensor([[0]], dtype=torch.float32)
798
+
799
+ # If the user hasn't defined a target dataloader sequence length, then use the max along the sample lengths.
800
+ max_seq_len = self.dataloader_seq_length
801
+ if not max_seq_len:
802
+ max_seq_len = max(len(s.tokens) for s in samples)
803
+
804
+ tokens = torch.full((len(samples), max_seq_len), self.tokenizer.pad, dtype=torch.int64)
805
+ # +1 to accommodate shift to left by one later.
806
+ labels = torch.full((len(samples), max_seq_len + 1), self.tokenizer.pad, dtype=torch.int64)
807
+
808
+ for i, s in enumerate(samples):
809
+ # If the sample/target length exceeds the target sequence length, then truncate.
810
+ text_len = min(max_seq_len, len(s.tokens))
811
+ target_len = min(max_seq_len+1, len(s.labels))
812
+
813
+ tokens[i, :text_len] = s.tokens[:text_len]
814
+ labels[i, :target_len] = s.labels[:target_len]
815
+
816
+ num_tiles = torch.tensor([n for s in samples for n in s.num_tiles], dtype=torch.int32)
817
+ if len(num_tiles) == 0:
818
+ num_tiles = torch.tensor([[0]], dtype=torch.int32)
819
+
820
+ # Cumulative sample lengths are needed for packing, otherwise use dummy values.
821
+ cu_lengths = torch.tensor([[0]], dtype=torch.int32)
822
+ max_lengths = torch.tensor([[0]], dtype=torch.int32)
823
+
824
+ is_packed = isinstance(samples[0], ImageTaskSamplePacked)
825
+
826
+ if is_packed:
827
+ cu_lengths = torch.stack([s.cu_lengths for s in samples])
828
+ max_lengths = torch.tensor([s.max_length for s in samples], dtype=torch.int32)
829
+
830
+ # Pad entire sequence to be a multiple of 32 or 16 if using fp8.
831
+ has_fp8 = self.args.fp8
832
+ if has_fp8:
833
+ total_seq_len = self._get_total_seq_length(tokens[0], num_tiles)
834
+ padding_needed = get_padding(
835
+ total_seq_len,
836
+ self.args.context_parallel_size,
837
+ self.args.tensor_model_parallel_size,
838
+ self.args.sequence_parallel,
839
+ fp8_enabled=has_fp8,
840
+ fp8_recipe=self.args.fp8_recipe,
841
+ )
842
+ if padding_needed > 0:
843
+ tokens = torch.cat([tokens, torch.full((tokens.shape[0], padding_needed), self.tokenizer.pad, dtype=torch.int64)], dim=1)
844
+ labels = torch.cat([labels, torch.full((labels.shape[0], padding_needed), IGNORE_INDEX, dtype=torch.int64)], dim=1)
845
+ if is_packed:
846
+ cu_lengths[0][-1] += padding_needed
847
+ new_max_length = cu_lengths[0][-1] - cu_lengths[0][-2]
848
+ max_lengths = torch.max(max_lengths, new_max_length)
849
+
850
+
851
+ return ImageTaskBatchPacked(
852
+ __key__=[s.__key__ for s in samples],
853
+ __restore_key__=[s.__restore_key__ for s in samples],
854
+ __subflavor__=None,
855
+ __subflavors__=samples[0].__subflavors__,
856
+ tokens=tokens,
857
+ labels=labels,
858
+ imgs=imgs,
859
+ num_tiles=num_tiles,
860
+ cu_lengths=cu_lengths,
861
+ max_lengths=max_lengths,
862
+ )
863
+
864
+ def encode_batch(self, batch: ImageTaskBatchPacked) -> dict:
865
+ raw = dataclasses.asdict(batch)
866
+ del raw["__subflavors__"]
867
+ return raw
868
+
869
+ def select_samples_to_pack(self, samples: List[ImageTaskSample]) -> List[List[ImageTaskSample]]:
870
+ """Selects which samples will be packed together.
871
+
872
+ NOTE: Energon dataloader calls this method internally if packing is used.
873
+ Please see https://nvidia.github.io/Megatron-Energon/advanced/packing.html
874
+ """
875
+ lengths = [sample.total_len for sample in samples]
876
+
877
+ packed_samples = greedy_knapsack(lengths, samples, self.packing_seq_length)
878
+
879
+ return packed_samples
880
+
881
+ @stateless
882
+ def pack_selected_samples(self, samples: List[ImageTaskSample]) -> List[ImageTaskSamplePacked]:
883
+ """
884
+ Function to pack a list of ImageTaskSample into a single ImageTaskSamplePacked.
885
+
886
+ NOTE: Energon dataloader calls this method internally if packing is used.
887
+ Please see https://nvidia.github.io/Megatron-Energon/advanced/packing.html
888
+
889
+ Args:
890
+ samples: List of ImageTaskSample instances to pack into one sample.
891
+
892
+ Returns:
893
+ ImageTaskSamplePacked instance.
894
+ """
895
+ packing_seq_len = self.packing_seq_length
896
+
897
+ packed_tokens = []
898
+ packed_labels = []
899
+ packed_imgs = []
900
+
901
+ current_length = 0
902
+ max_length = 0
903
+ cu_lengths = [0]
904
+
905
+ # Process each sample and build lists that we will concatenate to create the packed sample.
906
+ for _, sample in enumerate(samples):
907
+ sample_len = sample.total_len
908
+
909
+ if sample_len > max_length:
910
+ max_length = sample_len
911
+
912
+ # If adding this sample exceeds the max length, stop.
913
+ # This should not happen. The select_samples_to_pack method should have already ensured that the samples fit.
914
+ if current_length + sample_len > packing_seq_len:
915
+ raise ValueError(f"Packed sample exceeds the maximum sequence length of {packing_seq_len}: {samples}")
916
+
917
+ # Add the sample's tokens and labels
918
+ packed_tokens.append(sample.tokens)
919
+ packed_labels.append(sample.labels)
920
+
921
+ # Add the images
922
+ packed_imgs += sample.imgs
923
+
924
+ current_length += sample_len
925
+ cu_lengths.append(current_length)
926
+
927
+ # Concatenate packed tokens and labels.
928
+ packed_tokens = torch.cat(packed_tokens, dim=0)
929
+ packed_labels = torch.cat(packed_labels, dim=0)
930
+
931
+ return ImageTaskSamplePacked(
932
+ __key__=",".join([s.__key__ for s in samples]),
933
+ __restore_key__=(), # Will be set by energon based on `samples`
934
+ __subflavor__=None,
935
+ __subflavors__=samples[0].__subflavors__,
936
+ tokens=packed_tokens,
937
+ labels=packed_labels,
938
+ imgs=packed_imgs,
939
+ cu_lengths=torch.tensor(cu_lengths, dtype=torch.int32),
940
+ max_length=max_length,
941
+ num_tiles=[n for s in samples for n in s.num_tiles],
942
+ )
943
+
944
+
945
+ def print_error_handler(exc: Exception, key: Optional[str]):
946
+ print(
947
+ f"The following exception occurred in the dataloader for sample {key} and is skipped",
948
+ file=sys.stderr,
949
+ )
950
+ traceback.print_exc()
951
+
952
+
953
+ def format_multichoice_question(question, multichoice_options):
954
+ """Format multi-choice question."""
955
+ options_text = ["{}. {}\n".format(chr(ord('A') + i), option) for i, option in
956
+ zip(range(len(multichoice_options)), multichoice_options)]
957
+ options_text = "".join(options_text)
958
+
959
+ options_text = f"{options_text}Answer with the option's letter from the given choices directly."
960
+
961
+ return "{}\n{}".format(question, options_text)
962
+
963
+
964
+ def format_multichoice_answer(idx):
965
+ """Format multi-choice answer."""
966
+ return chr(ord('A') + idx)
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/energon_util.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
2
+ import torch
3
+ from dataclasses import dataclass
4
+ from typing import Any, List
5
+
6
+ from megatron.energon import Sample
7
+
8
+
9
+ @dataclass
10
+ class SampleListSample(Sample):
11
+ """Sample type for a list of samples of any type which needs to be packed together.
12
+
13
+ This is useful for datasets which are packed offline.
14
+ """
15
+
16
+ #: The images of the sequence
17
+ samples: List[Any]
18
+
19
+
20
+ @dataclass
21
+ class OfflineTargetAspectRatioSample(Sample):
22
+ """Sample type for image + text samples with target aspect ratio computed offline."""
23
+
24
+ #: The images of the sequence
25
+ images: List[torch.Tensor]
26
+ #: The texts of the sequence
27
+ texts: List[str]
28
+ target_aspect_ratio: List[List]
29
+
30
+ if not hasattr(Sample, "__subflavor__"):
31
+ __subflavor__: str
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/evaluation/evaluate_ai2d.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+
4
+ from .evaluate_mmmu import get_input_output_paths
5
+ from .evaluate_vqav2 import compute_vqa_accuracy
6
+
7
+
8
+ def merge_input_files(input_path):
9
+ """Merge input files to a format compatible with the evaluator."""
10
+ input_file_paths, output_file_path = get_input_output_paths(input_path, task="AI2D")
11
+
12
+ results = dict()
13
+
14
+ for input_file_path in input_file_paths:
15
+ with open(input_file_path, "r") as input_file:
16
+ for line in input_file:
17
+ res = json.loads(line)
18
+ sample_id = res["sample_id"]
19
+
20
+ # Ignore possible duplicates.
21
+ if sample_id in results:
22
+ continue
23
+
24
+ results[sample_id] = {
25
+ "question_id": sample_id,
26
+ "answer": res["answer"],
27
+ "gt_answer": res["gt_answer"],
28
+ }
29
+
30
+ results = list(results.values())
31
+
32
+ with open(output_file_path, "w") as output_file:
33
+ json.dump(results, output_file, indent=4, sort_keys=True)
34
+
35
+ return output_file_path
36
+
37
+
38
+ def ai2d_eval(input_path):
39
+ """Run AI2D evaluation."""
40
+ result_file_path = merge_input_files(input_path)
41
+ avg_acc = compute_vqa_accuracy(result_file_path, task="AI2D")
42
+ return avg_acc
43
+
44
+
45
+ if __name__ == "__main__":
46
+ parser = argparse.ArgumentParser()
47
+ parser.add_argument('--input-path', type=str, help="Path to input file(s)")
48
+ args = parser.parse_args()
49
+
50
+ avg_acc = ai2d_eval(args.input_path)
51
+
52
+ print(f"===== AI2D Accuracy {avg_acc:.2f}% =====")
tasks/kfc/wro-megatron-moe-routing-fused-triton-loop16/task/environment/repo/examples/multimodal/evaluation/evaluate_coco.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
2
+ import argparse
3
+ import json
4
+
5
+ from .evaluate_mmmu import get_input_output_paths
6
+ from pycocoevalcap.eval import COCOEvalCap
7
+ from pycocotools.coco import COCO
8
+
9
+
10
+ def convert_to_coco_format(input_path):
11
+ """Convert input files to COCO compatible format."""
12
+ input_file_paths, output_file_path = get_input_output_paths(input_path, task="captioning")
13
+
14
+ results = dict()
15
+
16
+ for input_file_path in input_file_paths:
17
+ with open(input_file_path, "r") as input_file:
18
+ for line in input_file:
19
+ res = json.loads(line)
20
+ sample_id = res["sample_id"]
21
+
22
+ # Ignore possible duplicates.
23
+ if sample_id in results:
24
+ continue
25
+
26
+ caption = res["caption"].rstrip(".").lower()
27
+ results[sample_id] = {
28
+ "image_id": sample_id,
29
+ "caption": caption,
30
+ }
31
+
32
+ results = list(results.values())
33
+
34
+ with open(output_file_path, "w") as output_file:
35
+ json.dump(results, output_file, indent=4, sort_keys=True)
36
+
37
+ return output_file_path
38
+
39
+
40
+ def coco_captioning_eval(input_path, groundtruth_file):
41
+ """Run COCO captioning evaluation."""
42
+ coco = COCO(groundtruth_file)
43
+ input_file = convert_to_coco_format(input_path)
44
+ coco_result = coco.loadRes(input_file)
45
+
46
+ coco_eval = COCOEvalCap(coco, coco_result)
47
+
48
+ # Evaluate on the input subset of images.
49
+ coco_eval.params["image_id"] = coco_result.getImgIds()
50
+
51
+ coco_eval.evaluate()
52
+
53
+ print("========== COCO captioning scores ==========")
54
+ for metric, score in coco_eval.eval.items():
55
+ print(f"{metric} {score * 100:.3f}")
56
+
57
+ return coco_eval.eval['CIDEr']
58
+
59
+ if __name__ == "__main__":
60
+ parser = argparse.ArgumentParser()
61
+ parser.add_argument("--input-path", type=str, required=True, help="Path to input file(s)")
62
+ parser.add_argument(
63
+ "--groundtruth-path", type=str, required=True, help="Path to groundtruth file"
64
+ )
65
+ args = parser.parse_args()
66
+
67
+ coco_captioning_eval(args.input_path, args.groundtruth_path)