Skip to content

Commit

Permalink
Fixed gpu detection for cuda rocm etc using env vars
Browse files Browse the repository at this point in the history
Signed-off-by: Brian <[email protected]>
  • Loading branch information
bmahabirbu committed Nov 26, 2024
1 parent 590fe3e commit 2d5c1a5
Showing 1 changed file with 86 additions and 27 deletions.
113 changes: 86 additions & 27 deletions ramalama/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,12 +98,14 @@ def _image(self, args):
if args.image != default_image():
return args.image

gpu_type, _ = get_gpu()
if gpu_type == "HIP_VISIBLE_DEVICES":
if os.getenv("HIP_VISIBLE_DEVICES"):
return "quay.io/ramalama/rocm:latest"

if gpu_type == "ASAHI_VISIBLE_DEVICES":
if os.getenv("ASAHI_VISIBLE_DEVICES"):
return "quay.io/ramalama/asahi:latest"

if os.getenv("CUDA_VISIBLE_DEVICES"):
return "docker.io/brianmahabir/rama-cuda:v1"

return args.image

Expand Down Expand Up @@ -143,9 +145,15 @@ def setup_container(self, args):
if os.path.exists("/dev/kfd"):
conman_args += ["--device", "/dev/kfd"]

gpu_type, gpu_num = get_gpu()
if gpu_type == "HIP_VISIBLE_DEVICES" or gpu_type == "ASAHI_VISIBLE_DEVICES":
conman_args += ["-e", f"{gpu_type}={gpu_num}"]
for var in ["HIP_VISIBLE_DEVICES", "ASAHI_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"]:
value = os.getenv(var)
if value:
if var == "CUDA_VISIBLE_DEVICES":
# Special handling for CUDA (e.g., using '--gpus all')
conman_args += ["--gpus", "all"]
else:
# For HIP and ASAHI, we directly add the environment variable with its value
conman_args += ["-e", f"{var}={value}"]
return conman_args

def run_container(self, args, shortnames):
Expand Down Expand Up @@ -190,14 +198,14 @@ def cleanup():
return True

def gpu_args(self):
gpu_type, gpu_num = get_gpu()
gpu_args = []
if sys.platform == "darwin":
# llama.cpp will default to the Metal backend on macOS, so we don't need
# any additional arguments.
pass
elif sys.platform == "linux" and (
os.getenv("HIP_VISIBLE_DEVICES") or os.getenv("ASAHI_VISIBLE_DEVICES") or os.getenv("CUDA_VISIBLE_DEVICES")
):
elif sys.platform == "linux" and gpu_type is not None:
os.environ[gpu_type] = gpu_num
gpu_args = ["-ngl", "99"]
else:
print("GPU offload was requested but is not available on this system")
Expand Down Expand Up @@ -382,31 +390,82 @@ def check_valid_model_path(self, relative_target_path, model_path):
return os.path.exists(model_path) and os.readlink(model_path) == relative_target_path


def initialize_gpu_template():
"""Initialize a GPU template."""
return {
"gpus": [] # List of GPU entries, each with index, memory, and environment variables
}

def add_gpu_entry(template, gpu_arch, index, memory_mib, env_var):
"""Add a GPU entry to the template if it has valid memory."""
if memory_mib > 1024: # Only consider GPUs with > 1 GiB of memory
template["gpus"].append({
"gpu_arch": gpu_arch,
"index": index,
"memory_mib": memory_mib,
"env_var": env_var
})

def get_amdgpu(template):
"""Detect AMD GPUs and append valid entries to the template."""
for i, fp in enumerate(sorted(glob.glob('/sys/bus/pci/devices/*/mem_info_vram_total'))):
try:
with open(fp, 'r') as file:
memory_bytes = int(file.read())
memory_mib = memory_bytes / (1024 * 1024) # Convert bytes to MiB
add_gpu_entry(template, "AMD", str(i), memory_mib, "HIP_VISIBLE_DEVICES")
except Exception as ex:
print(f"Error reading AMD GPU memory info: {ex}")

def get_nvgpu(template):
"""Detect NVIDIA GPUs and append valid entries to the template."""
try:
command = ['nvidia-smi', '--query-gpu=index,memory.total', '--format=csv,noheader,nounits']
output = run_cmd(command).stdout.decode("utf-8")
for line in output.strip().split('\n'):
try:
index, memory_mib = line.split(',')
memory_mib = int(memory_mib)
add_gpu_entry(template, "NVIDIA", index.strip(), memory_mib, "CUDA_VISIBLE_DEVICES")
except ValueError as ex:
print(f"Error parsing NVIDIA GPU info: {ex}")
except FileNotFoundError:
print("The 'nvidia-smi' command was not found.")
except Exception as ex:
print(f"An unexpected error occurred while checking for NVIDIA GPUs: {ex}")

def get_gpu():
i = 0
gpu_num = 0
gpu_bytes = 0
for fp in sorted(glob.glob('/sys/bus/pci/devices/*/mem_info_vram_total')):
with open(fp, 'r') as file:
content = int(file.read())
if content > 1073741824 and content > gpu_bytes:
gpu_bytes = content
gpu_num = i
"""
Detects and selects a GPU with at least 1 GiB of memory.
Uses a centralized template to handle multiple GPU types.
Returns:
tuple: Environment variable name and GPU index (as a string), or (None, None) if no suitable GPU is found.
"""
# Check if system is running Asahi Linux (Apple Silicon)
if os.path.exists('/etc/os-release'):
try:
with open('/etc/os-release', 'r') as file:
if "asahi" in file.read().lower():
return "ASAHI_VISIBLE_DEVICES", "1"
except Exception as ex:
print(f"Error reading OS release file: {ex}")

i += 1
# Initialize the GPU template
gpu_template = initialize_gpu_template()

if gpu_bytes: # this is the ROCm/AMD case
return "HIP_VISIBLE_DEVICES", gpu_num
# Detect GPUs from different architectures
get_amdgpu(gpu_template)
get_nvgpu(gpu_template)

if os.path.exists('/etc/os-release'):
with open('/etc/os-release', 'r') as file:
content = file.read()
if "asahi" in content.lower():
return "ASAHI_VISIBLE_DEVICES", 1
# Sort GPUs by memory (descending order) and return the best one
if gpu_template["gpus"]:
best_gpu = sorted(gpu_template["gpus"], key=lambda x: x["memory_mib"], reverse=True)[0]
return best_gpu["env_var"], best_gpu["index"]

# No suitable GPU found
return None, None


def dry_run(args):
for arg in args:
if not arg:
Expand Down

0 comments on commit 2d5c1a5

Please sign in to comment.