RL icon indicating copy to clipboard operation
RL copied to clipboard

GPT-OSS SFT OOM when setting up JIT fusion

Open dhineshkumar-r opened this issue 8 months ago • 5 comments

Describe the bug

I've been trying to perform SFT on gpt-oss-20b with Megatron backend and a custom dataset in openai format. The job fails due to OOM when setting jit fusion.

ray.exceptions.ActorDiedError: The actor died because of an error raised in its creation task, ray::lm_policy-1-3:MegatronPolicyWorker.__init__() (pid=219146, ip=100.64.240.80, actor_id=8562bae60896d129459db77a09000000, repr=MegatronPolicyWorker[rank=11])
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/nemo-rl/nemo_rl/models/policy/workers/megatron_policy_worker.py", line 864, in __init__
    ) = setup_megatron_model(
        ^^^^^^^^^^^^^^^^^^^^^
  File "/opt/nemo-rl/nemo_rl/models/policy/workers/megatron_policy_worker.py", line 244, in setup_megatron_model
    set_jit_fusion_options(cfg.model, cfg.train.micro_batch_size)
  File "/opt/nemo-rl/3rdparty/Megatron-Bridge-workspace/Megatron-Bridge/src/megatron/bridge/training/initialize.py", line 267, in set_jit_fusion_options
    _warmup_jit_function(model_config, micro_batch_size)
  File "/opt/nemo-rl/3rdparty/Megatron-Bridge-workspace/Megatron-Bridge/src/megatron/bridge/training/initialize.py", line 509, in _warmup_jit_function
    output = bias_gelu(bias, input)
             ^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/ray_venvs/nemo_rl.models.policy.workers.megatron_policy_worker.MegatronPolicyWorker/lib/python3.12/site-packages/torch/_dynamo/eval_frame.py", line 832, in compile_wrapper
    return fn(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^
  File "/opt/nemo-rl/3rdparty/Megatron-LM-workspace/Megatron-LM/megatron/core/fusions/fused_bias_gelu.py", line 16, in bias_gelu
    @jit_fuser
  File "/opt/ray_venvs/nemo_rl.models.policy.workers.megatron_policy_worker.MegatronPolicyWorker/lib/python3.12/site-packages/torch/_dynamo/eval_frame.py", line 1044, in _fn
    return fn(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^
  File "/opt/ray_venvs/nemo_rl.models.policy.workers.megatron_policy_worker.MegatronPolicyWorker/lib/python3.12/site-packages/torch/_functorch/aot_autograd.py", line 1130, in forward
    return compiled_fn(full_args)
           ^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/ray_venvs/nemo_rl.models.policy.workers.megatron_policy_worker.MegatronPolicyWorker/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py", line 339, in runtime_wrapper
    all_outs = call_func_at_runtime_with_args(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/ray_venvs/nemo_rl.models.policy.workers.megatron_policy_worker.MegatronPolicyWorker/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/utils.py", line 129, in call_func_at_runtime_with_args
    out = normalize_as_list(f(args))
                            ^^^^^^^
  File "/opt/ray_venvs/nemo_rl.models.policy.workers.megatron_policy_worker.MegatronPolicyWorker/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/utils.py", line 103, in g
    return f(*args)
           ^^^^^^^^
  File "/opt/ray_venvs/nemo_rl.models.policy.workers.megatron_policy_worker.MegatronPolicyWorker/lib/python3.12/site-packages/torch/autograd/function.py", line 581, in apply
    return super().apply(*args, **kwargs)  # type: ignore[misc]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/ray_venvs/nemo_rl.models.policy.workers.megatron_policy_worker.MegatronPolicyWorker/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py", line 2118, in forward
    fw_outs = call_func_at_runtime_with_args(
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/ray_venvs/nemo_rl.models.policy.workers.megatron_policy_worker.MegatronPolicyWorker/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/utils.py", line 129, in call_func_at_runtime_with_args
    out = normalize_as_list(f(args))
                            ^^^^^^^
  File "/opt/ray_venvs/nemo_rl.models.policy.workers.megatron_policy_worker.MegatronPolicyWorker/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py", line 526, in wrapper
    return compiled_fn(runtime_args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/ray_venvs/nemo_rl.models.policy.workers.megatron_policy_worker.MegatronPolicyWorker/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py", line 724, in inner_fn
    outs = compiled_fn(args)
           ^^^^^^^^^^^^^^^^^
  File "/opt/ray_venvs/nemo_rl.models.policy.workers.megatron_policy_worker.MegatronPolicyWorker/lib/python3.12/site-packages/torch/_inductor/output_code.py", line 613, in __call__
    return self.current_callable(inputs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/ray_venvs/nemo_rl.models.policy.workers.megatron_policy_worker.MegatronPolicyWorker/lib/python3.12/site-packages/torch/_inductor/utils.py", line 2962, in run
    out = model(new_inputs)
          ^^^^^^^^^^^^^^^^^
  File "/tmp/torchinductor_root/ww/cwwhw3r3h6ek6joapplgy2gpcwsugvthbqrlor3btwls472btxr5.py", line 128, in call
    buf0 = empty_strided_cuda((131072, 1, 2880), (2880, 2880, 1), torch.bfloat16)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 720.00 MiB. GPU 0 has a total capacity of 139.81 GiB of which 620.12 MiB is free. Including non-PyTorch memory, this process has 2.00 GiB memory in use. Of the allocated memory 1.41 GiB is allocated by PyTorch, and 1.99 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation.  See documentation for Memory Management  (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)

Steps/Code to reproduce bug

  1. NemoRL image created at https://github.com/NVIDIA-NeMo/RL/commit/e480f8f01973d9adca40d16d3e2599880301d5d3
  2. Kick off SFT job with following overrides
    uv run examples/run_sft.py \
      --config examples/configs/sft.yaml \
      sft.max_num_epochs=1 \
      policy.model_name=openai/gpt-oss-20b \
      policy.tokenizer.name=openai/gpt-oss-20b \
      ~policy.tokenizer.chat_template \
      policy.train_global_batch_size=32 \
      policy.train_micro_batch_size=1 \
      policy.max_total_sequence_length=1024 \
      policy.sequence_packing.enabled=false \
      policy.dtensor_cfg.enabled=false \
      policy.megatron_cfg.enabled=true \
      policy.megatron_cfg.sequence_parallel=false \
      policy.megatron_cfg.expert_model_parallel_size=16 \
      policy.megatron_cfg.tensor_model_parallel_size=1 \
      policy.megatron_cfg.pipeline_model_parallel_size=1 \
      policy.make_sequence_length_divisible_by=1 \
      policy.megatron_cfg.freeze_moe_router=false \
      policy.megatron_cfg.moe_router_dtype=fp64 \
      policy.megatron_cfg.moe_router_load_balancing_type=aux_loss \
      policy.megatron_cfg.moe_router_bias_update_rate=1e-3 \
      +policy.megatron_cfg.env_vars.NRL_MEGATRON_CHECKPOINT_DIR=/fsx/models/megatron/gpt-oss-20b \
      policy.megatron_cfg.optimizer.use_distributed_optimizer=true \
      policy.megatron_cfg.optimizer.use_precision_aware_optimizer=true \
      policy.megatron_cfg.optimizer.params_dtype=float32 \
      logger.wandb_enabled=false \
      logger.tensorboard_enabled=false \
      logger.mlflow_enabled=true \
      logger.mlflow.experiment_name=nemo-rl-experiments \
      logger.mlflow.run_name=gpt-oss-20b-tool-call-sft-run \
      +logger.mlflow.tracking_uri=<tracking_uri> \
      cluster.gpus_per_node=8 \
      cluster.num_nodes=4 \
      checkpointing.checkpoint_dir=/fsx/ramasud/ws/dpo-k8s/checkpoints-megatron/gpt-oss-sft-20b/ramasud-nemo-tool-call-sft-ray \
      checkpointing.keep_top_k=5 \
      data.train.dataset_name=openai_format \
      ++data.train.data_path=/fsx/ramasud/ws/dpo-k8s/custom_datasets/xlam_toolcalls/train_data.jsonl \
      ~data.train.split \
      ~data.validation \
      ++data.default.chat_key=messages \
      ++data.default.tool_key=tools \
      ~data.default.processor \
      ++data.default.use_preserving_dataset=true

Expected behavior SFT job to finish running successfully.

Additional context Instance type: p5en.48xlarge (H200 GPUs)

dhineshkumar-r avatar Mar 16 '26 06:03 dhineshkumar-r

I'm not facing this issue when I run the same job with OpenMathInstruct dataset, could this be due to usage of preserving dataset?

@terrykong / @HeyyyyyyG to provide suggestions or workarounds. Thanks in advance.

dhineshkumar-r avatar Mar 16 '26 18:03 dhineshkumar-r

@terrykong

I see that there is no processor for openai format dataset here, is that expected? I tried using sft_processor and I see the following error.

🔍 Running initial validation...
▶ Starting validation at step 0...
Traceback (most recent call last):
  File "/opt/nemo-rl/examples/run_sft.py", line 192, in <module>
    main()
  File "/opt/nemo-rl/examples/run_sft.py", line 178, in main
    sft_train(
  File "/opt/nemo-rl/nemo_rl/algorithms/sft.py", line 393, in sft_train
    val_metrics, validation_timings = validate(
                                      ^^^^^^^^^
  File "/opt/nemo-rl/nemo_rl/algorithms/sft.py", line 264, in validate
    for batch_idx, val_batch in enumerate(val_dataloader):
                                ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/nemo_rl_venv/lib/python3.12/site-packages/torchdata/stateful_dataloader/stateful_dataloader.py", line 450, in __next__
    return super().__next__()
           ^^^^^^^^^^^^^^^^^^
  File "/opt/nemo_rl_venv/lib/python3.12/site-packages/torch/utils/data/dataloader.py", line 732, in __next__
    data = self._next_data()
           ^^^^^^^^^^^^^^^^^
  File "/opt/nemo_rl_venv/lib/python3.12/site-packages/torchdata/stateful_dataloader/stateful_dataloader.py", line 1456, in _next_data
    return self._process_data(data, worker_id, state_dict)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/nemo_rl_venv/lib/python3.12/site-packages/torchdata/stateful_dataloader/stateful_dataloader.py", line 1543, in _process_data
    data.reraise()
  File "/opt/nemo_rl_venv/lib/python3.12/site-packages/torch/_utils.py", line 762, in reraise
    raise self.exc_type(message=msg)
jinja2.exceptions.UndefinedError: Caught UndefinedError in DataLoader worker process 0.
Original Traceback (most recent call last):
  File "/opt/nemo_rl_venv/lib/python3.12/site-packages/torchdata/stateful_dataloader/worker.py", line 242, in _worker_loop
    data = fetcher.fetch(index)  # type: ignore[union-attr]
           ^^^^^^^^^^^^^^^^^^^^
  File "/opt/nemo_rl_venv/lib/python3.12/site-packages/torch/utils/data/_utils/fetch.py", line 52, in fetch
    data = [self.dataset[idx] for idx in possibly_batched_index]
            ~~~~~~~~~~~~^^^^^
  File "/opt/nemo-rl/nemo_rl/data/datasets/processed_dataset.py", line 109, in __getitem__
    datum_spec = task_data_processor(
                 ^^^^^^^^^^^^^^^^^^^^
  File "/opt/nemo-rl/nemo_rl/data/processors.py", line 156, in sft_processor
    message_log = get_formatted_message_log(
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/nemo-rl/nemo_rl/data/llm_message_utils.py", line 541, in get_formatted_message_log
    formatted_message: str = tokenizer.apply_chat_template(  # type: ignore
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/nemo_rl_venv/lib/python3.12/site-packages/transformers/tokenization_utils_base.py", line 1666, in apply_chat_template
    rendered_chat, generation_indices = render_jinja_template(
                                        ^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/nemo_rl_venv/lib/python3.12/site-packages/transformers/utils/chat_template_utils.py", line 539, in render_jinja_template
    rendered_chat = compiled_template.render(
                    ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/nemo_rl_venv/lib/python3.12/site-packages/jinja2/environment.py", line 1295, in render
    self.environment.handle_exception()
  File "/opt/nemo_rl_venv/lib/python3.12/site-packages/jinja2/environment.py", line 942, in handle_exception
    raise rewrite_traceback_stack(source=source)
  File "<template>", line 252, in top-level template code
  File "/opt/nemo_rl_venv/lib/python3.12/site-packages/jinja2/sandbox.py", line 401, in call
    return __context.call(__obj, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/nemo_rl_venv/lib/python3.12/site-packages/jinja2/runtime.py", line 784, in _invoke
    rv = self._func(*arguments)
         ^^^^^^^^^^^^^^^^^^^^^^
  File "<template>", line 113, in template
  File "/opt/nemo_rl_venv/lib/python3.12/site-packages/jinja2/sandbox.py", line 319, in getattr
    value = getattr(obj, attribute)
            ^^^^^^^^^^^^^^^^^^^^^^^
jinja2.exceptions.UndefinedError: 'dict object' has no attribute 'function'

If an openai format data processor is required, could you please share some guidance/list of steps to implement one and unblock myself?

Thanks

dhineshkumar-r avatar Mar 16 '26 21:03 dhineshkumar-r

Updating the tools section of the dataset to the following format helped overcome the above issue with sft_processor.

'tools': [
{'type': 'function',
  'function': {'name': 'greatest_common_divisor',
   'description': 'Computes the greatest common divisor (GCD) of two non-negative integers.',
   'parameters': {'a': {'description': 'The first non-negative integer.',
     'type': 'int'},
    'b': {'description': 'The second non-negative integer.', 'type': 'int'}}}},
 {'type': 'function',
  'function': {'name': 'monthly_mortgage_payment',
   'description': 'Calculates the monthly mortgage payment based on the loan amount, annual interest rate, and loan term.',
   'parameters': {'loan_amount': {'description': 'The total amount of the loan.',
     'type': 'float'},
    'annual_interest_rate': {'description': 'The annual interest rate as a decimal (e.g., 0.05 for 5%).',
     'type': 'float'},
    'loan_term_years': {'description': 'The loan term in years.',
     'type': 'int'}}}},
 {'type': 'function',
  'function': {'name': 'calculate_standard_deviation',
   'description': 'Calculates the standard deviation of a list of numbers.',
   'parameters': {'numbers': {'description': 'The list of numbers.',
     'type': 'List[Union[int, float]]'}}}},
 {'type': 'function',
  'function': {'name': 'cosine_similarity',
   'description': 'Calculates the cosine similarity between two vectors.',
   'parameters': {'vector_a': {'description': 'The first vector.',
     'type': 'List[float]'},
    'vector_b': {'description': 'The second vector.',
     'type': 'List[float]'}}}}]

Can someone please confirm whether sft_processor is the correct processor for openai format datasets?

dhineshkumar-r avatar Mar 16 '26 22:03 dhineshkumar-r

i think this is a duplicate of https://github.com/NVIDIA-NeMo/RL/issues/1685. @seonjinn can you confirm?

terrykong avatar Mar 16 '26 22:03 terrykong

Hey @terrykong, Following up on the previous question. Is sft_processor, the correct one for openai dataset?

dhineshkumar-r avatar Apr 14 '26 06:04 dhineshkumar-r