#!/usr/bin/env python3 """which-setup: which multi-GPU setup fits the NVIDIA cards in this machine, and what is left to install. The same questions as the which-setup pictures (CUDA P2P, DRMShare with its NCCL fork, or plain NCCL through system RAM), answered from the machine itself: every NVIDIA card on the PCI bus (also those the driver does not run), each card's generation, where it sits on PCIe (CPU lanes, the chipset, a switch), its BAR1 window, the IOMMU, the driver branch and its kernel modules, the CUDA toolkits installed, PyTorch, what CUDA offers between each pair right now and whether DRMShare's option is loaded (by hand, or at every boot). Then the setup that fits, step by step, with what is already done, and the commands (Ubuntu's) for what is left. It prints the commands; it never runs them. python3 which-setup.py looks only: changes nothing, installs nothing python3 which-setup.py --python ~/venv/bin/python also checks the PyTorch (and vLLM) in that Python; repeatable python3 which-setup.py --test also copies 64 MiB each way between every pair CUDA offers P2P for (one direction at a time, as CUDA's own bandwidth test does) and checks every byte: CUDA saying "OK" is not proof Linux, Python 3.8 or newer, nothing to install. CUDA's answers come from the driver's libcuda.so.1, no CUDA toolkit needed. GPU numbers are nvidia-smi's (PCI order); set CUDA_DEVICE_ORDER=PCI_BUS_ID to get the same numbers in CUDA programs. From https://github.com/Cinderella-Man/drmshare and https://github.com/Cinderella-Man/how-to-enable-p2p-on-nvidia-gpus (the same file in both). """ import argparse import ctypes import glob import importlib.util import json import os import re import shutil import subprocess import sys import time P2P_GUIDE = 'https://github.com/Cinderella-Man/how-to-enable-p2p-on-nvidia-gpus' DRMSHARE = 'https://github.com/Cinderella-Man/drmshare' OLD = ('Maxwell', 'Pascal', 'Volta') # NVIDIA's closed driver only; its 580 branch is their last BDF = re.compile(r'[0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]') GT_S = {'2.5': '1.0', '5.0': '2.0', '8.0': '3.0', '16.0': '4.0', '32.0': '5.0', '64.0': '6.0'} CHIPS = (('GM', 'Maxwell'), ('GP', 'Pascal'), ('GV', 'Volta'), ('TU', 'Turing'), ('GA', 'Ampere'), ('AD', 'Ada'), ('GH', 'Hopper'), ('GB', 'Blackwell')) DEVICE_IDS = ((0x1340, 0x143f, 'Maxwell'), (0x17c0, 0x17ff, 'Maxwell'), (0x15f0, 0x15ff, 'Pascal'), (0x1b00, 0x1d3f, 'Pascal'), (0x1d80, 0x1dbf, 'Volta'), (0x1e00, 0x1fff, 'Turing'), (0x2180, 0x21ff, 'Turing'), (0x20b0, 0x20ff, 'Ampere'), (0x2200, 0x22ff, 'Ampere'), (0x2300, 0x233f, 'Hopper'), (0x2400, 0x25ff, 'Ampere'), (0x2680, 0x28ff, 'Ada'), (0x2900, 0x2fff, 'Blackwell')) # The lowest compute capability of each generation, for cards the driver does not run (CUDA cannot tell theirs). ARCH_CC = {'Maxwell': (5, 0), 'Pascal': (6, 0), 'Volta': (7, 0), 'Turing': (7, 5), 'Ampere': (8, 0), 'Ada': (8, 9), 'Hopper': (9, 0), 'Blackwell': (12, 0)} # The oldest CUDA toolkit that builds for each generation, and the first that cannot. CUDA_FROM = {'Ampere': (11, 1), 'Ada': (11, 8), 'Hopper': (11, 8), 'Blackwell': (12, 8)} CUDA_UNTIL = {'Maxwell': (13, 0), 'Pascal': (13, 0), 'Volta': (13, 0)} # ---------------------------------------------------------------------------------------------------------- reading def arch_of(cc): major, minor = cc if major == 5: return 'Maxwell' if major == 6: return 'Pascal' if major == 7: return 'Turing' if minor >= 5 else 'Volta' if major == 8: return 'Ada' if minor == 9 else 'Ampere' if major == 9: return 'Hopper' if major >= 10: return 'Blackwell' return 'Kepler or older' def sysread(path, default=''): try: with open(path) as f: return f.read().strip() except OSError: return default def drmshare_boot(): """DRMShare's boot install (its scripts/drmshare-boot): None if it is not installed, else whether the running kernel has its line in /etc/depmod.d/zz-drmshare.conf with the option on in /etc/modprobe.d/drmshare.conf.""" conf, opt = sysread('/etc/depmod.d/zz-drmshare.conf'), sysread('/etc/modprobe.d/drmshare.conf') if not conf and not opt: return None field = '^' + re.sub(r'([.+*?(){}|$])', r'[\1]', os.uname().release) + '$' line = any(l.split() == ['override', 'nvidia-drm', field, 'updates/drmshare'] for l in conf.splitlines()) return line and 'options nvidia-drm peer_vidmem_dmabuf=1' in opt.splitlines() def mib(n): return f'{n // (1 << 30)} GiB' if n >= 1 << 30 and n % (1 << 30) == 0 else f'{n // (1 << 20)} MiB' def run(cmd, timeout=60): try: return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout except (OSError, subprocess.SubprocessError): return '' def pci_name(bdf): out = run(['lspci', '-s', bdf]) return out.split(': ', 1)[1].strip() if ': ' in out else '' class Gpu: pass def read_gpus(): q = 'index,name,pci.bus_id,memory.total,driver_version,compute_cap' out = run(['nvidia-smi', f'--query-gpu={q}', '--format=csv,noheader,nounits']) if not out.strip(): # older nvidia-smi without compute_cap: CUDA tells it below out = run(['nvidia-smi', f'--query-gpu={q.rsplit(",", 1)[0]}', '--format=csv,noheader,nounits']) gpus = [] for line in out.strip().splitlines(): f = [x.strip() for x in line.split(',')] if len(f) < 5 or not f[0].isdigit(): continue g = Gpu() g.index, g.name, g.vram, g.driver = int(f[0]), f[1], int(f[3]) << 20, f[4] g.bdf = f[2][-12:].lower() g.cc = tuple(int(x) for x in f[5].split('.')) if len(f) > 5 and re.match(r'^\d+\.\d+$', f[5]) else None g.listed, g.label = True, f'GPU {g.index}' gpus.append(g) return gpus def read_unlisted(listed): """NVIDIA display controllers on the PCI bus that nvidia-smi does not list: the driver does not run them.""" out = [] have = {g.bdf for g in listed} for d in sorted(glob.glob('/sys/bus/pci/devices/*')): bdf = os.path.basename(d) cls = sysread(f'{d}/class') if sysread(f'{d}/vendor') != '0x10de' or not (cls.startswith('0x0300') or cls.startswith('0x0302')) \ or bdf in have: continue g = Gpu() g.bdf, g.index, g.vram, g.cc, g.driver = bdf, None, 0, None, '' g.listed, g.label = False, f'card {bdf[5:]}' full = pci_name(bdf) g.name = re.sub(r'^NVIDIA Corporation ', '', full) or f'NVIDIA device {sysread(f"{d}/device")}' g.arch = '' chip = re.search(r'\b(G[MPVAHB]|TU|AD)\d{2,3}', full) if chip: g.arch = dict(CHIPS).get(chip.group(1), '') if not g.arch: dev = int(sysread(f'{d}/device', '0'), 16) g.arch = next((a for lo, hi, a in DEVICE_IDS if lo <= dev <= hi), 'unknown') drv = os.path.realpath(f'{d}/driver') if os.path.exists(f'{d}/driver') else '' g.bound = os.path.basename(drv) if drv else '' out.append(g) return out def read_pci(g): dev = f'/sys/bus/pci/devices/{g.bdf}' comps = BDF.findall(os.path.realpath(dev)) g.root = comps[0] if len(comps) > 1 else None between = comps[1:-1] vendor = lambda b: int(sysread(f'/sys/bus/pci/devices/{b}/vendor', '0'), 16) if not g.root: g.place, g.via = 'cpu', '' elif not between: dev_no = int(g.root.split(':')[2].split('.')[0], 16) if vendor(g.root) == 0x8086 and dev_no in (0x1b, 0x1c, 0x1d): # Intel's chipset (PCH) root ports g.place, g.via = 'chipset', 'Intel chipset (PCH) root port' else: g.place, g.via = 'cpu', '' else: v = vendor(between[0]) g.place = 'chipset' if v in (0x1022, 0x8086) else 'asmedia' if v == 0x1b21 else 'switch' g.via = pci_name(between[0]) or f'bridge {between[0]} (vendor {v:04x})' g.group = (g.root, between[0]) if between else None if g.place == 'chipset' and not between: # all of Intel's PCH root ports are one chipset g.group = ('intel-pch',) width = sysread(f'{dev}/current_link_width') speeds = [sysread(f'{dev}/max_link_speed')] if len(comps) > 1: speeds.append(sysread(f'/sys/bus/pci/devices/{comps[-2]}/max_link_speed')) nums = [float(s.split()[0]) for s in speeds if s and s[0].isdigit()] top = f'{min(nums):.1f}' if nums else '' g.link = f'PCIe {GT_S.get(top, "?")} x{width}' if top and width else '' res = sysread(f'{dev}/resource').splitlines() g.bar1 = 0 if len(res) > 1: a, b = (int(x, 16) for x in res[1].split()[:2]) g.bar1 = b - a + 1 if b > a else 0 t = sysread(f'{dev}/iommu_group/type') g.iommu = 'off' if not os.path.exists(f'{dev}/iommu_group') else ('passthrough' if t == 'identity' else f'translated ({t or "DMA"})') g.usbc = [] for s in sorted(glob.glob(f'/sys/bus/pci/devices/{g.bdf[:-1]}[1-7]')): cls = sysread(f'{s}/class') if sysread(f'{s}/vendor') == '0x10de' and (cls.startswith('0x0c03') or cls.startswith('0x0c80')): g.usbc.append(os.path.basename(s)) g.geforce = bool(re.search(r'GeForce|TITAN', g.name, re.I)) g.render = None for r in glob.glob('/sys/class/drm/renderD*'): b = BDF.findall(os.path.realpath(f'{r}/device')) if b and b[-1] == g.bdf: g.render = os.access(f'/dev/dri/{os.path.basename(r)}', os.R_OK | os.W_OK) def topo_p2p(): """nvidia-smi's own answer per pair: OK, NS (not supported), CNS (chipset), GNS (GPU), TNS (topology).""" m = {} for kind in ('r', 'w'): text = re.sub(r'\x1b\[[0-9;]*m', '', run(['nvidia-smi', 'topo', '-p2p', kind])) # the header is underlined lines = [l.split() for l in text.splitlines() if l.strip()] if not lines: continue head = [x for x in lines[0] if x.startswith('GPU')] for row in lines[1:]: if row and row[0].startswith('GPU') and row[0][3:].isdigit(): for j, v in enumerate(row[1:1 + len(head)]): m.setdefault((int(row[0][3:]), int(head[j][3:])), {})[kind] = v return m def find_fork(): """A libnccl.so.2 named in LD_PRELOAD or found in LD_LIBRARY_PATH that carries the fork's transport.""" cands = [p for p in re.split(r'[: ]', os.environ.get('LD_PRELOAD', '')) if p.endswith('libnccl.so.2')] cands += [os.path.join(d, 'libnccl.so.2') for d in os.environ.get('LD_LIBRARY_PATH', '').split(':') if d] for c in cands: try: with open(c, 'rb') as f: if b'DRMShare: ' in f.read(): return os.path.realpath(c) except OSError: pass return '' def find_toolkits(): """Every nvcc found: on PATH, Ubuntu's /usr/bin/nvcc, NVIDIA's /usr/local/cuda*; (version, path).""" paths = [shutil.which('nvcc') or '', '/usr/bin/nvcc'] + sorted(glob.glob('/usr/local/cuda*/bin/nvcc')) seen, out = set(), [] for p in paths: if not p or not os.path.exists(p) or os.path.realpath(p) in seen: continue seen.add(os.path.realpath(p)) m = re.search(r'release (\d+)\.(\d+)', run([p, '--version'])) if m: out.append(((int(m.group(1)), int(m.group(2))), p)) return out TORCH_PROBE = r''' import json, importlib.metadata as md out = {} try: import torch out['torch'] = torch.__version__ out['cuda'] = torch.version.cuda f = getattr(torch._C, '_cuda_getArchFlags', None) out['arch'] = (f() or '').split() if f else [] try: out['available'] = torch.cuda.is_available() except Exception: out['available'] = False except Exception as e: out['error'] = '%s: %s' % (type(e).__name__, e) try: out['vllm'] = md.version('vllm') except Exception: pass print('WHICHSETUP' + json.dumps(out)) ''' def probe_torch(python): for line in run([python, '-c', TORCH_PROBE], timeout=300).splitlines(): if line.startswith('WHICHSETUP'): return json.loads(line[10:]) return {'error': 'could not run it'} def arch_covered(flags, cc): """Does a build with these -gencode targets run on a card of compute capability cc?""" for f in flags: m = re.match(r'^(sm|compute)_(\d+)(\d)$', f) if not m: continue kind, major, minor = m.group(1), int(m.group(2)), int(m.group(3)) if kind == 'sm' and major == cc[0] and minor <= cc[1]: return True if kind == 'compute' and (major, minor) <= cc: return True return False # ------------------------------------------------------------------------------------------------------------- CUDA class Cuda: def __init__(self): self.lib = ctypes.CDLL('libcuda.so.1') self.ok(self.lib.cuInit(0), 'cuInit') def ok(self, r, what): if r != 0: s = ctypes.c_char_p() self.lib.cuGetErrorName(r, ctypes.byref(s)) raise RuntimeError(f'{what}: {s.value.decode() if s.value else r}') def driver_cuda(self): v = ctypes.c_int() self.ok(self.lib.cuDriverGetVersion(ctypes.byref(v)), 'cuDriverGetVersion') return (v.value // 1000, v.value % 1000 // 10) def devices(self): n = ctypes.c_int() self.ok(self.lib.cuDeviceGetCount(ctypes.byref(n)), 'cuDeviceGetCount') out = {} for i in range(n.value): d = ctypes.c_int() self.ok(self.lib.cuDeviceGet(ctypes.byref(d), i), 'cuDeviceGet') buf = ctypes.create_string_buffer(32) self.ok(self.lib.cuDeviceGetPCIBusId(buf, 32, d), 'cuDeviceGetPCIBusId') mj, mn = ctypes.c_int(), ctypes.c_int() self.lib.cuDeviceGetAttribute(ctypes.byref(mj), 75, d) self.lib.cuDeviceGetAttribute(ctypes.byref(mn), 76, d) out[buf.value.decode()[-12:].lower()] = (d.value, (mj.value, mn.value)) return out def can_access(self, a, b): v = ctypes.c_int() self.ok(self.lib.cuDeviceCanAccessPeer(ctypes.byref(v), a, b), 'cuDeviceCanAccessPeer') return bool(v.value) def copy_check(self, a, b, nbytes=64 << 20, rounds=5): """Peer copies a -> b and b -> a, one direction at a time; every byte checked; GB/s of each direction.""" L = self.lib L.cuMemcpyPeer.argtypes = [ctypes.c_uint64, ctypes.c_void_p, ctypes.c_uint64, ctypes.c_void_p, ctypes.c_size_t] L.cuMemcpyHtoD_v2.argtypes = [ctypes.c_uint64, ctypes.c_void_p, ctypes.c_size_t] L.cuMemcpyDtoH_v2.argtypes = [ctypes.c_void_p, ctypes.c_uint64, ctypes.c_size_t] L.cuMemsetD8_v2.argtypes = [ctypes.c_uint64, ctypes.c_ubyte, ctypes.c_size_t] L.cuMemFree_v2.argtypes = [ctypes.c_uint64] L.cuCtxSetCurrent.argtypes = [ctypes.c_void_p] L.cuCtxEnablePeerAccess.argtypes = [ctypes.c_void_p, ctypes.c_uint] L.cuCtxDisablePeerAccess.argtypes = [ctypes.c_void_p] ctx = {} for d in (a, b): c = ctypes.c_void_p() self.ok(L.cuDevicePrimaryCtxRetain(ctypes.byref(c), d), 'cuDevicePrimaryCtxRetain') ctx[d] = c bufs = [] try: def alloc(d): L.cuCtxSetCurrent(ctx[d]) p = ctypes.c_uint64() self.ok(L.cuMemAlloc_v2(ctypes.byref(p), ctypes.c_size_t(nbytes)), 'cuMemAlloc') bufs.append((d, p.value)) return p.value for x, y in ((a, b), (b, a)): L.cuCtxSetCurrent(ctx[x]) r = L.cuCtxEnablePeerAccess(ctx[y], 0) if r not in (0, 704): # 704: already enabled self.ok(r, 'cuCtxEnablePeerAccess') result = {} for src, dst in ((a, b), (b, a)): s, t = alloc(src), alloc(dst) data = os.urandom(nbytes) L.cuCtxSetCurrent(ctx[src]) self.ok(L.cuMemcpyHtoD_v2(s, data, nbytes), 'cuMemcpyHtoD') L.cuCtxSetCurrent(ctx[dst]) self.ok(L.cuMemsetD8_v2(t, 0x5A, nbytes), 'cuMemsetD8') self.ok(L.cuCtxSynchronize(), 'cuCtxSynchronize') self.ok(L.cuMemcpyPeer(t, ctx[dst], s, ctx[src], nbytes), 'cuMemcpyPeer') self.ok(L.cuCtxSynchronize(), 'cuCtxSynchronize') back = ctypes.create_string_buffer(nbytes) self.ok(L.cuMemcpyDtoH_v2(back, t, nbytes), 'cuMemcpyDtoH') got = back.raw wrong = 0 if got == data else sum(1 for i in range(0, nbytes, 4096) if got[i:i + 4096] != data[i:i + 4096]) t0 = time.perf_counter() for _ in range(rounds): self.ok(L.cuMemcpyPeer(t, ctx[dst], s, ctx[src], nbytes), 'cuMemcpyPeer') for d in (src, dst): L.cuCtxSetCurrent(ctx[d]) self.ok(L.cuCtxSynchronize(), 'cuCtxSynchronize') result[(src, dst)] = (wrong, rounds * nbytes / (time.perf_counter() - t0) / 1e9) return result finally: for d, p in bufs: L.cuCtxSetCurrent(ctx[d]) L.cuMemFree_v2(p) for x, y in ((a, b), (b, a)): L.cuCtxSetCurrent(ctx[x]) L.cuCtxDisablePeerAccess(ctx[y]) for d in (a, b): L.cuDevicePrimaryCtxRelease_v2(d) # ---------------------------------------------------------------------------------------------------------- helpers def pair_link(a, b): """'cpu' (both on CPU root ports), 'same-chipset', 'same-switch', 'same-asmedia', or 'mixed'.""" if a.place == 'cpu' and b.place == 'cpu': return 'cpu' if a.group and a.group == b.group: return {'chipset': 'same-chipset', 'asmedia': 'same-asmedia'}.get(a.place, 'same-switch') return 'mixed' def where(g): if g.place == 'cpu': return 'on CPU lanes (directly on a CPU root port)' if g.place == 'chipset': return f'behind the chipset ({g.via})' if g.place == 'asmedia': return f'behind an ASMedia chip ({g.via}): a chipset or a cheap switch' return f'behind a PCIe switch ({g.via})' def mark(done): return {True: '[done]', False: '[to do]', None: '[check]'}[done] def names(cards): return ', '.join(g.label for g in cards) def ver(v): return f'{v[0]}.{v[1]}' def main(): ap = argparse.ArgumentParser(description='Which multi-GPU setup fits the NVIDIA cards in this machine, and what ' 'is left to install.') ap.add_argument('--test', action='store_true', help='copy 64 MiB each way between pairs CUDA offers P2P for and ' 'check every byte (one direction at a time)') ap.add_argument('--python', action='append', default=[], metavar='PYTHON', help='a Python (e.g. ~/venv/bin/python) whose PyTorch and vLLM to check; repeatable') args = ap.parse_args() listed = read_gpus() unlisted = read_unlisted(listed) gpus = listed + unlisted if not gpus: print('No NVIDIA graphics card on the PCI bus.') return 2 for g in gpus: read_pci(g) version = sysread('/proc/driver/nvidia/version').splitlines() loaded = bool(version) open_modules = loaded and 'Open Kernel Module' in version[0] m = re.search(r'(\d+)\.(\d+)(\.\d+)?', version[0]) if loaded else None driver = m.group(0) if m else '' branch = int(m.group(1)) if m else None drmshare = sysread('/sys/module/nvidia_drm/parameters/peer_vidmem_dmabuf') == 'Y' boot = drmshare_boot() cpuinfo = sysread('/proc/cpuinfo')[:2000] intel = 'GenuineIntel' in cpuinfo ubuntu = 'ubuntu' in sysread('/etc/os-release').lower() topo = topo_p2p() if listed else {} cuda, cuda_err, cudev, drv_cuda = None, '', {}, None if listed: try: cuda = Cuda() cudev = cuda.devices() drv_cuda = cuda.driver_cuda() except (OSError, RuntimeError) as e: cuda_err = str(e) for g in listed: g.cudev = cudev.get(g.bdf, (None, None))[0] if g.cc is None: g.cc = cudev.get(g.bdf, (None, (0, 0)))[1] g.arch = arch_of(g.cc) for g in unlisted: g.cudev = None # ------------------------------------------------------------------------------------------------ the cards print('which-setup: the NVIDIA cards in this machine, the setup that fits them, and what is left to install\n') mods = 'open' if open_modules else 'closed' print((f'Driver {driver}, NVIDIA\'s {mods} kernel modules' + (f' (CUDA {ver(drv_cuda)} and older)' if drv_cuda else '') if loaded else 'No NVIDIA driver loaded') + f'. DRMShare\'s option (peer_vidmem_dmabuf): ' + ('loaded, installed for every boot' if drmshare and boot else 'loaded by hand (gone after a reboot)' if drmshare else 'not loaded, installed for the next boot' if boot else 'not loaded') + '. ' f'CPU: {"Intel" if intel else "AMD" if "AuthenticAMD" in cpuinfo else "other"}.\n') for g in gpus: if g.listed: bar = (f'BAR1 {mib(g.bar1)}' + ('' if g.bar1 >= g.vram else ' (smaller than its memory)')) if g.bar1 \ else 'BAR1 ?' print(f'{g.label} {g.name} {g.arch} ({g.cc[0]}.{g.cc[1]}) {g.bdf} {mib(g.vram)}, {bar}') else: print(f'{g.label} {g.name} {g.arch} {g.bdf} NOT RUNNING: the NVIDIA driver does not run this card ' f'(kernel driver: {g.bound or "none"})' + (f', BAR1 {mib(g.bar1)}' if g.bar1 else '')) extra = f'; USB-C functions present: {", ".join(g.usbc)}' if g.usbc else '' print(f' {where(g)}{", " + g.link if g.link else ""}; IOMMU {g.iommu}{extra}') if cuda_err: print(f'\nCUDA could not be asked ({cuda_err}): the "CUDA P2P now" answers below are unknown.') gens = {g.arch for g in gpus} old = sorted(a for a in gens if a in OLD) cmds = [] # (title, lines) printed at the end # ------------------------------------------------------------------------------------------------ software print('\nDriver and software') if old and 'Blackwell' in gens: print(f' [!] No NVIDIA driver runs these cards together: {"/".join(old)} cards need the closed kernel ' f'modules (580 is their last branch), Blackwell cards need the open ones. Split them over two machines.') if old: ok = loaded and not open_modules and branch == 580 why = ('no NVIDIA driver is loaded' if not loaded else 'the open modules do not run them' if open_modules else f'branch {branch} no longer runs them' if branch and branch > 580 else f'branch {branch} is older than the tested 580' if branch and branch < 580 else '') print(f' {mark(ok)} NVIDIA\'s driver 580 with its closed kernel modules: the last branch for ' f'{"/".join(old)} cards ({names([g for g in gpus if g.arch in OLD])})' + ('' if ok else f'; {why}')) if not ok: lines = [] if loaded and branch and branch != 580: lines += [f'# from DRMShare\'s docs/volta-dmabuf.md: driver {branch} out, the closed 580 in', f'apt-mark showhold > ~/holds-before-580.txt', f'sudo apt-mark unhold $(cat ~/holds-before-580.txt)', f'sudo apt purge $(dpkg -l | awk \'/^(ii|hi)/ && /-{branch}/ {{print $2}}\')'] elif open_modules: lines += ['# the open 580 modules out first: sudo apt purge the nvidia-*-580-open packages'] lines += ['sudo apt install nvidia-driver-580 nvidia-kernel-source-580', 'sudo apt-mark hold $(dpkg -l | awk \'/^(ii|hi)/ && /-580/ {print $2}\')', 'sudo reboot'] cmds.append(('NVIDIA\'s closed driver 580 (not -open; Ubuntu\'s installer picks 595-open)', lines)) elif 'Blackwell' in gens and loaded and not open_modules: print(' [to do] the open kernel modules: NVIDIA\'s closed modules do not run Blackwell cards') elif loaded: print(f' [done] driver {driver} ({mods} modules) runs every card') else: print(' [to do] NVIDIA\'s driver: none is loaded') for g in unlisted: if g.arch in OLD and old and (open_modules or (branch or 0) > 580): continue # said above reason = {'nouveau': 'nouveau (the kernel\'s own driver) holds it: NVIDIA\'s driver is not installed or ' 'not loaded', 'vfio-pci': 'it is given to a virtual machine (vfio-pci)'}.get( g.bound, 'NVIDIA\'s driver did not take it: see `sudo dmesg | grep -i nvrm`') print(f' [to do] {g.label} ({g.name}) is not running: {reason}') toolkits = find_toolkits() needs = [g for g in gpus if g.arch in CUDA_FROM or g.arch in CUDA_UNTIL] def tk_fits(v): bad = [g for g in gpus if (g.arch in CUDA_FROM and v < CUDA_FROM[g.arch]) or (g.arch in CUDA_UNTIL and v >= CUDA_UNTIL[g.arch])] too_new = drv_cuda is not None and v[0] > drv_cuda[0] return bad, too_new good = [] for v, p in toolkits: bad, too_new = tk_fits(v) if not bad and not too_new: good.append((v, p)) if not toolkits: print(' [check] CUDA toolkit: none found (needed only to build: the NCCL fork, llama.cpp, test programs)') else: print(f' {mark(bool(good))} CUDA toolkit, to build for these cards:') for v, p in toolkits: bad, too_new = tk_fits(v) what = [] if bad: arches = sorted({g.arch for g in bad}) what.append(f'cannot build for {"/".join(arches)} ({names(bad)}): ' + ('CUDA 13 dropped Maxwell, Pascal and Volta' if any(a in OLD for a in arches) else f'needs CUDA {ver(max(CUDA_FROM[a] for a in arches if a in CUDA_FROM))} or newer')) if too_new: what.append(f'what it builds needs a driver for CUDA {v[0]}, this one is for {ver(drv_cuda)}') print(f' CUDA {ver(v)} ({p}): ' + ('; '.join(what) if what else 'builds for every card')) if not good and (toolkits or needs): if old: cmds.append(('a CUDA 12 toolkit (CUDA 13 cannot build for Maxwell, Pascal or Volta)', ['sudo apt install nvidia-cuda-toolkit # Ubuntu 26.04: CUDA 12.4, as /usr/bin/nvcc'])) elif toolkits: cmds.append(('a newer CUDA toolkit', [f'# NVIDIA\'s CUDA 13: {P2P_GUIDE}/blob/main/docs/procedure.md, step 5'])) pythons = list(args.python) if importlib.util.find_spec('torch') is not None: pythons.insert(0, sys.executable) torch_any, torch_cmd = False, None for py in pythons: t = probe_torch(os.path.expanduser(py)) if 'error' in t: print(f' [check] PyTorch in {py}: {t["error"]}') continue flags = t.get('arch') or [] missing = [g for g in gpus if (g.cc or ARCH_CC.get(g.arch)) and not arch_covered(flags, g.cc or ARCH_CC[g.arch])] tcuda = tuple(int(x) for x in (t.get('cuda') or '0.0').split('.')[:2]) too_new = drv_cuda is not None and tcuda[0] > drv_cuda[0] ok = not missing and not too_new and bool(flags) torch_any = torch_any or ok what = [] if not flags: what.append('a build without CUDA' if not t.get('cuda') else 'its kernel list could not be read') if missing: what.append(f'no kernels for {names(missing)} ({"/".join(sorted({g.arch for g in missing}))}): ' '"no kernel image is available" at the first CUDA call on ' + ('it' if len(missing) == 1 else 'them') + ('' if len(missing) == len(gpus) else '; fine for the other cards')) if too_new: what.append(f'built for CUDA {t["cuda"]}, newer than this driver ({ver(drv_cuda)})') print(f' {mark(ok)} PyTorch {t["torch"]} in {py}: ' + ('; '.join(what) if what else 'kernels for every card, runs on this driver')) if t.get('vllm') and 'Volta' in gens: print(f' [!] vLLM {t["vllm"]} in {py}: vLLM\'s own builds have no Volta code; on the V100 it runs ' 'through volta-forever (github.com/nbald/volta-forever)' + (', one process per card beside a newer one: tools/vllm-volta (next to this script) starts them' if len(gens) > 1 else '') + '; or use llama.cpp') if not ok and torch_cmd is None: idx = 'cu126' if old else None torch_cmd = (f'PyTorch for every card (the one in {py} cannot run on all of them)', ['sudo apt install python3-venv', 'python3 -m venv ~/venv', 'mkdir -p ~/pip-tmp # /tmp is in RAM on Ubuntu 26.04: too small for PyTorch', 'TMPDIR=~/pip-tmp ~/venv/bin/pip install torch' + (f' --index-url https://download.pytorch.org/whl/{idx} # its CUDA 12.6 build still ' 'has Maxwell, Pascal and Volta kernels' if idx else '')]) if torch_cmd and not torch_any: cmds.append(torch_cmd) if not pythons: print(f' [check] PyTorch: not in this Python ({sys.executable}); to check yours: ' f'--python /bin/python') if len(gpus) < 2: print('\nOne GPU: nothing to share between cards. With two or more, run this again.') print_cmds(cmds, ubuntu) return 0 # ------------------------------------------------------------------------------------------------ the pairs if gens == {'Turing', 'Ampere'}: box = 'p2p-mix' elif len(gens) == 1: box = 'p2p-one' else: box = 'none' pairs = [] print('\nPairs') for i, a in enumerate(gpus): for b in gpus[i + 1:]: p = Gpu() p.a, p.b, p.link = a, b, pair_link(a, b) p.cuda = (cuda.can_access(a.cudev, b.cudev) and cuda.can_access(b.cudev, a.cudev) if cuda and a.cudev is not None and b.cudev is not None else None) t = topo.get((a.index, b.index), {}) if a.listed and b.listed else {} p.topo = f'read {t.get("r", "?")}, write {t.get("w", "?")}' if t else '' if p.link in ('same-chipset', 'same-asmedia'): p.route = 'ram' elif box != 'none': p.route = 'p2p' elif a.arch == b.arch and a.arch in ('Pascal', 'Volta'): p.route = 'p2p-580' else: p.route = 'drm' p.test = None pairs.append(p) if args.test: for p in pairs: if p.cuda: try: p.test = cuda.copy_check(p.a.cudev, p.b.cudev) except RuntimeError as e: p.test = str(e) by_cudev = {g.cudev: g for g in listed} for p in pairs: a, b = p.a, p.b rel = 'same generation' if a.arch == b.arch else f'{a.arch} + {b.arch}' link = {'cpu': 'both on CPU lanes', 'same-chipset': 'both behind one chipset', 'same-asmedia': 'both behind one ASMedia chip', 'same-switch': 'both behind one PCIe switch', 'mixed': 'not both on CPU lanes'}[p.link] now = {True: 'yes', False: 'no', None: 'unknown'}[p.cuda] print(f'{a.label} + {b.label}: {rel}, {link}; CUDA P2P now: {now}' + (f' (nvidia-smi: {p.topo})' if p.topo else '')) if isinstance(p.test, str): print(f' copy check failed to run: {p.test}') elif p.test: for (s, d), (wrong, gbs) in p.test.items(): verdict = 'every byte right' if wrong == 0 else f'**{wrong} of {(64 << 20) // 4096} 4 KiB blocks WRONG**' print(f' copy check {by_cudev[s].label} -> {by_cudev[d].label}: 64 MiB, {verdict}, {gbs:.2f} GB/s') bad = isinstance(p.test, dict) and any(w for w, _ in p.test.values()) if bad: p.route = 'ram' route = { 'p2p': 'CUDA P2P (stock NCCL through VRAM)', 'p2p-580': 'CUDA P2P on NVIDIA\'s driver 580 (two cards of one older generation)', 'drm': 'DRMShare + the NCCL fork, card to card' + ( ' (the fork will time both directions and most likely read across: both cards on CPU lanes;' ' in a job with a card behind a chipset every pair writes)' if p.link == 'cpu' else ' (write mode: a card is behind a chipset or switch)'), 'ram': 'plain NCCL through system RAM' + ( ': the data did not arrive, so neither P2P nor DRMShare between these two' if bad else ': two cards behind one chipset cannot reach each other, with P2P or with DRMShare' if p.link == 'same-chipset' else ': mining-board ASMedia switches carried no peer traffic'), }[p.route] print(f' -> {route}') if p.route == 'drm' and old and a.arch not in OLD and b.arch not in OLD and ( a.arch == b.arch or {a.arch, b.arch} == {'Turing', 'Ampere'}) and a.geforce and b.geforce: print(f' (alone in a machine these two could have CUDA P2P with the P2P guide\'s patched driver; ' f'the {"/".join(old)} card here needs NVIDIA\'s closed driver)') # ------------------------------------------------------------------------------------------------ the answer routes = {p.route for p in pairs} known = [g for g in gpus if g.listed] small = [g for g in known if g.bar1 < g.vram] turing = [g for g in gpus if g.arch == 'Turing' and g.geforce] iommu_ok = all(g.iommu in ('passthrough', 'off') for g in gpus) iommu_line = (f'{mark(iommu_ok)} the IOMMU off or in passthrough mode (iommu=pt' + (', with intel_iommu=on' if intel else '') + ')' + ('' if iommu_ok else ': ' + ', '.join(f'{g.label} {g.iommu}' for g in gpus if g.iommu not in ('passthrough', 'off')))) if not iommu_ok: opt = 'intel_iommu=on iommu=pt' if intel else 'iommu=pt' cmds.append(('the IOMMU in passthrough mode (the P2P guide, docs/procedure.md step 4)', [f'sudo sed -i \'s/^GRUB_CMDLINE_LINUX_DEFAULT="\\(.*\\)"/GRUB_CMDLINE_LINUX_DEFAULT="\\1 {opt}"/\' ' '/etc/default/grub', 'sudo update-grub && sudo reboot'])) bar_cmd = ('a BAR1 window as large as each card\'s memory', [f'# geforce-bar1-resize at every boot: {P2P_GUIDE}/blob/main/docs/procedure.md step 4b, or ' f'{DRMSHARE}/blob/main/docs/machine-setup.md step 3' + ('; the RTX 20 cards\' USB-C functions out first (scripts/gpu-usbc-off)' if turing else '')]) p2p_pairs = [p for p in pairs if p.route in ('p2p', 'p2p-580')] all_p2p_now = all(p.cuda for p in p2p_pairs) if p2p_pairs else False print('\nYour setup') if box in ('p2p-mix', 'p2p-one'): title = 'Full CUDA P2P across two generations' if box == 'p2p-mix' else 'Full CUDA P2P' print(f' {title}: CUDA reaches the other card\'s memory directly; every CUDA program (NCCL, PyTorch, ' f'vLLM, llama.cpp) uses it.') if all_p2p_now: print(' CUDA offers P2P between every pair already' + (' and the copy check passed.' if args.test and all(isinstance(p.test, dict) for p in p2p_pairs) else '. Run with --test to check that the data arrives.')) arch = next(iter(gens)) if box == 'p2p-one' and arch in ('Pascal', 'Volta'): print(f' {mark(loaded and not open_modules and branch == 580)} NVIDIA\'s own driver 580 (closed ' f'modules): nothing to patch, it does P2P for {arch} cards') print(' ' + iommu_line) print(f' Guide: {P2P_GUIDE}/blob/main/docs/pascal-and-volta.md') elif box == 'p2p-one' and arch == 'Maxwell': print(' Two Maxwell cards: NVIDIA\'s closed driver; P2P between them was not tested by these projects. ' 'Run with --test.') else: print(f' {mark(not small)} unlock BAR1 (each card\'s window at least as large as its memory): ' + ('every card' if not small else ', '.join(f'{g.label} has {mib(g.bar1)}' for g in small)) + f' ({P2P_GUIDE}/blob/main/docs/procedure.md, step 4b)') if small: cmds.append(bar_cmd) if turing: usb = [g for g in turing if g.usbc] print(f' {mark(False if usb else (True if all(g.bar1 >= g.vram for g in turing) else None))} the ' f'USB-C hack for the RTX 20 card{"s" if len(turing) > 1 else ""} ({names(turing)}): remove the ' f'card\'s USB-C functions before the resize ({P2P_GUIDE}/blob/main/docs/turing.md)' + (f'; still present on {names(usb)}' if usb else '')) pro = not any(g.geforce for g in gpus) same = [p for p in pairs if p.a.arch == p.b.arch and p.route == 'p2p'] drv = all(p.cuda for p in same) if same and cuda else None if pro: print(f' {mark(drv)} NVIDIA\'s own driver often offers P2P on these cards already; if not, the P2P ' f'guide\'s patched driver ({P2P_GUIDE})') elif arch == 'Blackwell': print(f' {mark(drv)} NVIDIA\'s own driver (open modules) for RTX 50 P2P; 16 GB cards need static BAR1 ' f'({P2P_GUIDE}#which-path-is-yours)') else: base = loaded and open_modules and branch == 615 print(f' {mark(drv)} the P2P guide\'s patched driver, built on driver 615 with the open modules: ' f'{P2P_GUIDE}/blob/main/docs/procedure.md' + ('' if drv or base else f'; driver {driver or "none"} ({mods} modules) is loaded now')) if not drv and not base: cmds.append(('driver 615 with the open modules, the base of the P2P guide\'s patched driver ' '(docs/procedure.md step 3; then its steps 4-16)', ['sudo apt install -y nvidia-driver-615-open # not the 595-open Ubuntu recommends', 'sudo reboot'])) if box == 'p2p-mix': mixp = [p for p in pairs if p.a.arch != p.b.arch and p.route == 'p2p'] print(f' {mark(all(p.cuda for p in mixp) if mixp and cuda else None)} the shim: a patched copy of ' f'libcuda so CUDA pairs a Turing card with an Ampere one ({P2P_GUIDE}/blob/main/docs/' f'mixed-generations.md)') print(' ' + iommu_line) if arch in ('Ada', 'Hopper'): print(f' {arch}: see the P2P guide\'s table for these cards (RTX 40: P2P opt-in per card).') print(' then stock NCCL, through VRAM: PyTorch\'s and vLLM\'s own NCCL use P2P by themselves ' '(NCCL_DEBUG=INFO says "via P2P").' + (' On an Intel CPU set NCCL_P2P_LEVEL=PHB.' if intel else ' With three or more cards on an AMD CPU set NCCL_P2P_LEVEL=PHB ' '(one socket; SYS across sockets), or NCCL stays in host memory.' if len(gpus) >= 3 else '')) if len(gpus) > 1 and all(g.place == 'cpu' for g in gpus): print(' with every card on CPU lanes, also export NCCL_P2P_READ_ENABLE=1: each card reads from the other ' 'instead of writing into it (two RTX 3090s on an AMD X570: prompts and training about 6 % faster, ' 'large all-reduces +19 %)' + ('; measured on AMD only, so compare with and without on this Intel ' 'board' if intel else '')) elif len(gpus) > 1: print(' leave NCCL_P2P_READ_ENABLE off on this machine: with a card behind a chipset or switch in the job ' 'it made large all-reduces 43 % slower (it applies to every pair)') else: why = ('a Volta, Pascal or Maxwell card next to a newer one: those need NVIDIA\'s closed driver, which the ' 'P2P patch cannot change' if old else 'two generations other than RTX 20 + RTX 30: CUDA refuses peer access between them') print(f' CUDA P2P is impossible for these cards ({why}).') if 'drm' in routes: print(' DRMShare + the NCCL fork: each card copies straight into (or reads straight from) the other\'s ' 'memory through a dma-buf; NCCL programs use it through the fork, a drop-in libnccl.so.2.') print(f' {mark(not small and not unlisted)} unlock BAR1 where the card allows it (each card\'s window at ' f'least as large as its memory): ' + ('every card' if not small and not unlisted else ', '.join( [f'{g.label} has {mib(g.bar1)}' for g in small] + [f'{g.label} unknown (not running)' for g in unlisted])) + f' ({DRMSHARE}/blob/main/docs/machine-setup.md, step 3; the fork also ran with 256 MiB windows)') if small: cmds.append(bar_cmd) usb = [g for g in turing if g.usbc] if [g for g in turing if not g.listed or g.bar1 < g.vram]: print(f' {mark(False if usb else None)} before that, the USB-C hack for the RTX 20 card' f'{"s" if len(turing) > 1 else ""} ({names(turing)}): DRMShare\'s scripts/gpu-usbc-off removes ' f'the USB-C functions that block the resize' + (f'; still present on {names(usb)}' if usb else '')) print(' ' + iommu_line + f' ({DRMSHARE}/blob/main/docs/machine-setup.md, step 2)') page = 'volta-dmabuf.md' if old else 'dmabuf-615.md' branch_ok = (loaded and not open_modules and branch == 580) if old else (branch in (580, 595, 615)) print(f' {mark(drmshare)} DRMShare: one nvidia-drm option, peer_vidmem_dmabuf=1, on NVIDIA\'s ' + ('closed driver 580 (Volta, Pascal and Maxwell need it)' if old else 'driver 580, 595 or 615') + f' ({DRMSHARE}/blob/main/docs/{page})' + ('' if branch_ok else f'; driver {driver or "none"} ({mods} modules) is loaded now')) print(f' {"[done]" if boot else "[optional]"} DRMShare\'s nvidia-drm at every boot: its scripts/drmshare-boot ' f'builds it, installs it next to the stock one and keeps it in step with kernel and driver updates ' f'({DRMSHARE}/blob/main/docs/boot-install.md)' + ('; installed but not loaded yet: reboot' if boot and not drmshare else '; installed, but not for this kernel: sudo drmshare-boot check' if boot is False else '')) noaccess = [g for g in gpus if g.render is False] render_ok = False if noaccess else (True if all(g.render for g in known) else None) root = os.geteuid() == 0 print(f' {mark(None if root else render_ok)} every process can open its card\'s render node ' f'(/dev/dri/renderD*): the user in the render group' + (f'; this user cannot open {names(noaccess)}\'s' if noaccess and not root else '') + ('; run this as the user who runs the programs to check' if root else '')) if noaccess and not root: cmds.append(('the render group (the NCCL fork needs each process to open its card\'s render node)', ['sudo usermod -aG render $USER # then log out and in again'])) fork = find_fork() print(f' {mark(bool(fork))} the NCCL fork, built for your cards ({DRMSHARE}/blob/main/docs/nccl.md, ' f'step 1)' + (f': {fork} (from LD_PRELOAD / LD_LIBRARY_PATH)' if fork else '') + ', then:') print(' export NCCL_DRMSHARE_TRANSPORT=1 NCCL_DRMSHARE_SPLIT_BYTES=4194304') print(' export LD_PRELOAD=/build/lib/libnccl.so.2 # PyTorch and vLLM bring their own NCCL') print(' export VLLM_NCCL_SO_PATH=$LD_PRELOAD # vLLM only') print(' The fork checks every pair before using it (a pair that fails goes through system RAM) and picks ' 'read or write mode by itself (read mode only when every pair of the job\'s cards reads faster); ' 'NCCL_DEBUG=INFO says "via DRM" and what it chose.') for p in pairs: if p.route == 'p2p-580': print(f' {p.a.label} + {p.b.label} ({p.a.arch}): CUDA P2P on NVIDIA\'s 580 with the IOMMU in ' f'passthrough mode; NCCL takes P2P there by itself, the fork\'s transport for the rest.') if routes == {'ram'}: print(' Plain NCCL through system RAM: no faster route between these cards.') for p in pairs: if p.route == 'ram' and len(routes) > 1: print(f' {p.a.label} + {p.b.label}: through system RAM (above).') # ------------------------------------------------------------------------------------------------ notes notes = [] if 'Volta' in gens and 'drm' in routes: notes.append('Training with a Tesla V100 (PyTorch DDP) through the fork: set CUDA_DEVICE_MAX_CONNECTIONS=1.') if 'Volta' in gens: notes.append('vLLM on a V100: its own builds have no Volta code; it runs through volta-forever ' '(github.com/nbald/volta-forever)' + (', one process per card beside a newer card (volta-forever v0.1.6 breaks cuBLAS on the newer ' 'one): tools/vllm-volta (next to this script) starts them, for vllm serve or your own program.' if len(gens) > 1 else ': vf vllm serve ...')) if [a for a in gens if a in ('Pascal', 'Maxwell')]: notes.append('No vLLM on Pascal or Maxwell cards (not even through volta-forever, which is for Volta): llama.cpp.') if {'Turing', 'Ampere'} <= gens: notes.append('vLLM on an RTX 20 + RTX 30 pair: --attention-backend TRITON_ATTN --dtype float16 (FlashAttention ' 'needs Ampere; Turing has no bf16).') chip = [g for g in gpus if g.place == 'chipset'] if len(chip) == 1: notes.append(f'{chip[0].label} is behind the chipset: fine on its own, but a second card behind the same ' f'chipset could not reach it (with P2P or with DRMShare): put more cards on CPU lanes.') if any(g.bar1 and g.bar1 < 256 << 20 for g in gpus): notes.append('A BAR1 window below 256 MiB: check Above 4G Decoding in the BIOS.') if notes: print('\nNotes') for n in notes: print(f' - {n}') print_cmds(cmds, ubuntu) print(f'\nThe same questions as a picture: {DRMSHARE}#which-setup-for-your-cards. Something wrong with DRMShare? ' f'{DRMSHARE}/issues, and plain NCCL through system RAM meanwhile: slower, never wrong.') return 1 if any(isinstance(p.test, dict) and any(w for w, _ in p.test.values()) for p in pairs) else 0 def print_cmds(cmds, ubuntu): if not cmds: return print('\nCommands for what is left' + (' (Ubuntu; run them yourself, one at a time)' if ubuntu else ' (Ubuntu\'s package names: use your distribution\'s)')) seen = set() for title, lines in cmds: if title in seen: continue seen.add(title) print(f' # {title}') for line in lines: print(f' {line}') if __name__ == '__main__': sys.exit(main())