Как установить torch на ubuntu

Обновлено: 06.07.2024

Перепечатано: руководство по установке и настройке Torch7 в Ubuntu объяснено подробно (Начало работы с torch)

Основная цель этой серии учебных пособий по Torch7 - представить введение в Torch. Сегодня я сначала поделюсь установкой Torch7. (Установите torch7 в Ubuntu 14.04)

Почему стоит выбрать Факел

Цель Torch - добиться максимальной гибкости и скорости при создании научных алгоритмов, и этот процесс очень прост. Torch имеет большую пакетную экосистему, управляемую сообществом, которая включает в себя машинное обучение, компьютерное зрение, обработку сигналов, параллельную обработку, изображения, видео, аудио и сетевое взаимодействие, и основана на сообществе Lua.

В основе Torch лежат популярные нейронные сети и библиотеки оптимизации, которые просты в использовании и обладают наибольшей гибкостью при реализации сложных топологий нейронных сетей. Вы можете создавать произвольные графы нейронных сетей и эффективно распараллеливать их на процессорах и графических процессорах.

Перед установкой сначала убедитесь, что вы устанавливаете git tool под Ubuntu, открываете терминал через Ctrl + Alt + T, вводите git под терминалом, добавляете вывод терминала

Torch7 Ubuntu (torch )

Это означает, что git не установлен в вашей системе. Введите sudo apt install git в терминал для установки, как показано ниже.

Torch7 Ubuntu (torch )

После подтверждения успешной установки инструмента git вы можете начать установку Torch7!

Первый шаг:

/ torch --recursive, как показано ниже.

Torch7 Ubuntu (torch )

Torch7 Ubuntu (torch )

Второй шаг:

Поскольку зависимый пакет загружается по умолчанию в файл факела по текущему пути, введите папку факела, откройте и выполните команду в install-deps (выполнение этой команды может занять много времени, не беспокойтесь) Код выглядит следующим образом:

Torch7 Ubuntu (torch )

Третий шаг:

Запустите файл install.sh, как показано ниже.

Torch7 Ubuntu (torch )

Torch7 Ubuntu (torch )

Терминальная подсказка:

Do you want to automatically prepend the Torch install locationto PATH and LD_LIBRARY_PATH in your /home/guodongwei/.bashrc? (yes/no)

Четвертый шаг:

Добавьте путь к переменной PATH вручную:

Torch7 Ubuntu (torch )

Torch7 Ubuntu (torch )

Шаг 5:

Проверьте, если установка прошла успешно. Введите в терминал команду th.Если появится следующий рисунок, установка прошла успешно.

Torch7 Ubuntu (torch )

На этом этапе, даже если Torch7 успешно установлен, вы можете использовать его для выполнения своих собственных задач машинного обучения. Запись Torch7de будет проанализирована более подробно далее.

Интеллектуальная рекомендация


Краткое описание общих функций MPI

содержание 1, основная функция MPI 2, точка-точка функция связи 3, коллективная функция связи 1, основная функция MPI MPI_Init(&argc, &argv) Информировать системы MPI для выполнения всех необх.

Примечание 9: EL выражение


JVM память

концепция Виртуальная машина JVM управляет собственной памятью, которая разделяет память во многие блоки, наиболее распространенной для памяти стека и памяти кучи. 1 структура виртуальной машины JVM H.

Проблема сетевого запроса на Android 9.0

вЗапустите Android 9 (API Уровень 28) или вышеНа устройстве операционной системы Android, чтобы обеспечить безопасность пользовательских данных и устройств, использование по умолчанию для зашифрованно.


Учебная запись по Webpack (3) В статье рассказывается о создании webpack4.0.

предисловие Для изучения веб-пакета автор также предпринял много обходных путей. Есть много вещей, которые я хочу знать, но я не могу их найти. Автор поможет вам быстро начать работу. Цель этой статьи.

Select preferences and run the command to install PyTorch locally, or get started quickly with one of the supported cloud platforms.

Start Locally

