Skip to content

Fix runtime lib loading logic - #2297

Merged
ksivaman merged 2 commits into
NVIDIA:mainfrom
ksivaman:reorder_lib_loading
Dec 9, 2025
Merged

ksivaman merged 2 commits into
NVIDIA:mainfrom
ksivaman:reorder_lib_loading

Conversation

@ksivaman

@ksivaman ksivaman commented Oct 23, 2025 •

Copy link
Copy Markdown
Member

Description

This is a small refactor of library loading logic during runtime to be more consistent and avoid duplication. The main point is to check python packages as a last ditch attempt to find the library and prioritize system installations.

Fixes a bug where the incorrect shared object is loaded (with mismatching versions) due to presence of PyPI packages that are installed by pytorch/jax etc.

It also allows users to install and import TE wheels in an environment without the cuda toolkit.

Fixes #2373

Type of change

  • Documentation change (change only to the documentation, either a fix or a new content)
  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Infra/Build change
  • Code refactoring

Changes

  • Remove duplication of loading logic for various libs such as curand, cudnn etc.
  • Prioritize loading packages via system, e.g. LD_LIBRARY_PATH before checking python packages.
  • Remove search via ldconfig as redundant and brute force.

Checklist:

  • I have read and followed the contributing guidelines
  • The functionality is complete
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

@ksivaman
ksivaman requested a review from ptrendx October 23, 2025 16:14

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 file reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

Comment thread transformer_engine/common/__init__.py Resolved

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Greptile Overview

Greptile Summary

This review covers only the changes made since the last review, not the entire PR. New critical issues identified: The refactored _load_cuda_library function has a duplicate @functools.lru_cache decorator on line 320 that will cause a syntax error. Additionally, lines 334–336 now return only the first handle from multi-handle returns (previously _load_nvidia_cuda_library returned all handles), breaking libraries that may provide multiple versions. Most critically, lines356–357 directly assign the tuple (bool, list) from _load_cuda_library_from_python to _CUBLAS_LIB_CTYPES and _CUDART_LIB_CTYPES instead of unpacking the handle, which will cause runtime failures when these variables are later used as ctypes handles. The previously reported if-elif-else logic error on lines 269–274 remains unfixed.

Important Files Changed

Filename Score Overview
transformer_engine/common/init.py 1/5 Refactored library loading to prioritize system over Python packages, but introduces duplicate decorator, loses multi-handle semantics, and incorrectly assigns tuple return values to ctypes handle globals

Confidence score: 0/5

  • This PR will cause immediate failures in production due to multiple syntax and logic errors
  • Score reflects four distinct critical issues: duplicate decorator causing syntax error, incorrect return-value unpacking causing type errors, lost multi-handle semantics breaking library loading, and unfixed if-elif-else fallthrough from previous review
  • Pay close attention to lines 320(duplicate decorator), 334–336 (lost multi-handle return), 356–357 (incorrect tuple assignment), and 269–274 (unfixed if-elif-else logic)

1 file reviewed, 3 comments

Edit Code Review Agent Settings | Greptile

Comment thread transformer_engine/common/__init__.py Resolved
Comment thread transformer_engine/common/__init__.py Resolved
Comment thread transformer_engine/common/__init__.py Resolved

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Greptile Overview

Greptile Summary

This review covers only the changes made since the last review, not the entire PR. The developer has updated transformer_engine/common/__init__.py to address multiple critical bugs identified in previous reviews. Specifically, the changes fix: (1) the if-elif-else fallthrough issue by converting line 271 to elif to prevent unintended overwrites, (2) the duplicate decorator on line 360 which is removed, (3) the cublas/cudart loading logic which is now wrapped in _load_cuda_library_from_system to properly search system paths and raise errors on failure rather than silently assigning (False, []), and (4) the single-handle return in _load_cuda_library which now returns all matched handles. The glob pattern on lines 270/272/274 still uses a wildcard (lib*{ext}.*[0-9]) that matches all versioned libraries in the directory instead of filtering specifically by the requested lib_name, which could lead to incorrect library selection when multiple CUDA libraries coexist, but this is a pre-existing pattern carried over from the original code and may be intentional to capture multi-part library names (e.g., libcudart.so.12.0).

Important Files Changed

Filename Score Overview
transformer_engine/common/init.py 4/5 Fixed if-elif fallthrough, duplicate decorator, and cublas/cudart loading; all handles now returned; glob pattern still non-specific but matches prior behavior

Confidence score: 4/5

  • This PR is now safe to merge with minimal risk after addressing the previous critical issues
  • Score reflects that all previously identified logic errors (fallthrough, duplicate decorator, silent failures, single-handle return) have been corrected; remaining uncertainty is the wildcard glob pattern which may be by design and does not introduce new risk
  • No files require additional attention; all critical bugs have been resolved

1 file reviewed, 2 comments

Edit Code Review Agent Settings | Greptile

