Source code for nemo_rl.transformers_compat

# Copyright (c) 2026, NVIDIA CORPORATION.  All rights reserved.
# Copyright 2021 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Temporary compatibility patches for supported Transformers releases.

The dynamic-module hashing patch can be removed when NeMo RL requires
Transformers 5.13.0 or newer. Keep the torch-FX helper until the converted
DeepSeek-V3 checkpoint no longer imports the Transformers 4.x API.
"""

import hashlib
import importlib
import inspect
import logging
import os
from importlib.metadata import PackageNotFoundError
from importlib.metadata import version as distribution_version
from pathlib import Path
from typing import Any

logger = logging.getLogger(__name__)

_MIN_AFFECTED_TRANSFORMERS_VERSION = "5.11.0"
_FIXED_TRANSFORMERS_VERSION = "5.13.0"
_EXPECTED_HASH_FUNCTION_PARAMETERS = (
    "pretrained_model_name_or_path",
    "resolved_module_file",
)


[docs] def _is_torch_fx_available_compat() -> bool: """Compatibility replacement for the helper removed in Transformers 5.""" try: importlib.import_module("torch.fx") except ImportError: return False return True
[docs] def _patch_transformers_torch_fx_compat() -> bool: """Restore the legacy helper imported by DeepSeek-V3 remote model code. The converted DeepSeek-V3 checkpoint used by the performance suite embeds model code written for Transformers 4.33.1. That code imports ``is_torch_fx_available`` from ``transformers.utils.import_utils``, but the helper was removed in Transformers 5. Install an equivalent only when the installed Transformers does not provide it already. """ try: distribution_version("transformers") except PackageNotFoundError: return False import_utils = importlib.import_module("transformers.utils.import_utils") if hasattr(import_utils, "is_torch_fx_available"): return False setattr(import_utils, "is_torch_fx_available", _is_torch_fx_available_compat) logger.info( "Installed the Transformers compatibility helper " "is_torch_fx_available for legacy remote model code" ) return True