Select your preferences and run the install command. Stable represents the most currently tested and supported version of PyTorch. This should be suitable for many users. Preview is available if you want the latest, not fully tested and supported, 1.11 builds that are generated nightly. Please ensure that you have met the prerequisites below (e.g., numpy), depending on your package manager. Anaconda is our recommended package manager since it installs all dependencies. You can also install previous versions of PyTorch. Note that LibTorch is only available for C++.

Additional support or warranty for some PyTorch Stable and LTS binaries are available through the PyTorch Enterprise Support Program.

PyTorch can be installed and used on macOS. Depending on your system and compute requirements, your experience with PyTorch on a Mac may vary in terms of processing time. It is recommended, but not required, that your Mac have an NVIDIA GPU in order to harness the full power of PyTorch’s CUDA support.

Currently, CUDA support on macOS is only available by building PyTorch from source

Prerequisites

macOS Version

PyTorch is supported on macOS 10.10 (Yosemite) or above.

Python

It is recommended that you use Python 3.5 or greater, which can be installed either through the Anaconda package manager (see below), Homebrew, or the Python website.

Package Manager

To install the PyTorch binaries, you will need to use one of two supported package managers: Anaconda or pip. Anaconda is the recommended package manager as it will provide you all of the PyTorch dependencies in one, sandboxed install, including Python.

Anaconda

To install Anaconda, you can download graphical installer or use the command-line installer. If you use the command-line installer, you can right-click on the installer link, select Copy Link Address , and then use the following commands:

If you installed Python via Homebrew or the Python website, pip was installed with it. If you installed Python 3.x, then you will be using the command pip3 .

Tip: If you want to use just the command pip , instead of pip3 , you can symlink pip to the pip3 binary.

Installation

Anaconda

To install PyTorch via Anaconda, use the following conda command:

To install PyTorch via pip, use one of the following two commands, depending on your Python version:

Verification

To ensure that PyTorch was installed correctly, we can verify the installation by running sample PyTorch code. Here we will construct a randomly initialized tensor.

The output should be something similar to:

Building from source

For the majority of PyTorch users, installing from a pre-built binary via a package manager will provide the best experience. However, there are times when you may want to install the bleeding edge PyTorch code, whether for testing or actual development on the PyTorch core. To install the latest PyTorch code, you will need to build PyTorch from source.

You will also need to build from source if you want CUDA support.

Prerequisites

You can verify the installation as described above.

PyTorch can be installed and used on various Linux distributions. Depending on your system and compute requirements, your experience with PyTorch on Linux may vary in terms of processing time. It is recommended, but not required, that your Linux system has an NVIDIA GPU in order to harness the full power of PyTorch’s CUDA support..

Prerequisites

Supported Linux Distributions

PyTorch is supported on Linux distributions that use glibc >= v2.17, which include the following:

    , minimum version 2012-07-15 , minimum version 7.3-1611 , minimum version 8.0 , minimum version 24 , minimum version 14 , minimum version 42.1 , minimum version 2014.7 , minimum version 14.2 , minimum version 13.04

The install instructions here will generally apply to all supported Linux distributions. An example difference is that your distribution may support yum instead of apt . The specific examples shown were run on an Ubuntu 18.04 machine.

Python

Python 3.6 or greater is generally installed by default on any of our supported Linux distributions, which meets our recommendation.

Tip: By default, you will have to use the command python3 to run Python. If you want to use just the command python , instead of python3 , you can symlink python to the python3 binary.

However, if you want to install another version, there are multiple ways:

If you decide to use APT, you can run the following command to install it:

It is recommended that you use Python 3.6, 3.7 or 3.8, which can be installed via any of the mechanisms above .

If you use Anaconda to install PyTorch, it will install a sandboxed version of Python that will be used for running PyTorch applications.

Package Manager

To install the PyTorch binaries, you will need to use one of two supported package managers: Anaconda or pip. Anaconda is the recommended package manager as it will provide you all of the PyTorch dependencies in one, sandboxed install, including Python.

Anaconda

To install Anaconda, you will use the command-line installer. Right-click on the 64-bit installer link, select Copy Link Location , and then use the following commands:

You may have to open a new terminal or re-source your

/.bashrc to get access to the conda command.

While Python 3.x is installed by default on Linux, pip is not installed by default.

