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

---
 CMakeLists.txt | 31 +++++++++++++++++++++++++++----
 1 file changed, 27 insertions(+), 4 deletions(-)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 0512280..9aee9f9 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,12 +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()
+
 set(USE_MPI OFF)
 
 ## specify the C++ standard
-- 
GitLab