From 91fcf8591942c10494678a58f815117bef08e636 Mon Sep 17 00:00:00 2001
From: Chris Maffeo <cmaffeo2@illinois.edu>
Date: Wed, 1 Nov 2023 15:09:44 -0500
Subject: [PATCH] Add CMake code to determine cuda architecture

---
 CMakeLists.txt | 35 ++++++++++++++++++++++++++++++-----
 1 file changed, 30 insertions(+), 5 deletions(-)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 8904dc5..82a95d6 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,13 +1,35 @@
 ## Specify the project
 cmake_minimum_required(VERSION 3.9 FATAL_ERROR)
 
-if(NOT CMAKE_CUDA_ARCHITECTURES)
-  set(CMAKE_CUDA_ARCHITECTURES 70 75)
-endif()
-
 # option(USE_CUDA "Use CUDA" ON)
 set(USE_CUDA ON)
 
+if(${USE_CUDA} AND NOT CMAKE_CUDA_ARCHITECTURES)
+  if(${CMAKE_VERSION} VERSION_LESS "3.18.0")
+    message("CMake support for CUDA prior to CMake 3.18 may not work well; consider switching to a more recent version of CMake if you encounter errors at compile- or run-time.")
+  endif()
+  if(${CMAKE_VERSION} VERSION_LESS "3.24.0") 
+    message("CMAKE_CUDA_ARCHITECTURES not specified; checking GPUs on your system for CUDA architecture...")
+    execute_process(COMMAND nvidia-smi --query-gpu=compute_cap --format=csv,noheader
+    COMMAND sort
+    COMMAND uniq
+    COMMAND tr "\\n" " "
+    COMMAND sed "s/ \\(.\\)/,\\1/g"
+    TIMEOUT 1
+    RESULT_VARIABLE GPU_QUERY_RESULT
+    OUTPUT_VARIABLE GPU_QUERY_OUTPUT
+    )
+    if (GPU_QUERY_RESULT EQUAL 0)
+      set(CMAKE_CUDA_ARCHITECTURES ${GPU_QUERY_OUTPUT})
+    else()
+      message("CUDA architecture could not be found! Guessing SM 7.5")  
+      set(CMAKE_CUDA_ARCHITECTURES 7.5)
+    endif()
+  else()
+    set(CMAKE_CUDA_ARCHITECTURES native)
+  endif()
+endif()
+
 ## specify the C++ standard
 set(CMAKE_CXX_STANDARD 14)
 set(CMAKE_CXX_STANDARD_REQUIRED True)
@@ -43,7 +65,10 @@ option(USE_NVTX "Build with NVTX profiling ranges" False)
 
 # (not yet optional) message(STATUS "USE_CUDA: ${USE_CUDA}")
 message(STATUS "DEBUG: ${DEBUG}")
-message(STATUS "USE_NCCL: ${USE_NCCL}")
+if(${USE_CUDA})
+  message(STATUS "CMAKE_CUDA_ARCHITECTURES: ${CMAKE_CUDA_ARCHITECTURES}")
+  message(STATUS "USE_NCCL: ${USE_NCCL}")
+endif()
 message(STATUS "USE_NVTX: ${USE_NVTX}")
 
 
-- 
GitLab