Tip: If you want to use just the command pip , instead of pip3 , you can symlink pip to the pip3 binary.

Installation

Anaconda

No CUDA

To install PyTorch via Anaconda, and do not have a CUDA-capable system or do not require CUDA, in the above selector, choose OS: Linux, Package: Conda and CUDA: None. Then, run the command that is presented to you.

With CUDA

To install PyTorch via Anaconda, and you do have a CUDA-capable system, in the above selector, choose OS: Linux, Package: Conda and the CUDA version suited to your machine. Often, the latest CUDA version is better. Then, run the command that is presented to you.

No CUDA

To install PyTorch via pip, and do not have a CUDA-capable system or do not require CUDA, in the above selector, choose OS: Linux, Package: Pip and CUDA: None. Then, run the command that is presented to you.

With CUDA

To install PyTorch via pip, and do have a CUDA-capable system, in the above selector, choose OS: Linux, Package: Pip and the CUDA version suited to your machine. Often, the latest CUDA version is better. Then, run the command that is presented to you.

Verification

To ensure that PyTorch was installed correctly, we can verify the installation by running sample PyTorch code. Here we will construct a randomly initialized tensor.

The output should be something similar to:

Additionally, to check if your GPU driver and CUDA is enabled and accessible by PyTorch, run the following commands to return whether or not the CUDA driver is enabled:

Building from source

For the majority of PyTorch users, installing from a pre-built binary via a package manager will provide the best experience. However, there are times when you may want to install the bleeding edge PyTorch code, whether for testing or actual development on the PyTorch core. To install the latest PyTorch code, you will need to build PyTorch from source.

Prerequisites

You can verify the installation as described above.

PyTorch can be installed and used on various Windows distributions. Depending on your system and compute requirements, your experience with PyTorch on Windows may vary in terms of processing time. It is recommended, but not required, that your Windows system has an NVIDIA GPU in order to harness the full power of PyTorch’s CUDA support.

Prerequisites

Supported Windows Distributions

PyTorch is supported on the following Windows distributions:

    7 and greater; Windows 10 or greater recommended. r2 and greater

The install instructions here will generally apply to all supported Windows distributions. The specific examples shown will be run on a Windows 10 Enterprise machine

Python

Currently, PyTorch on Windows only supports Python 3.x; Python 2.x is not supported.

As it is not installed by default on Windows, there are multiple ways to install Python:

If you use Anaconda to install PyTorch, it will install a sandboxed version of Python that will be used for running PyTorch applications.

If you decide to use Chocolatey, and haven’t installed Chocolatey yet, ensure that you are running your command prompt as an administrator.

For a Chocolatey-based install, run the following command in an administrative command prompt:

Package Manager

To install the PyTorch binaries, you will need to use at least one of two supported package managers: Anaconda and pip. Anaconda is the recommended package manager as it will provide you all of the PyTorch dependencies in one, sandboxed install, including Python and pip.

Anaconda

To install Anaconda, you will use the 64-bit graphical installer for PyTorch 3.x. Click on the installer link and select Run . Anaconda will download and the installer prompt will be presented to you. The default options are generally sane.

If you installed Python by any of the recommended ways above, pip will have already been installed for you.

Installation

Anaconda

To install PyTorch with Anaconda, you will need to open an Anaconda prompt via Start | Anaconda3 | Anaconda Prompt .

No CUDA

To install PyTorch via Anaconda, and do not have a CUDA-capable system or do not require CUDA, in the above selector, choose OS: Windows, Package: Conda and CUDA: None. Then, run the command that is presented to you.

With CUDA

To install PyTorch via Anaconda, and you do have a CUDA-capable system, in the above selector, choose OS: Windows, Package: Conda and the CUDA version suited to your machine. Often, the latest CUDA version is better. Then, run the command that is presented to you.

No CUDA

To install PyTorch via pip, and do not have a CUDA-capable system or do not require CUDA, in the above selector, choose OS: Windows, Package: Pip and CUDA: None. Then, run the command that is presented to you.

With CUDA

