Nvidia Optimus laptops include both a power-efficient Intel GPU and a Nvidia GPU. In this post I describe how to enable CUDA on such a laptop while keeping all Linux graphics on the Intel GPU. Thereby power can be saved during normal usage (as the Intel GPU is more efficient). Furthermore the GPU memory is completely free for the CUDA program (otherwise the X server would consume a non-neglectible amount of GPU memory).
Installing the Nvidia drivers
The drivers packaged by your distribution are set up in such a way that CUDA
will only work when running the X server on the Nvidia GPU. When switching the X
server to the Intel GPU using
prime-select CUDA will stop working.
Instead the driver needs to be installed manually. The most recent version of the driver can be found on Nvidia's ftp server (at the time of this writing 378.09).
To install use:
sudo ./NVIDIA-Linux-x86_64-378.09.run --dkms --no-opengl-files
--dkms registers the kernel module with DKMS so that it is rebuilt when you
upgrade your kernel.
--no-opengl-files keeps the X graphics configuration of your computer so that
you can continue to use the Intel GPU
The installer will likely complain that the open source
nouveau driver is
loaded in your system. Simply allow the installer to blacklist this driver.
Before you reboot your machine make sure to update your initramfs using
update-initramfs -u to make sure the
nouveau driver is indeed not loaded.
Then reboot your machine and start the installation process again as described
After installing the driver make sure to update your initramfs using
Enable the Nvidia devices
To enable the Nvidia devices root rights are necessary. Usually this is
performed by the X server. However, as we do not wish the X server to manage our
Nvidia device and as our CUDA programs are usually not run as root we need to
This tool is a setuid program and can therefore enable the Nvidia devices even when called from an unprivileged CUDA program.
nvidia-modprobe is automatically installed when installing the
This is described in more detail in the FAQ of the driver.
Afterwards CUDA can be used/installed as usual.
DKMS not working
When using a custom kernel that was compiled on a different machine with
fakeroot make-kpkg DKMS is often not working. This is due to a bug in
make-kpkg not creating properly portable
.deb files. It seems this bug is
not being fixed as
make-kpkg is obsolete.
.deb packages for the linux kereln can be created using
included in the kernels compilation infrastructure. There shouldn't be any
problems with dkms when installing the kernel from these
If this does not fix your problem it is likely that the Nvidia driver does not (yet) support your kernel version. At the time of this writing linux 4.9 is supported by the Nvidia driver 375.26 and higher.
This solution is inspired by a askubuntu.com question but instead uses
nvidia-modprobe to avoid having the X server manage the Nvidia card.