Расчёт на видеокарте
Цикл по времени на Rt-сетке — это миллионы одинаковых простых обновлений узлов на каждом такте. Именно такую работу видеокарта выполняет в десятки раз быстрее процессора. Ядра PlanarRT_H и PlanarRT_X умеют переносить этот цикл на видеокарту, не меняя ни одной цифры результата. На странице объяснено, почему схема хорошо параллелится, как обеспечено совпадение с процессором и когда карта выгодна. Устройство кода — на странице «Расчёт на видеокарте и замер времени».
OpenCL и выбор устройства
Программа обращается к видеокарте через стандарт OpenCL 1.2. Его поддерживают обычные драйверы видеокарт NVIDIA и AMD, поэтому
- одна и та же ветка кода работает на картах обоих производителей;
- не нужны CUDA и другие пакеты разработчика — достаточно драйвера;
- библиотека
OpenCL.dllподключается во время работы: на компьютере без неё программа запускается как обычно и считает на процессоре.
Расчёт ведётся в числах двойной точности (double), как и на процессоре. Карта без
двойной точности (это обычно встроенная графика) для расчёта не используется. Карты
нумеруются с нуля среди карт с двойной точностью; номер выбирается в окне «Compute»
или ключом /GPU:n, ключ /CPU запрещает карту.
Перед первым использованием окно «Compute» проверяет карту: драйвер должен создать рабочий контекст, скомпилировать программу расчёта и получить на пробной сетке ровно те же биты, что и процессор.
Узлы сетки и рабочие элементы
Почему схема параллелится
Состояние Rt-сетки — напряжения падающих волн в узлах (у ядра H две компоненты на узел, у ядра X — шесть; см. «Схема узла H» и «Узел X»). Шаг по времени разбит на подтакты (H, X). На каждом подтакте обновляется одна компонента всех узлов, и для этого используются только
- значения другой компоненты у четырёх соседей и в самом узле;
- проводимости самого узла;
- у ядра X — ещё вспомогательные компоненты своего узла.
Компонента, которую подтакт пишет, ни одним другим узлом на этом подтакте не читается. Значит, узлы подтакта независимы: их можно обновлять в любом порядке и одновременно, и результат не изменится. Для ядра H это видно прямо из формулы подтакта
где справа нет ни одного нового значения соседей. Следующий подтакт меняет роли компонент, и между подтактами достаточно одной точки синхронизации.
Как узлы распределены по карте
Каждый внутренний узел — один рабочий элемент OpenCL. Рабочие элементы собраны в группы 64 × 4 узла: соседние по узлы лежат в памяти подряд, и группа читает память широкими непрерывными блоками. Узлов в сетке сотни тысяч и миллионы, поэтому тысячи ядер видеокарты загружены полностью.
Скорость такого расчёта ограничена не арифметикой (на узел — около десятка операций), а пропускной способностью памяти: за подтакт каждый узел читает и пишет несколько чисел по 8 байт. У видеокарты эта пропускная способность в десятки раз выше, чем у процессора; отсюда и ускорение.
Чтобы большие сетки помещались в отдельные буферы карты, каждая компонента хранится своим массивом (на процессоре компоненты узла лежат рядом).
Что остаётся на процессоре
- Порты. Возбуждение падающей волны и запись сигналов — немного узлов, но сложная логика (сигналы из выражений и файлов, многочастотность). На каждом подтакте процессор забирает с карты только небольшие окна узлов вокруг портов и возвращает их обратно.
- Граничные узлы блоков (металл, поглотители, магнитные стенки) считаются на карте отдельными короткими проходами по спискам их узлов, в том же порядке блоков, что на процессоре.
- Подготовка задания и все выходные файлы. Если нужен вывод поля целиком (
FIELDS) или накопление поля для диаграммы направленности, вся сетка копируется с карты — такие задания ускоряются слабо.
Совпадение с расчётом на процессоре
Результат на карте совпадает с результатом на процессоре бит в бит, а не «с точностью до погрешности». Это обеспечено тремя условиями.
- Тот же порядок операций. Сложение чисел с плавающей точкой не ассоциативно: и могут различаться в последнем бите. Формулы на карте записаны слово в слово как в процессорном коде, слагаемые складываются в том же порядке. Распараллеливание идёт по узлам, а не внутри формулы одного узла, поэтому порядок внутри формулы сохраняется.
- Без слияния умножения и сложения. Современные процессоры и видеокарты умеют
выполнять одной операцией FMA с одним округлением вместо двух. Это
точнее, но даёт другие биты. Слияние запрещено с обеих сторон: в программе OpenCL
(
FP_CONTRACT OFF) и при сборке процессорного кода. - Те же числа и тот же порядок обработки граничных узлов. Расчёт идёт в
doubleстандарта IEEE 754 с округлением к ближайшему; блоки обрабатываются в порядке задания, а узел, записанный в блоке несколько раз, получает значение последней записи — как при последовательном обходе на процессоре.
Совпадение проверено на регрессионных заданиях обоих ядер (диэлектрики, металл,
поглотители, магнитные стенки, подмагниченная плазма, файлы распределений, сетки до
миллионов узлов) по выходным файлам .t, .s, .AMP, .FAZ, .DAT — побайтно, на
картах NVIDIA и AMD и на встроенной графике Intel. Поэтому выбор «карта или процессор»
влияет только на скорость, а не на физический результат.
Автоматический выбор CPU/GPU
Даже когда карта включена, ядро решает для каждого шага задания, стоит ли ею пользоваться.
Размер сетки. На каждом подтакте карта ждёт обмена узлами портов с процессором. Это ожидание — доли миллисекунды на такт — почти не зависит от размера сетки. На большой сетке оно ничтожно по сравнению с выигрышем в счёте, на маленькой — дороже самого счёта. Поэтому сетка меньше порога считается на процессоре: 150 000 узлов для ядра H и 60 000 для ядра X (узел X втрое дороже, и карта окупается раньше). Порог измерен на одной видеокарте и может быть заменён переменной окружения.
Память. На карте нужно примерно 32 байта на узел для ядра H и 96 байт для ядра X (плюс немного на граничные узлы и порты). Если задача не помещается в память карты, шаг считается на процессоре.
Наличие карты. Нет драйвера OpenCL, нет карты с двойной точностью, карта не приняла работу — шаг считается на процессоре.
Во всех этих случаях результат такой же, как на карте; меняется только время. Где
фактически считался каждый шаг и почему, указано в отчёте о времени расчёта (строка
Compute:).
Когда карта выгодна. Чем больше сетка, тем больше выигрыш: от примерно десятикратного на миллионе узлов до нескольких десятков раз на десятках миллионов узлов; точная величина определяется прежде всего скоростью памяти видеокарты. Мало выигрывают задания с выводом поля на каждом шаге и с накоплением диаграммы направленности, а также небольшие задачи. Окно «Compute» делает короткий замер на конкретном компьютере и показывает оценку ускорения для него.
GPU computing
The time loop on the Rt-grid consists of millions of identical simple node updates at every time step. This is exactly the kind of work a GPU performs tens of times faster than a CPU. The PlanarRT_H and PlanarRT_X kernels can offload this loop to the GPU without changing a single digit of the result. This page explains why the scheme parallelizes well, how agreement with the CPU is ensured, and when the GPU pays off. The code structure is described on the "GPU computing and timing" page.
OpenCL and device selection
The program accesses the GPU through the OpenCL 1.2 standard. It is supported by the standard NVIDIA and AMD graphics drivers, therefore
- the same code path works on cards from both vendors;
- CUDA and other developer kits are not needed — the driver is sufficient;
- the
OpenCL.dlllibrary is loaded at run time: on a computer without it the program starts as usual and computes on the CPU.
The computation is performed in double-precision numbers (double), as on the CPU. A card without
double precision (usually integrated graphics) is not used for computation. Cards
are numbered from zero among the cards with double precision; the number is selected in the "Compute" window
or with the /GPU:n switch, and the /CPU switch disables the card.
Before first use, the "Compute" window tests the card: the driver must create a working context, compile the computation program and obtain on a test grid exactly the same bits as the CPU.
Grid nodes and work-items
Why the scheme parallelizes
The state of the Rt-grid is the voltages of the incident waves at the nodes (two components per node for the H kernel, six for the X kernel; see "H node circuit" and "X node"). A time step is divided into sub-steps (H, X). At each sub-step one component of all nodes is updated, and this uses only
- the values of the other component at the four neighbours and at the node itself;
- the admittances of the node itself;
- for the X kernel, also auxiliary components of the node itself.
The component that a sub-step writes is not read by any other node during that sub-step. Hence the nodes of a sub-step are independent: they can be updated in any order and simultaneously, and the result does not change. For the H kernel this can be seen directly from the sub-step formula
where the right-hand side contains no new values of of the neighbours. The next sub-step swaps the roles of the components, and a single synchronization point between sub-steps is sufficient.
How nodes are distributed over the card
Each interior node is one OpenCL work-item. Work-items are grouped into work-groups of 64 × 4 nodes: nodes adjacent in are contiguous in memory, and a work-group reads memory in wide contiguous blocks. A grid has hundreds of thousands to millions of nodes, so the thousands of GPU cores are fully loaded.
The speed of such a computation is limited not by arithmetic (about a dozen operations per node) but by memory bandwidth: during a sub-step each node reads and writes several 8-byte numbers. A GPU has tens of times higher memory bandwidth than a CPU; hence the speed-up.
So that large grids fit into separate buffers on the card, each component is stored in its own array (on the CPU the components of a node are stored next to each other).
What remains on the CPU
- Ports. Excitation of the incident wave and recording of signals involve few nodes but complex logic (signals from expressions and files, multi-frequency operation). At each sub-step the CPU fetches from the card only small windows of nodes around the ports and sends them back.
- Boundary nodes of blocks (metal, absorbers, magnetic walls) are computed on the card in separate short passes over the lists of their nodes, in the same block order as on the CPU.
- Task preparation and all output files. If full field output (
FIELDS) or field accumulation for the radiation pattern is required, the whole grid is copied from the card — such tasks gain little speed-up.
Agreement with the CPU computation
The result on the card matches the result on the CPU bit for bit, not "to within round-off error". This is ensured by three conditions.
- The same order of operations. Floating-point addition is not associative: and may differ in the last bit. The formulas on the card are written word for word as in the CPU code, and the terms are summed in the same order. Parallelization is over nodes, not within the formula of a single node, so the order within a formula is preserved.
- No fusion of multiplication and addition. Modern CPUs and GPUs can
perform as a single FMA operation with one rounding instead of two. This
is more accurate but gives different bits. Fusion is prohibited on both sides: in the OpenCL program
(
FP_CONTRACT OFF) and when building the CPU code. - The same numbers and the same order of processing boundary nodes. The computation uses IEEE 754
doublewith round-to-nearest; blocks are processed in the order of the task file, and a node written several times within a block receives the value of the last write — as in sequential traversal on the CPU.
The agreement has been verified on the regression tasks of both kernels (dielectrics, metal,
absorbers, magnetic walls, magnetized plasma, distribution files, grids of up to
millions of nodes) using the output files .t, .s, .AMP, .FAZ, .DAT — byte for byte, on
NVIDIA and AMD cards and on Intel integrated graphics. Therefore the choice "GPU or CPU"
affects only the speed, not the physical result.
Automatic CPU/GPU selection
Even when the card is enabled, the kernel decides for each step of the task whether it is worth using it.
Grid size. At each sub-step the card waits for the exchange of port nodes with the CPU. This wait — a fraction of a millisecond per time step — hardly depends on the grid size. On a large grid it is negligible compared with the gain in computation, while on a small one it costs more than the computation itself. Therefore a grid below a threshold is computed on the CPU: 150 000 nodes for the H kernel and 60 000 for the X kernel (an X node is three times more expensive, so the card pays off sooner). The threshold was measured on one GPU and can be overridden by an environment variable.
Memory. The card needs about 32 bytes per node for the H kernel and 96 bytes for the X kernel (plus a little for boundary nodes and ports). If the problem does not fit into the card's memory, the step is computed on the CPU.
Availability of a card. If there is no OpenCL driver, no card with double precision, or the card did not accept the work, the step is computed on the CPU.
In all these cases the result is the same as on the card; only the time changes. Where
each step was actually computed, and why, is indicated in the computation-time report (the
Compute: line).
When the GPU pays off. The larger the grid, the greater the gain: from about tenfold at a million nodes to several tens of times at tens of millions of nodes; the exact value is determined primarily by the memory speed of the GPU. Tasks with field output at every step and with radiation-pattern accumulation, as well as small problems, gain little. The "Compute" window runs a short benchmark on the particular computer and shows the estimated speed-up for it.