Comment thread transformer_engine/common/__init__.py Resolved
Comment on lines +306 to +309
libs = glob.glob(f"{path}/**/lib{lib_name}{_get_sys_extension()}*", recursive=True)
libs.sort(reverse=True, key=os.path.basename)
if libs:
return True, ctypes.CDLL(libs[0], mode=ctypes.RTLD_GLOBAL)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: glob uses lib{lib_name}* but does not filter out stub libraries; for nvrtc this previously filtered stubs explicitly (old code line ~336). Consider adding not ("stub" in x) filter.

@ksivaman

Copy link
Copy Markdown
Member Author

/te-ci

@ksivaman
ksivaman requested review from ptrendx and removed request for ptrendx October 28, 2025 20:18
Comment thread transformer_engine/common/__init__.py Resolved
Comment thread transformer_engine/common/__init__.py Resolved
@greptile-apps

greptile-apps Bot commented Nov 25, 2025 •

Copy link
Copy Markdown
Contributor

Greptile Overview

Greptile Summary

Refactors library loading logic to consolidate duplicate code and prioritize system installations over PyPI packages, addressing version mismatch bugs.

Key changes:

  • Consolidated library loading into _load_cuda_library(), _load_cuda_library_from_system(), and _load_cuda_library_from_python() helper functions
  • Removed redundant ldconfig search logic
  • Updated build_tools/utils.py to dynamically discover CUDA include directories
  • Added packaging and pydantic dependencies

Critical issues found:

  • Type mismatch: _load_cuda_library_from_system() returns (bool, single_handle) but _load_cuda_library_from_python() returns (bool, list_of_handles), causing inconsistent return types
  • Logic error on line 374: condition uses and instead of or, failing to handle mixed system/python scenarios correctly
  • Line 378 overwrites _CUDNN_LIB_CTYPES that was already loaded from system on line 367
  • Lines 376-378 call _load_cuda_library_from_python() but should call _load_cuda_library() to match variable type expectations
  • Glob patterns on lines 273, 281, 285 use lib* instead of lib{lib_name}*, matching all libraries instead of the requested one

Confidence Score: 1/5

  • This PR has critical bugs that will cause runtime failures
  • Score of 1 reflects multiple critical logic errors: type mismatches between loader functions will cause crashes when handles are used, incorrect boolean logic will fail in mixed system/python environments, and overly broad glob patterns will load wrong libraries. These are not edge cases - they will break core functionality.
  • Pay critical attention to transformer_engine/common/__init__.py - it contains type mismatches, logic errors, and incorrect glob patterns that will cause runtime failures

Important Files Changed

File Analysis

Filename Score Overview
build_tools/pytorch.py 5/5 Added packaging and pydantic dependencies - straightforward dependency addition
build_tools/utils.py 5/5 Replaced hardcoded include paths with dynamic discovery - cleaner and more maintainable approach
transformer_engine/common/init.py 1/5 Critical type mismatch and logic errors: return types inconsistent between system/python loaders, incorrect and condition on line 374, cudnn overwritten on line 378, glob patterns too broad on lines 273/281/285

Sequence Diagram

sequenceDiagram
    participant Main as Main Code
    participant LoadLib as _load_cuda_library()
    participant LoadSys as _load_cuda_library_from_system()
    participant LoadPy as _load_cuda_library_from_python()
    participant FS as File System

    Note over Main: Load cudnn, nvrtc, curand
    Main->>LoadLib: _load_cuda_library("cudnn")
    LoadLib->>LoadSys: Check system paths
    LoadSys->>FS: Check CUDNN_HOME/PATH
    LoadSys->>FS: Check CUDA_HOME/PATH
    LoadSys->>FS: Check LD_LIBRARY_PATH
    alt Found in system
        LoadSys-->>LoadLib: (True, handle)
        LoadLib-->>Main: (True, handle)
    else Not found in system
        LoadLib->>LoadPy: Check python packages
        LoadPy->>FS: Check nvidia/cu13/lib_name
        LoadPy->>FS: Check nvidia/cu13/lib
        LoadPy->>FS: Check nvidia/lib_name
        LoadPy->>FS: Check nvidia/cuda_lib_name
        alt Found in python
            LoadPy-->>LoadLib: (True, [handles])
            LoadLib-->>Main: (False, [handles])
        else Not found
            LoadLib-->>Main: RuntimeError
        end
    end

    Note over Main: Check if system libs loaded
    alt system_nvrtc AND system_curand
        Note over Main: All system - done
    else NOT system_nvrtc AND NOT system_curand
        Note over Main: Load cublas, cudart, cudnn from python
        Main->>LoadPy: _load_cuda_library_from_python()
        LoadPy-->>Main: (bool, [handles])
    end
Loading

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 file reviewed, 3 comments

Edit Code Review Agent Settings | Greptile

Comment thread transformer_engine/common/__init__.py Resolved
Comment thread transformer_engine/common/__init__.py Resolved
Comment thread transformer_engine/common/__init__.py Resolved

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 file reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

Comment thread transformer_engine/common/__init__.py Resolved

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 file reviewed, no comments

Edit Code Review Agent Settings | Greptile

