0Pricing
CUDA Academy · Урок

Перечисление и выбор устройств

cudaSetDevice и контексты для каждого GPU

«Перечисление и выбор устройств» — бесплатный урок CUDA Academy на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения CUDA Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс CUDA Academy содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

More Than One GPU

A single machine can hold several GPUs. To use them all, your program first needs to discover how many devices are present before it sends any work.

Counting the Devices

One call tells you how many GPUs the runtime can see. cudaGetDeviceCount writes that number into an int you hand it.

int count;
cudaGetDeviceCount(&count);

Devices Are Numbered

Each GPU gets an integer id from 0 up to count minus one. That device id is how you point the runtime at one specific card.

Picking the Active Device

You choose which GPU your next calls target with cudaSetDevice. After this, allocations and launches go to that card.

cudaSetDevice(1);

There Is a Current Device

At any moment exactly one GPU is the current device for the calling thread. Every cudaMalloc or kernel launch lands on whatever device is current.

Inspecting a Device

Before trusting a GPU you can read its specs. cudaGetDeviceProperties fills a struct with name, memory size, and compute capability.

cudaDeviceProp prop;
cudaGetDeviceProperties(&prop, 0);

Reading the Properties

The properties struct is rich. Fields like name and totalGlobalMem help you pick the best card or skip one that is too small.

Each Device Owns Its Memory

A pointer from cudaMalloc belongs to whichever GPU was current then. Using it while another device is current is an error waiting to happen.

Per-Device Contexts

Behind each GPU sits a context that holds its allocations and streams. Switching the current device switches you into that device's context.

Looping Over All GPUs

A common pattern is a loop that calls cudaSetDevice for each id, then does setup on that card. This is how you spread work across every device.

for (int d = 0; d < count; d++) {
  cudaSetDevice(d);
}

Restore Before You Leave

If a helper changes the current device, switch it back when done. Leaving the current device changed can surprise the rest of your code.

Quick Check

Recall which call chooses the GPU your next allocations and launches will use.

Recap

You count GPUs, pick one with cudaSetDevice, and inspect it with properties. Each device owns its own memory and context. Next: splitting work across them. ✨

Часто задаваемые вопросы

Урок «Перечисление и выбор устройств» бесплатный?

Да — полный текст урока «Перечисление и выбор устройств» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс CUDA Academy, подпишись на CoddyKit PRO. Курс CUDA Academy содержит 4 уроков всего.

Чему я научусь в уроке «Перечисление и выбор устройств»?

cudaSetDevice и контексты для каждого GPU Ты практикуешь CUDA Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать CUDA Academy?

Предыдущий опыт не требуется. CUDA Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.

Сколько времени занимает урок «Перечисление и выбор устройств»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке CUDA Academy?

Да. Каждый урок CUDA Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Перечисление и выбор устройств
  2. Распределение работы между GPU
  3. Прямой доступ к памяти между устройствами
  4. Несколько GPU с NCCL
← Назад к CUDA Academy