Repository: pytorch
Issue: ROCm: libamdhip64.so is linked twice when building a torch C++ program
Labels: module: rocm,triaged

### 🐛 Describe the bug

Hi, I am giving a try to PyTorch C++ API, and for some reason `hipcc` appears to link twice some shared objects, once from `lib/python3.10/site-packages/torch/lib` and once from `/opt/rocm/lib`. This appears to bring some conflicts, which results in segfaults at the end of libtorch execution (similar to https://discuss.pytorch.org/t/segmentation-fault-at-end-of-execution-libtorch/211881).

I have this file structure:
```
CMakeLists.txt
gemv.h
gemv.hip
test_torch.cpp
```

Where `test_torch.cpp` is some frontend main function that does some stuff. CMakeLists.txt is the following:
```cmake
cmake_minimum_required(VERSION 3.10)

# Set project name.
set(PROJECT_NAME test_app)

project(${PROJECT_NAME})

# Set the C++ standard to C++17
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED YES)

# Set amd's Clang++ as the compiler
set(CMAKE_CXX_COMPILER /opt/rocm/bin/amdclang++)

# Specify the path to LibTorch (replace with your path)
set(Torch_DIR "/scratch/felmarty/miniconda3/envs/py310/lib/python3.10/site-packages/torch/share/cmake/Torch")

# Supported AMD GPU architectures.
set(HIP_SUPPORTED_ARCHS "gfx90a")

find_package(Torch REQUIRED)

# Importing torch recognizes and sets up some HIP/ROCm configuration but does
# not let cmake recognize .hip files. In order to get cmake to understand the
# .hip extension automatically, HIP must be enabled explicitly.
enable_language(HIP)

# Add kernels?
file(GLOB HIP_FILES *.hip)
# add_library(${PROJECT_NAME}_lib SHARED ${hip_files})

# Add the executable you want to compile
add_executable(${PROJECT_NAME} test_torch.cpp ${HIP_FILES})

# Link the executable with LibTorch
target_link_libraries(${PROJECT_NAME} "${TORCH_LIBRARIES}")

# Add additional compilation flags if needed
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}")
```

At the end of `test_app` execution:
```
1,8
res: 1
here <- libtorch stuff ends here
Segmentation fault (core dumped)
```

I tried to use as well:
```cmake
add_library(${PROJECT_NAME}_lib SHARED ${HIP_FILES})

# Add the executable you want to compile
add_executable(${PROJECT_NAME} test_torch.cpp)

# Link the executable with LibTorch
target_link_libraries(${PROJECT_NAME} "${TORCH_LIBRARIES}")

target_link_libraries(${PROJECT_NAME} ${PROJECT_NAME}_lib)

```
and I have the same segfault.

Looking at the linker, using the above full CMakeLists.txt, I get:
```
$ ldd test_app | grep libamdhip64
        libamdhip64.so.6 => /opt/rocm-6.2.4/lib/llvm/bin/../../../lib/libamdhip64.so.6 (0x00007a97ada00000)
        libamdhip64.so => /scratch/felmarty/miniconda3/envs/py310/lib/python3.10/site-packages/torch/lib/libamdhip64.so (0x00007a97aac00000)
```

so libamdhip64.so (and a few others) is linked twice.

Using a `Makefile` build system instead of cmake, I had the same issue with the linking
```bash
# compile test_torch.ccp to test_torch & gemv.hip to gemv before
hipcc -D_GLIBCXX_USE_CXX11_ABI=0 test_torch gemv -L${TORCH_PATH}/lib \
		-Wl,-rpath,${TORCH_PATH}/lib \
		-ldl -lc10 -ltorch_cpu -ltorch_hip -Wl,--as-needed
```

So far when only compiling `test_torch.cpp` and not the kernel, `-Wl,--as-needed` was enough to prevent `hipcc` to link from `/opt/rocm/lib` and only link from `lib/python3.10/site-packages/torch/lib`. But adding the actual `.hip` files add links to `/opt/rocm/lib` shared objects anyway.

Is this double linking expected? Do you think the segfault is related to this double linking? Should amd-related shared objects be linked from `/opt/rocm/lib` or from `lib/python3.10/site-packages/torch/lib`?

Edit: I looked at `nm -D /opt/rocm-6.2.4/liblibamdhip64.so.6` & `nm -D /path/to/py310/lib/python3.10/site-packages/torch/lib/libamdhip64.so` and the symbols defined are the same, so I am not sure what is happening here. There were 5-6 other duplicate links (other than `liblibamdhip64`) like this so something might be different in an other one.

Thank you!

### Versions

```
PyTorch version: 2.5.1+rocm6.2
Is debug build: False
CUDA used to build PyTorch: N/A
ROCM used to build PyTorch: 6.2.41133-dd7f95766

OS: Ubuntu 24.04 LTS (x86_64)
GCC version: (Ubuntu 13.2.0-23ubuntu4) 13.2.0
Clang version: Could not collect
CMake version: version 3.28.3
Libc version: glibc-2.39

Python version: 3.10.14 (main, May  6 2024, 19:42:50) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.8.0-48-generic-x86_64-with-glibc2.39
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: AMD Instinct MI250X/MI250 (gfx90a:sramecc+:xnack-)
Nvidia driver version: Could not collect
cuDNN version: Could not collect
HIP runtime version: 6.2.41133
MIOpen runtime version: 3.2.0
Is XNNPACK available: True

CPU:
Architecture:                         x86_64
CPU op-mode(s):                       32-bit, 64-bit
Address sizes:                        48 bits physical, 48 bits virtual
Byte Order:                           Little Endian
CPU(s):                               32
On-line CPU(s) list:                  0-31
Vendor ID:                            AuthenticAMD
Model name:                           AMD EPYC 73F3 16-Core Processor
CPU family:                           25
Model:                                1
Thread(s) per core:                   1
Core(s) per socket:                   16
Socket(s):                            2
Stepping:                             1
Frequency boost:                      enabled
CPU(s) scaling MHz:                   65%
CPU max MHz:                          4036.6211
CPU min MHz:                          1500.0000
BogoMIPS:                             6986.55
Flags:                                fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local user_shstk clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin brs arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold v_vmsave_vmload vgif v_spec_ctrl umip pku ospke vaes vpclmulqdq rdpid overflow_recov succor smca fsrm debug_swap
Virtualization:                       AMD-V
L1d cache:                            1 MiB (32 instances)
L1i cache:                            1 MiB (32 instances)
L2 cache:                             16 MiB (32 instances)
L3 cache:                             512 MiB (16 instances)
NUMA node(s):                         2
NUMA node0 CPU(s):                    0-15
NUMA node1 CPU(s):                    16-31
Vulnerability Gather data sampling:   Not affected
Vulnerability Itlb multihit:          Not affected
Vulnerability L1tf:                   Not affected
Vulnerability Mds:                    Not affected
Vulnerability Meltdown:               Not affected
Vulnerability Mmio stale data:        Not affected
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Not affected
Vulnerability Spec rstack overflow:   Mitigation; Safe RET
Vulnerability Spec store bypass:      Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:             Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:             Mitigation; Retpolines; IBPB conditional; IBRS_FW; STIBP disabled; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] numpy==1.26.4
[pip3] onnx==1.16.2
[pip3] onnxoptimizer==0.3.13
[pip3] onnxruntime==1.18.1
[pip3] onnxruntime_extensions==0.12.0
[pip3] onnxsim==0.4.36
[pip3] pytorch-triton-rocm==3.1.0
[pip3] torch==2.5.1+rocm6.2
[pip3] torchaudio==2.5.1+rocm6.2
[pip3] torchvision==0.20.1+rocm6.2
[conda] numpy                     1.26.4                   pypi_0    pypi
[conda] pytorch-triton-rocm       3.1.0                    pypi_0    pypi
[conda] torch                     2.5.1+rocm6.2            pypi_0    pypi
[conda] torchaudio                2.5.1+rocm6.2            pypi_0    pypi
[conda] torchvision               0.20.1+rocm6.2           pypi_0    pypi
```

cc @jeffdaily @sunway513 @jithunnair-amd @pruthvistony @ROCmSupport @dllehr-amd @jataylo @hongxiayang @naromero77amd