To install PyTorch via pip, and do have a CUDA-capable system, in the above selector, choose OS: Windows, Package: Pip and the CUDA version suited to your machine. Often, the latest CUDA version is better. Then, run the command that is presented to you.

Verification

To ensure that PyTorch was installed correctly, we can verify the installation by running sample PyTorch code. Here we will construct a randomly initialized tensor.

From the command line, type:

then enter the following code:

The output should be something similar to:

Additionally, to check if your GPU driver and CUDA is enabled and accessible by PyTorch, run the following commands to return whether or not the CUDA driver is enabled:

Building from source

For the majority of PyTorch users, installing from a pre-built binary via a package manager will provide the best experience. However, there are times when you may want to install the bleeding edge PyTorch code, whether for testing or actual development on the PyTorch core. To install the latest PyTorch code, you will need to build PyTorch from source.

100% успешная установка torch под ubuntu и одновременная настройка cuda и cudnn (неудачно, вы станете доброжелателем)

Установить torch7

Используйте собственный скрипт torch напрямую

Проблемы, которые могут здесь возникнуть, находятся вЯма одинв.
Если отсутствуют зависимости для nn: moses> = 1., Обратитесь к дополнительному разделу блога
Затем он предложит добавить torch в bashrc, появится запрос «. (yes | no)», просто введите yes.
Для страховки вы можете посмотреть файл bashrc

Проверьте, есть ли что-то подобное в конце документа

Выше указан путь установки вашего фонарика.
Затем обновите переменные среды.


Будет появляться

Теперь базовый фонарик установлен! ! ! Это так просто. Но вы также можете установить cuda, что на самом деле очень просто.

Загрузите и настройте нейронный стиль (используется только для тестирования программы сравнения процессора и графического процессора, действительно можно опустить . )

Установить другие зависимые библиотеки

Загрузите код нейронного стиля

Установить модель VGG

Значит, если этого шага не достичь, это будет довольно сложно.

Установить cuda

Если вы устанавливали его раньше, вам не нужно устанавливать его заново. Фактически, это среда. Установка по умолчанию аналогична /usr/local/cuda-8.0. Во время установки будет создана программная ссылка, похожая на ярлык Windows.
Скачайте соответствующую версию прямо с официального сайтаcuda . Затем дважды щелкните файл deb непосредственно для установки. Не думайте, что после установки deb будет установлена ​​cuda - на самом деле есть дополнительные библиотеки, которые необходимо установить. Это необходимо сделать через командную строку.

Cuda, установленный с помощью apt-get выше, установит соответствующую библиотеку в соответствии с версией вашего deb cuda. Например, если вы используете deb cuda8.0, тогда будет куча библиотек с такими именами файлов, как cuda8.0-.

Наконец, попробуйте еще раз, чтобы увидеть, установлен ли cuda


Если отображается информация о конфигурации вашей видеокарты, это нормально.

Установите поддержку cuda для резака

Только что установленный cuda универсален и может использоваться всеми программными фреймворками. Но если вы позволите torch использовать cuda, вам потребуется установить две библиотеки cutorch и cunn. Cutorch позволяет torch использовать GPU, а cunn специально предназначен для нейронных сетей, позволяя нейронным сетям работать на GPU. Фактически, torch по-прежнему очень просто установить соответствующие другие библиотеки, всего одна команда.



Здесь должно быть правильно в это время.

Установить cudnn

По сути, cudnn - это некоторая библиотека ссылок, как ее установить. Поместите файл заголовка cudnn и соответствующую библиотеку ссылок в соответствующую позицию пути cuda. Очевидно, что файл заголовка помещается в папку include, а библиотека ссылок помещается в папку lib64. Так что есть
Сначала установите cudnn5.1, а затем непосредственно luarocks install cudnn, Теперь по умолчанию cudnn5.x. Если вы хотите установить cudnn6.0, см. Прилагаемую статью.

Наконец, установите поддержку cudnn для torch.

Успех почти на 100%, если это так, может показатьсяЯма два。

(Примечание: сбой может быть из-за установки определенного порога ошибки. Сейчас они не обновляются, поэтому вы можете использовать его, как будто нет проблем, в противном случае рекомендуется перенести, кстати, он использовался почти 2 года , Кажется, я не обнаружил никаких проблем ни с одной функцией.)