@greptile-apps greptile-apps Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Additional Comments (1)

  1. transformer_engine/pytorch/1.txt, line 1-13 (link)

    style: build log accidentally committed - should be removed from repository

4 files reviewed, 4 comments

Edit Code Review Agent Settings | Greptile

Comment thread transformer_engine/common/__init__.py Resolved
Comment thread transformer_engine/common/__init__.py Resolved
Comment thread transformer_engine/common/__init__.py Resolved
@ksivaman

ksivaman commented Dec 3, 2025

Copy link
Copy Markdown
Member Author

/te-ci

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

4 files reviewed, 2 comments

Edit Code Review Agent Settings | Greptile

Comment thread transformer_engine/common/__init__.py Outdated
Comment on lines +371 to +374
if not system_nvrtc and not system_curand:
_CUBLAS_LIB_CTYPES = _load_cuda_library_from_python("cublas", strict=True)
_CUDART_LIB_CTYPES = _load_cuda_library_from_python("cudart", strict=True)
_CUDNN_LIB_CTYPES = _load_cuda_library_from_python("cudnn", strict=True)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: logic error: condition requires BOTH nvrtc AND curand to come from python before loading cublas/cudart/cudnn from python. If only one came from system, the block won't execute, creating mixed system/python library state. Line 374 also re-assigns _CUDNN_LIB_CTYPES, overwriting the system version loaded on line 367. Should be or not and, or remove the cudnn re-assignment.

Comment thread transformer_engine/pytorch/1.txt Resolved
Signed-off-by: Kirthi Shankar Sivamani <ksivamani@nvidia.com>
@ksivaman
ksivaman force-pushed the reorder_lib_loading branch from 347eed8 to 17e0bd0 Compare December 8, 2025 06:12

@greptile-apps greptile-apps Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Additional Comments (3)

  1. transformer_engine/common/__init__.py, line 321 (link)

    logic: missing libnvrtc-builtins filter - old code filtered both stub and libnvrtc-builtins, but new code only filters stub

  2. transformer_engine/common/__init__.py, line 377 (link)

    logic: incorrect library name: should be cuda_runtime not cudart - old code used _load_nvidia_cuda_library("cuda_runtime") on line 385

  3. transformer_engine/common/__init__.py, line 374-378 (link)

    logic: _CUBLAS_LIB_CTYPES and _CUDART_LIB_CTYPES undefined when CUDA toolkit present - if load_libs_for_no_ctk is False (system has toolkit), these variables are never assigned, causing NameError at runtime

3 files reviewed, 3 comments

Edit Code Review Agent Settings | Greptile

@ksivaman

ksivaman commented Dec 8, 2025

Copy link
Copy Markdown
Member Author

/te-ci

@ksivaman ksivaman added the 2.11.0 label Dec 8, 2025

@timmoon10 timmoon10 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@ksivaman

ksivaman commented Dec 9, 2025

Copy link
Copy Markdown
Member Author

/te-ci

@greptile-apps greptile-apps Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Additional Comments (5)

  1. transformer_engine/common/__init__.py, line 343-350 (link)

    logic: return type mismatch: _load_cuda_library_from_system returns (bool, handle) where handle is a single ctypes object (line 324), but _load_cuda_library_from_python returns (bool, list) where the second element is a list of handles (line 297). When system lookup fails and python lookup succeeds, this returns a list instead of a single handle, causing inconsistent return types.

  2. transformer_engine/common/__init__.py, line 376-378 (link)

    logic: these return lists (line 297 shows _load_cuda_library_from_python returns (bool, list)), but the variable names suggest single handles. This will cause runtime errors when these are used as ctypes objects later.

  3. transformer_engine/common/__init__.py, line 374 (link)

    logic: condition is backwards: should be or not and. When nvrtc comes from system (system_nvrtc=True) but curand comes from python (system_curand=False), you want to load the remaining libs from python to keep consistency. The and requires BOTH to be from python, which misses the mixed case.

  4. transformer_engine/common/__init__.py, line 273 (link)

    logic: glob pattern lib*{ext}.*[0-9] matches ALL .so files, not just lib_name. Should be lib{lib_name}*{ext}.*[0-9] to filter correctly. Same issue on lines 281 and 285.

  5. transformer_engine/common/__init__.py, line 378 (link)

    logic: this overwrites _CUDNN_LIB_CTYPES which was already loaded from system on line 367. If the condition on line 374 executes, you're replacing the system cudnn with python cudnn. Remove this line - cudnn is already loaded.

3 files reviewed, 5 comments

Edit Code Review Agent Settings | Greptile

@ksivaman
ksivaman merged commit 8ef3a33 into NVIDIA:main Dec 9, 2025
@ksivaman
ksivaman deleted the reorder_lib_loading branch December 9, 2025 06:44
KshitijLakhani pushed a commit that referenced this pull request Dec 11, 2025
Fixes to runtime loading logic and add missing deps

Signed-off-by: Kirthi Shankar Sivamani <ksivamani@nvidia.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

_load_cudnn() is not respecting LD_LIBRARY_PATH when searching for libcudnn

3 participants