Cuda vs code python

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Using GPUs in VS Code with Nvidia CUDA Container

oceanumeric/cuda-container-vscode

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Using GPUs in VS Code with Nvidia CUDA Container

A docker container with GPUs

nvidia-smi Wed Dec 7 23:03:30 2022 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 470.141.03 Driver Version: 470.141.03 CUDA Version: 11.4 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | | | | MIG M. | |===============================+======================+======================| | 0 NVIDIA GeForce . On | 00000000:09:00.0 Off | N/A | | 0% 44C P8 29W / 350W | 19MiB / 24268MiB | 0% Default | | | | N/A | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: | | GPU GI CI PID Type Process name GPU Memory | | ID ID Usage | |=============================================================================| | 0 N/A N/A 1448 G /usr/lib/xorg/Xorg 9MiB | | 0 N/A N/A 1683 G /usr/bin/gnome-shell 8MiB | +-----------------------------------------------------------------------------+
nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2021 NVIDIA Corporation Built on Wed_Jun__2_19:15:15_PDT_2021 Cuda compilation tools, release 11.4, V11.4.48 Build cuda_11.4.r11.4/compiler.30033411_0

The version of Image has to be same with your CUDA version and architecture of your computer (amd64 for my case).

Mine is CUDA Version: 11.4 , therefore I need this image: 11.4.2-cudnn8-devel-ubuntu20.04

To test whether you installed the docker image or not, run

docker run --rm --gpus all nvidia/cuda:11.4.2-cudnn8-devel-ubuntu20.04 nvidia-smi Thu Dec 8 08:20:52 2022 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 470.141.03 Driver Version: 470.141.03 CUDA Version: 11.4 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | | | | MIG M. | |===============================+======================+======================| | 0 NVIDIA GeForce . On | 00000000:09:00.0 Off | N/A | | 0% 43C P8 29W / 350W | 19MiB / 24268MiB | 0% Default | | | | N/A | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: | | GPU GI CI PID Type Process name GPU Memory | | ID ID Usage | |=============================================================================| +-----------------------------------------------------------------------------+

In docker hub, Nvidia/cuda provides many images: https://hub.docker.com/r/nvidia/cuda

Читайте также:  Nginx настройки для php

Setup development container in VS Code

Please make sure you will put requirements.txt into the same directory with your Dockerfile . Otherwise you will have change the reference path in your Dockerfile.

Remove Dangling aka Images

docker rmi $(docker images -f «dangling=true» -q)

Never name your python file with the same name of pakcages! For instance, torch.py is very bad naming when you want to use pytorch .

Sometimes you might have out of memory error , please check two things:

The advatange of using Docker image nvidia/cuda:11.4.2-cudnn8-devel-ubuntu20.04 is that many things have been optimized for performance.

AX will preallocate 90% of the total GPU memory when the first JAX operation is run. Preallocating minimizes allocation overhead and memory fragmentation, but can sometimes cause out-of-memory (OOM) errors. If your JAX process fails with OOM, the following environment variables can be used to override the default behavior:

This disables the preallocation behavior. JAX will instead allocate GPU memory as needed, potentially decreasing the overall memory usage. However, this behavior is more prone to GPU memory fragmentation, meaning a JAX program that uses most of the available GPU memory may OOM with preallocation disabled.

If preallocation is enabled, this makes JAX preallocate XX% of the total GPU memory, instead of the default 90%. Lowering the amount preallocated can fix OOMs that occur when the JAX program starts.

This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed (note that this is the only configuration that will deallocate GPU memory, instead of reusing it). This is very slow, so is not recommended for general use, but may be useful for running with the minimal possible GPU memory footprint or debugging OOM failures.

Now once you have that image, you can use it for different projects.

Everytime you start a new project from Github, make sure you will have .devcontainer/devcontainer.json in your repository. Here is my

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Читайте также:  Php date and hour

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I can not use CUDA in vscode jupyter notebook #9081

I can not use CUDA in vscode jupyter notebook #9081

Comments

Applies To

What happened?

I can not use CUDA in vscode jupyter notebook. Because run the following code:

import torch print(torch.cuda.is_available())

If I run it in vscode jupyter notebook, it returns False, while if i run the code in .py file in vscode or in browser jupyter notebook, they all return True. It was ok before, I don’t know why suddenly it doesn’t work.

My environment infomation:

C:\Users\wwdok>python -m torch.utils.collect_env Collecting environment information. PyTorch version: 1.10.2+cu102 Is debug build: False CUDA used to build PyTorch: 10.2 ROCM used to build PyTorch: N/A OS: Microsoft Windows 10 professional workstation GCC version: (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 7.3.0 Clang version: Could not collect CMake version: version 3.20.0-rc5 Libc version: N/A Python version: 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] (64-bit runtime) Python platform: Windows-10-10.0.19041-SP0 Is CUDA available: True CUDA runtime version: 10.2.89 GPU models and configuration: GPU 0: NVIDIA GeForce GTX 1660 SUPER Nvidia driver version: 511.23 cuDNN version: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.2\bin\cudnn_ops_train64_8.dll HIP runtime version: N/A MIOpen runtime version: N/A Versions of relevant libraries: [pip3] numpy==1.22.2 [pip3] pytorch-lightning==1.5.5 [pip3] torch==1.10.2+cu102 [pip3] torch-model-archiver==0.4.2b20211023 [pip3] torch-workflow-archiver==0.1.2b20211023 [pip3] torchaudio==0.10.2+cu102 [pip3] torchcam==0.2.0 [pip3] torchfile==0.1.0 [pip3] torchinfo==1.5.4 [pip3] torchmetrics==0.6.1 [pip3] torchserve==0.4.2 [pip3] torchsummary==1.5.1 [pip3] torchtext==0.10.0 [pip3] torchvision==0.11.3+cu102 [pip3] torchviz==0.0.2 [pip3] vit-pytorch==0.23.2 [conda] blas 1.0 mkl [conda] cudatoolkit 11.1.1 heb2d755_9 conda-forge [conda] mkl 2020.2 256 [conda] mkl-service 2.3.0 py38h196d8e1_0 [conda] mkl_fft 1.3.0 py38h46781fe_0 [conda] mkl_random 1.1.1 py38h47e9c7a_0 [conda] numpy 1.21.3 pypi_0 pypi [conda] numpy-base 1.19.2 py38ha3acd2a_0 [conda] pytorch-lightning 1.5.5 pypi_0 pypi [conda] tensorflow 2.3.0 mkl_py38h8557ec7_0 [conda] torch 1.9.0 pypi_0 pypi [conda] torch-model-archiver 0.4.2b20211023 pypi_0 pypi [conda] torch-workflow-archiver 0.1.2b20211023 pypi_0 pypi [conda] torchaudio 0.9.1 py38 pytorch [conda] torchcam 0.2.0 pypi_0 pypi [conda] torchfile 0.1.0 pypi_0 pypi [conda] torchinfo 1.5.4 pypi_0 pypi [conda] torchmetrics 0.6.1 pypi_0 pypi [conda] torchsummary 1.5.1 pypi_0 pypi [conda] torchvision 0.10.1 py38_cu111 pytorch [conda] torchviz 0.0.2 pypi_0 pypi [conda] vit-pytorch 0.23.2 pypi_0 pypi 

Источник

Читайте также:  Пример простой страницы html

Переводчик Python

Теперь, когда мы настроили наш графический процессор, пришло время установить наш интерпретатор Python, который мы пойдем с Anaconda. Он считается гораздо лучше в использовании, чем традиционная установка Python, и будет работать намного лучше.

Мы можем установить два варианта этого интерпретатора: Anaconda и Miniconda. Чтобы выбрать, с чем идти, обратитесь к следующему руководству (взято из официальной документации):

Выберите Anaconda, если вы:

  • Новичок в Конде или Питоне
  • Как удобство автоматической установки Python и более 150 научных пакетов одновременно
  • Иметь время и дисковое пространство (несколько минут и 5 ГБ) и / или
  • Не хотите устанавливать каждый из пакетов, которые вы хотите использовать по отдельности.

Выберите Miniconda, если вы:

  • Не против установить каждый из пакетов, которые вы хотите использовать по отдельности.
  • Не хватает времени или места на диске для установки более 150 пакетов одновременно и / или
  • Просто вам нужен быстрый доступ к Python и командам conda, и вы хотите разобраться с другими программами позже.

Я использую Miniconda сам. Анаконда раздутая. Многие из пакетов никогда не используются и могут быть легко установлены в случае необходимости.

Примечание. Рекомендуется (но не обязательно) загружать версии Python 3 для выбранного вами интерпретатора, поскольку Python 2 подходит к концу.

После того, как вы установили выбранный вами интерпретатор, пришло время установить необходимые пакеты. Откройте Anaconda Prompt и введите команду:

Для пользователей, использующих только Anaconda, после ввода указанной выше команды введите:

НЕ закрывайте подсказку Anaconda прямо сейчас.

Примечание: TensorFlow поддерживает Python 3.5, 3.6 и 3.7 в Windows 10.

Теперь пришло время создать нашу среду, мы можем легко сделать это с помощью Anaconda Prompt (в этом случае мы будем создавать среду Python 3.7 с именем TensorFlow-GPU):

conda create -n TensorFlow-GPU python=3.7

И мы успешно создали новую среду.

НЕ закрывайте подсказку Anaconda прямо сейчас.

TensorFlow

Теперь мы начинаем устанавливать версию GPU tenorflow и для этого сначала активируем нашу вновь созданную среду. Просто введите:

conda activate TensorFlow-GPU

Далее мы устанавливаем TensorFlow (последняя версия):

pip install tensorflow-gpu

Версия pip официально поддерживается, в то время как версия conda поддерживается сообществом. Google рекомендует установить версию pip.

TensorFlow версии 1.13 и более поздние поставляются с предварительно установленной Keras и встроенной в TensorFlow, что позволяет пользователям устанавливать отдельный пакет Keras.

Теперь, чтобы протестировать среду, вызовите команду:

Если это результат, вы получите:

Тогда это означает, что установка прошла успешно. Теперь перейдем к IDE. Вы можете закрыть подсказку.

Python IDE / текстовый редактор

Оба следующих варианта отлично подходят для отладки, обработки и интеллектуального автозаполнения кода Python с молниеносной скоростью и точностью.

С этим вы готовы начать свое путешествие в машинное обучение и не только.

Источник

Оцените статью