Есть только одна ошибка в VolumetricFullConvolution_pair_test Но мне не следует использовать эту свертку, так что это не большая проблема.
Страшно то, что когда я снова протестировал его спустя долгое время, он оказался странным и правильным. . Так что нестабильно, убери факел и береги его.

LD_LIBRARY_PATH - это переменная среды, которая в основном используется для указания путей, отличных от пути по умолчанию, при поиске разделяемых библиотек (динамически подключаемых библиотек). Только сейчас
"Libcudnn *" копируется в /usr/local/cuda-8.0/lib64/, поэтому ему необходимо
метод первый:
1. sudo gedit /etc/ld.so.conf.d/cudnn.conf предназначен для создания нового файла conf. Любое имя
2. Добавьте прямо сейчас путь /usr/local/cuda-8.0/lib64/
3. Во всяком случае, я также добавил /usr/local/cuda-8.0/include/, это, наверное, не так.
4. После сохранения выполните sudo ldconfig, чтобы обновить кеш. (Может быть проблема в том, что libcudnn.so.5 не является символической ссылкой, но это не имеет значения! Чтобы решить эту проблему, вы можете увидетьХа-ха)
Метод второй (он простой):
непосредственный

Затем добавьте в конце


Получилось! ! ! !

Я обнаружил, что при использовании cudnn становится 50 и 50 на один дисплей, что быстрее. Только сейчас, но cuda хранилища отображается только один за другим. Перестань говорить, подожди немного.

Версия должна соответствовать! ! Версии cuda и cudnn должны соответствовать друг другу! ! ! !

если прямо в факеле

Это пойдет не так. Сделать это:

Некоторая конкретная ссылка на использование
DeepMind

Запишите решения различных проблем после n раз установки резака.

Некоторые другие библиотеки, которые можно использовать

Следующие три - это библиотеки, используемые для загрузки модели кафе, библиотеки для автоматического создания и библиотеки для пользовательских параметров инициализации.

Перед установкой установите loadcaffe

Среди них loadcaffe может быть неудачным из-за плохого характера. Теперь проверьте библиотеку автономной установки torch ниже.
Также есть дисплей библиотеки, который может захотеть отобразить потери или изображения в браузере.

Вам также может потребоваться преобразовать тензор факела в массив numpy, чтобы работать с библиотекой Python. На этот раз тебе нужно

Стоит отметить, что, поскольку таблица Torch начинается с 1, а python - с 0. Он автоматически конвертируется, поэтому не о чем беспокоиться.

Напоследок пожаловаться на это, он не обновлялся много лет. .

Посмотри другие TF. .

Наконец, в конце еще раз подчеркните! Закройте Torch и сохраните его. .

Установить библиотеку фонарика в автономном режиме

Мы знаем, что установка библиотеки torch по-прежнему очень проста. непосредственный luarocks install xxx . Но иногда не удается установить некоторые библиотеки. Такие как luarocks install loadcaffe
В это время прямо найдите исходный код github, скачайте и установите офлайн

Решение ошибки установки Cutorch

Раньше не было ничего плохого, но теперь они обновляют THCTensor, они пойдут не так.
The problem is the latest commit these guys have pushed into master in THCTensor file.
I made a local copy of the repo. Took out the problem some code and installed
it using luarocks. Worked for me
Эта проблема возникает из-за того, что:Стабильные версии различных пакетов, установленных дистрибутивом, будут отставать от каждого пакета на несколько месяцев. Если вы хотите обновить пакет отдельно, вы можете использовать следующие
Решение:Сначала установите фонарик с луароками, Это обновит пакет дистрибутива torch7.

cudnn6.0

Сначала конечно установите что-нибудь вроде cudnn-8.0-linux-x64-v6.0.tgz ,затем

Вдобавок кажется, что torch.cudnn не оптимизирован? ? В конце концов, это не главная ветвь, главное, что после ее установки скорость работы моей программы не улучшится. Говорят, что скорость увеличивается в 2 раза. . .

выполненный ./install.sh Моисей> = 1. Ошибка

Missing dependencies for nn:moses >= 1., Иногда выполняют ./install.sh Когда возникает эта проблема.
Одно предложение:Плохая скорость интернета! Низкая скорость интернета! Вы можете сказать, что у вас неплохая скорость интернета, эта проблема может возникнуть только в том случае, если есть проблема со скоростью интернета.
Решение

Это бесполезно! Вы должны скачать его отдельно
Moses, А затем обратитесь к упомянутому ранее блогуУстановить библиотеку фонарика в автономном режимеПосле установки Moses вы сможете правильно установить фонарик.

проблема пакета зависимостей g ++


Эта проблема, вероятно, вызвана изменением источника. Просто используйте официальный источник Ubuntu 14.04 напрямую и используйте соответствующий источник для других версий.

Измените /etc/apt/source.list, добавьте следующий источник в конце, затем обновите

Почему иногда luarocks явно устанавливает пакет, но все равно появляется ошибка, похожая на «Отсутствуют зависимости для nn: moses> = 1»? ?


Раньше я прямо говорил, что пакет дистрибутива был помещен в папку torch в домашнем каталоге, а затем установлен. Обычно эта установка - это все пакеты, установленные luarocks, по умолчанию/home/xxx/torch/installвнутри. Однако странно то, что иногда, когда пакет mose установлен в автономном режиме, он появляется

Это показывает, что luarocks установлен в / usr / libНиже. Значит нам нужно указать путь установки mose! в противном случае./installИз/home/xxx/torch/installНайдите установленный пакет.
решение:

среди них–treeЗадает путь установки moses.

Возможные решения для ошибки сегментации

Если ваша видеокарта ** Jetson Tegra или Jeston TK1, или если вы используете 32-разрядную версию Linux (супер не рекомендуется), при запуске программы появляется ошибка сегментации (дамп ядра).
Метод:Используйте Lua5.2 вместо LuaJIT по умолчанию. Однако, если размер модели превышает 2 ГБ, произойдет ошибка

How to Install PyTorch on Ubuntu 20.04 pip conda

Here you will learn how to install PyTorch on Ubuntu 20.04 using either pip or conda . Specifically, you will learn how to install Python 3 and Python package manager, either pip or conda (Anaconda or Miniconda). You will also learn how to install CUDA through apt-get in the official repository of Ubuntu 20.04. Last but not least, you will be able install both the PyTorch CPU only or GPU enabled versions, even though the GPU method is strongly recommended.

PyTorch & Ubuntu 20.04

PyTorch is a popular deep learning framework written in Python. Open-sourced by Facebook, PyTorch has been used by researchers and developers for computer vision ( torchvision ), NLP (natural language processing, torchtext ), and audio tasks.

PyTorch Tensor illustration

PyTorch Tensor Illustration (Source)

Under the hood, PyTorch is a Tensor library ( torch ), similar to NumPy, and mainly provides an automatic differentiation library ( torch.autograd ) and a neural networks library ( torch.nn ). It also contains 2 components for data processing: torch.multiprocessing enables memory sharing between torch Tensors between procisesses, and torch.utils provides DataLoder class. Lastly, PyTorch also contains a component ( torch.jit ) to serialize and optimize models from your PyTorch code.

Code-named Focal Fossa, Ubuntu 20.04 is the most recent release of Ubuntu LTS. It is out in April 2020 and supported for 5 years until April 2025 (standard support).

One of the most exciting feature for PyTorch users is that Ubuntu 20.04 now includes the proprietary NVIDIA Linux drivers. So when you install 20.04 (or upgrade from an older Ubuntu version, such as Ubuntu 18.04), the NVIDIA Linux driver will be automatically installed.

There are 2 major Python package managers. The first is the official one called Pip, and another one is Conda (Anaconda or Miniconda). When in doubt or for beginners, the official pip is recommended.

Install Python 3 and pip for PyTorch

Pip is the native Python package manager. We will use it to install PyTorch and torchvision . To install pip3 , run the following command. Because pip3 depends on Python 3, python3 will also be installed if it is not in your Ubuntu 20.04 system.

Install pip 3 for PyTorch

Here is the full output for the pip3 installation:

[Alternative] Install Conda (Anoconda/Miniconda) for PyTorch

[Alternative] Install PyTorch with CPU support only

You can skip the remaining steps and run the following 2 commands to install PyTorch and have it only use your CPU if

However, if you only use CPU, your deep learning models will run slow. Having a NVIDIA graphics card and installing PyTorch with GPU support will make your model training significantly faster.

To use pip to install PyTorch without GPU support, run

Use pip to install PyTorch without GPU support

To use conda (Anaconda/Miniconda) to install PyTorch without GPU support, run

Use conda Anaconda or Miniconda to install PyTorch with only CPU support

Install Nvidia directly from Ubuntu 20.04 in the Additional Drivers tab

PyTorch utilize CUDA for fast processing, especially autograding. As Ubuntu 20.04 has NVIDIA Linux driver built-in, we can directly install CUDA from the official repository. The current version is CUDA 10.1. To install CUDA for PyTorch on your Ubuntu 20.04 machine, run

It will download around 1.5 GB files for all the packages, and will take 3.8 GB additional disk space, so it will take a while to complete CUDA installation depending on your Internet speed. The following are a few screenshots and the complete output.

All the packages that nvidia-cuda-toolkit depends on:

Installing cuda on Ubuntu 20.04 sudo apt install nvidia cuda toolkit

Press enter to continue installation:

Before installing cuda on Ubuntu 20.04 sudo apt install nvidia cuda toolkit

For your reference, here are the complete output before continuing the installation. Note that because nvidia-cuda-doc is also installed, you can view the CUDA documentation by opening /usr/share/doc/nvidia-cuda-toolkit/html/index.html in a browser.

Verify CUDA is installed

After the Progress is 100%, you can run nvcc -V to check if CUDA 10.1 is successfully installed on Ubuntu 20.04

You will see the output in the following screenshot.

Checking if CUDA 10.1 is installed on Ubuntu 20.04 by nvcc V

I also copied the output text for your reference:

Install PyTorch with pip

To install it using pip , run the following with the pip3 command.

Installing PyTorch on Ubuntu 20.04 using pip3

It will take quite awhile to download around 700 MB pre-built wheel files for PyTorch and its dependencies. After the progress bar of downloading is complete, you will see the following output:

Finishing Installing PyTorch on Ubuntu 20.04 using pip3

Here is the complete output text:

Install PyTorch with conda

To install it using conda after you installed either Anaconda or Miniconda, run

Verify PyTorch Installation

Now PyTorch should be installed and have CUDA support. To double check, we will run 2 sample Python scripts. Run python3 on your Ubuntu 20.04 machine and copy & paste (or type) the code in this section.

Test PyTorch

In the following code, we create a randomly initialized tensor to test PyTorch.

You will see the following output printed. Yours will be similar as the ouput numbers are random.

Testing PyTorch installation on Ubuntu 20.04

Verify if CUDA is accessible in PyTorch

To test whether your GPU driver and CUDA are available and accessible by PyTorch, run the following Python code to determine whether or not the CUDA driver is enabled:

It should output true as seen below.

Testing if CUDA is available in PyTorch installation on Ubuntu 20.04

Congratulations! Now you have PyTorch with CUDA support installed on you Ubuntu 20.04 machine!

4 Steps to Install PyTorch on Ubuntu 20.04

Time Needed : 40 minutes

    Install Python package manager

Install pip 3 for PyTorch

Run this command to install pip3 and Python
sudo apt install python3-pip
(See the full article for conda method)

Install Nvidia directly from Ubuntu 20.04 in the Additional Drivers tab

Click Activities on the top left comer of your screen, search for “Additional Drivers”, then press enter. You will see the following window with the “Additional Drivers” tab active. Choose the entry with the biggest number and click apply to reboot your computer.

Installing cuda on Ubuntu 20.04 sudo apt install nvidia cuda toolkit

Here we will install CUDA from the official repo of Ubuntu 20.04:
sudo apt install nvidia-cuda-toolkit
(Verify by nvcc -V )

Читайте также: