Расчёт на видеокарте и замер времени

Назначение и место в пакете

Модуль переносит самую дорогую часть счёта ядер PlanarRT_H и PlanarRT_X — цикл по времени на Rt-сетке — на видеокарту и измеряет, сколько времени занимает каждая фаза расчёта. Он состоит из трёх частей:

  1. GPU-ветка ядер (tmcgpuh.h, tmcgpux.h, общий загрузчик tmcocl.h). Классы CTmcGpuH и CTmcGpuX держат сетку шага на карте и запускают на ней программы OpenCL C. Всё остальное — препроцессор, построение блоков, порты, запись файлов — остаётся прежним процессорным кодом.
  2. Окно и настройка (gui_common/compute). Окно «Compute» находит видеокарты, проверяет драйвер и саму карту (самотест с побитной сверкой) и сохраняет выбор пользователя. Перед расчётом настройка превращается в переменную окружения TMC_GPU, которую читает ядро.
  3. Хронометраж (tmccalctiming.h). Счётчики фаз шага и текстовый отчёт, который показывает кнопка «Calc. time...» окна статистики и сохраняет ключ /Time. В отчёте для каждого шага указано, где шёл цикл по времени: на процессоре или на карте.

Ключевые свойства:

  • OpenCL 1.2, библиотека OpenCL.dll загружается во время работы — одна ветка кода для NVIDIA и AMD, без CUDA и без зависимости при линковке;
  • расчёт на карте совпадает с расчётом на процессоре бит в бит;
  • карта используется, только если она запрошена, сетка достаточно велика и помещается в память карты; иначе шаг молча считается на процессоре (причина — в отчёте о времени);
  • только 64-битная сборка для Windows.

Принцип распараллеливания и обеспечения совпадения с процессором — на странице теории «Расчёт на видеокарте».

Состав

Файл Роль
src/Include/tmcocl.h загрузка OpenCL.dll (TmcOcl), перечень видеокарт (TmcOclListGpus, TmcOclDevice), имена кодов ошибок
src/kernels/planarrt_h/tmcgpuh.h CTmcGpuH и программа OpenCL ядра H (hpass, hmetal, habs, hgather, hscatter)
src/kernels/planarrt_x/tmcgpux.h CTmcGpuX и программа OpenCL ядра X (xpass, xmetal, xabs, xgather, xscatter)
src/Include/tmccalctiming.h CTmcCalcTiming, TmcTimingStep, счётчики TMCT_*, отчёт о времени
gui_common/compute/tmccompute.h/.cpp без виджетов: перечень карт и диагноз, самотест, Compute.ini, tmcApplyComputeSettings, tmcComputeStatusText
gui_common/compute/computedialog.h/.cpp окно ComputeDialog (меню Config → Compute (GPU)...)
gui_common/compute/demo/main.cpp тестовая программа tmc_compute_demo, в сборку пакета не входит

Вызывающий код (описан на страницах ядер): CTmcRTHRectNode::RunKernel и RunKernel1TGpu в tmcrthrectnode.cpp каждого ядра; доступ к узлам блоков — CTmcRTHNodeDiel::GpuView; окно и tmcApplyComputeSettings вызывает оболочка apps/planarrt_common (main.cpp, mainwindow.cpp).

Загрузка OpenCL

TmcOcl — таблица указателей на 28 функций OpenCL (список TMC_OCL_FUNCS). Load() загружает библиотеку только из системного каталога (<System32>\OpenCL.dll, полный путь), а не из папки задания, и получает адреса всех функций. Если файла нет или в нём не хватает хотя бы одной функции OpenCL 1.2, Load() возвращает false — программа продолжает работать на процессоре.

TmcOclListGpus перечисляет устройства типа GPU всех платформ в устойчивом порядке «платформа, затем устройство» и для каждой карты читает имя, драйвер, версию OpenCL, объём памяти, наибольший буфер, число вычислительных блоков, частоту и признак двойной точности bFP64 (cl_khr_fp64 или ненулевой CL_DEVICE_DOUBLE_FP_CONFIG).

Выбор устройства: ключи и переменные

Номер карты — номер среди карт с двойной точностью, считая с нуля, в порядке TmcOclListGpus. Одинаковую нумерацию дают ядро (Begin) и окно (usableDevices).

Запрос карты ядром (IsRequested) проверяется так:

Условие Итог
ключ /CPU или -CPU (отдельное слово вне кавычек) карта не запрашивается
переменная TMC_GPU > 0 карта номер TMC_GPU − 1
ключ /GPU карта 0
ключ /GPU:n или /GPU=n карта n
ничего из этого карта не запрашивается

Слово внутри кавычек (например, часть пути к .tpl) ключом не считается.

Переменную TMC_GPU ставит оболочка ядра функцией tmcApplyComputeSettings до первого расчёта и повторно после OK в окне «Compute»:

  1. есть /CPU — TMC_GPU снимается;
  2. есть /GPU в любой форме — окружение не трогается, ядро прочтёт ключ само;
  3. TMC_GPU была задана снаружи до запуска программы — она сохраняется (значение запоминается при первом вызове);
  4. в Compute.ini включено UseGpu и последняя проверка выбранной карты пройдена — TMC_GPU = Device + 1;
  5. иначе TMC_GPU снимается.

Строка состояния ядра (tmcComputeStatusText) показывает настройку — «Расчёт: GPU — имя карты» или «Расчёт: CPU». Решение по каждому шагу ядро принимает отдельно (см. следующий раздел), фактическое место счёта видно только в отчёте о времени.

Автоматический выбор CPU/GPU

CTmcGpuH::Begin / CTmcGpuX::Begin вызывается в начале цикла по времени каждого шага. Проверки идут по порядку; первая неудача оставляет шаг на процессоре, а причина записывается в csInfo и попадает в строку Compute: отчёта.

№ Проверка Текст csInfo при отказе
1 карта запрошена (IsRequested) CPU или CPU (key /CPU)
2 64-битная сборка CPU (GPU needs the win64 build)
3 число узлов nX·nY не меньше порога CPU (grid of N nodes is below the GPU threshold M; ...)
4 загружена OpenCL.dll CPU (GPU requested, but OpenCL.dll was not found)
5 есть карта с двойной точностью CPU (GPU requested, but no card with double precision)
6 есть карта с запрошенным номером CPU (GPU card n not found: ...)
7 у каждого блока есть узлы, узлы внутри сетки, нет недопустимых типов узлов поглотителя CPU (a block has no nodes), CPU (a block node is outside the grid), CPU (bad absorber node type - the CPU reports it)
8 хватает памяти карты CPU (the grid needs X GB, card ... has Y GB)
9 контекст создан, программа скомпилирована CPU (OpenCL start on ... failed: ...)
10 буферы созданы и заполнены CPU (memory on ...: ...)

При успехе csInfo = GPU n: имя (версия OpenCL, driver версия, память GB).

Порог числа узлов. TMC_GPU_H_MIN_NODES = 150 000 для H и TMC_GPU_X_MIN_NODES = 60 000 для X. На каждом подтакте процессор забирает с карты узлы вокруг портов и возвращает их — это ожидание почти не зависит от размера сетки, и на маленькой сетке карта проигрывает процессору. Пороги измерены на одной карте; переменная окружения TMC_GPU_MIN_NODES заменяет порог (0 — карта всегда).

Память. Ядро H хранит на карте 4 массива double на узел (две компоненты напряжения и две проводимости) — 32 байта на узел; ядро X — 12 массивов, 96 байт на узел. Оценка

M=bN+20Nблок+pNпорт,b=32 (H), 96 (X),p=24 (H), 64 (X),(1)

сравнивается с 92 % памяти карты; кроме того, один массив компоненты (8N байт) не должен превышать наибольший буфер карты (обычно 1/4 памяти). Ради этого ограничения сетка на карте хранится покомпонентно, а не чередованием, как на процессоре: чередованный массив H (16N байт) или X (48N байт) не уместился бы в один буфер.

Если блок нарушает условия проверки 7, шаг остаётся на процессоре намеренно: процессорный код сам выдаст ту же ошибку, что и без карты.

Цикл по времени на карте

Жизненный цикл объекта на шаге:

RunKernel:
  Begin(prUNode1, prYNode, nX, nY, блоки)  -> false: обычный RunKernel1T на процессоре
  цикл тактов:
    RunKernel1TGpu():
      для каждого подтакта k (H: 0..1, X: 0..3):
        PortsDown(prUNode1)          карта -> процессор: узлы окон портов
        RunExciteInputs..k()         процессор: возбуждение портов, запись сигналов
        [X: RunSaveInputs()]
        PortsUp(prUNode1)            процессор -> карта: узлы окон портов
        Pass(k)                      все внутренние узлы (hpass / xpass)
        [X: Restore()]               узлы портов (RunRestoreInputs)
        Blocks(k)                    METAL / ABSORBER / MAGNETIC
        Download(prUNode1)           только при FIELDS или в окне ДН
        PutField(k), DistributionIntegrated(k)
  End(prUNode1, блоки)               сетка и rU поглотителей -> процессор

Порядок вызовов в точности повторяет процессорный RunKernel1T; меняется только место, где выполняются обновление узлов и блоки.

Синхронизация. Очередь команд одна и выполняется по порядку. Запуски ядер OpenCL не блокируют процессор; точка синхронизации — блокирующее чтение в PortsDown в начале следующего подтакта (оно ждёт окончания всех ранее поставленных команд) и чтение в Download. Запись в PortsUp неблокирующая: её буфер на процессоре не меняется до следующего PortsDown, который стоит в очереди позже.

Контекст между шагами. Контекст, очередь и скомпилированная программа создаются при первом Begin и живут до конца процесса (пересоздаются только при смене карты). Буферы сетки создаются в Begin и освобождаются в End. Деструктор ничего не освобождает: вызовы OpenCL из деструкторов статических объектов небезопасны, ресурсы освобождает завершение процесса.

Конец шага. End вызывается при нормальном окончании, при остановке пользователем (bIsReadData сброшен) и при ошибке. Он копирует сетку и прошлые значения rU узлов поглотителей обратно в массивы процессора — после этого S-матрица, следующий шаг и продолжение после «Stop» работают с теми же данными, что и без карты.

Буферы и ядра OpenCL ядра H

Узел H на процессоре — два значения подряд: prUNode1[2n], prUNode1[2n+1] (компоненты u0, u1) и prYNode[2n], prYNode[2n+1] (проводимости y0, y1), n=ynX+x. На карте — четыре буфера mU0, mU1, mY0, mY1 по N значений.

Ядро OpenCL Процессорный аналог Сетка запусков Что делает
hpass RunScatteringNode1line / ...1line1 (через RunScatteringNode / RunScatteringNode1) 2D, группа 64 × 4, элемент = внутренний узел обновление компоненты подтакта
hmetal ветка METAL RunBlockNode / RunBlockNode1 1D, группа 64, элемент = узел блока обнуление записываемой компоненты
habs ветки ABSORBER, MAGNETIC тех же функций 1D формулы граничного узла по типу
hgather / hscatter — 1D упаковка узлов окон портов и обратно

Подтакт 0 обновляет u0 по u1, подтакт 1 — u1 по u0:

u0[n]←y1[n](u1[n−1]+u1[n+1]+u1[n−nX]+u1[n+nX]+u1[n]y0[n])−u0[n].(2)

Слагаемые складываются слева направо в том же порядке, что на процессоре. Края сетки (x=0, x=nX−1, y=0, y=nY−1) не обновляются ни там, ни там. Глобальный размер запуска округлён вверх до кратного группе; лишние рабочие элементы за краем сетки сразу выходят.

Буферы и ядра OpenCL ядра X

Узел X на процессоре — 6 значений подряд (шаг 6 на узел): компоненты prUNode1[6n+c] и проводимости prYNode[6n+c], c=0..5. На карте — 12 буферов mU[c], mY[c]. Такт состоит из 4 подтактов k=0..3; на подтакте k записывается w=uk, а также

  • s=u(k+3)mod4 — компонента, читаемая у соседей и в узле;
  • o1=u(k+1)mod4, o2=u(k+2)mod4 — компоненты своего узла;
  • a и b — вспомогательные компоненты: a=u5, b=u4 на подтактах 0 и 2; a=u4, b=u5 на 1 и 3.

Ядро xpass (аналог RunScatteringNode1line .. RunScatteringNode1line3):

r=s[n−1]+s[n+1]+s[n−nX]+s[n+nX]+y1s[n]+y2o2[n],(3)
w[n]←−w[n]−2o2[n]+y4(o1[n]+s[n])+y0(r+a[n]−y4b[n]+y3o2[n]−y5(s[n]+o1[n])),a[n]←r,(4)

где yc=yc[n]. Плазменные члены (подмагниченная плазма) входят через проводимости y3, y4, y5 и компоненты a, b; смысл слагаемых — на странице «Волны E-поляризации».

Ядро OpenCL Процессорный аналог Особенность
xpass RunScatteringNode .. RunScatteringNode3 14 аргументов: 6 компонент (в нужной роли) и 6 проводимостей
xmetal ветка METAL RunBlockNode .. RunBlockNode3 обнуляет uk узлов блока
xabs ветки ABSORBER, MAGNETIC читает u(k+3)mod4; проводимость шлейфа узла — слот 1 (mY[1] = prYNode[6n+1])
xgather / xscatter — 6 компонент на узел; pos — место узла в буфере упаковки

Восстановление узлов портов (Restore, аналог RunRestoreInputs): после обновления узлов узлы самих портов получают обратно значения, сохранённые после возбуждения порта. Они берутся из того же буфера упаковки mPPk, который записал PortsUp на этом подтакте; vRestPos хранит место каждого узла порта внутри окна.

Блоки METAL, ABSORBER, MAGNETIC

Узлы всех блоков этих типов собираются в Begin в общие буферы (mBIdx — номер узла, mBTyp — тип, mBRy — проводимость узла поглотителя rY, mBRu — прошлое значение rU), по сегменту на блок в порядке блоков задания. Blocks(k) запускает по одному ядру на сегмент; очередь выполняется по порядку, поэтому узел, попавший в два блока, получает значение последнего блока — как на процессоре. Блоки EPS на карту не переносятся: их вклад уже заложен в проводимостях узлов.

habs / xabs повторяют процессорный разбор типов узла CTMCRTH_BLCKNTYPE_ABSR_*. Пусть u1..u4 — читаемая компонента у соседей n−1, n+nX, n+1, n−nX, ut1 — в самом узле, ut2 = rU, y = rY, y5 — проводимость узла. Для узла с двумя соседями «полностью» и двумя «наполовину» (типы 3, 6, 9, 12)

w=23+|0,75y5|+y/2(ui+uj+0,5(uk+ul)+0,75y5ut1+y2ut2)−ut2,(5)

для типов 7, 11, 13, 14 — с коэффициентами 0,5 и знаменателем 2+|y5/2|+y, для углов 21–24 — с 0,25 и 1+|y5/4|+1,5y; типы 15 и 16 обнуляют узел. Физический смысл — на странице «Граничные условия». После формулы каждый узел сегмента запоминает в rU текущее значение читаемой компоненты. Проверка границ массива (индексы 2m+1 узла и соседей внутри (0,2N) для H, индексы 6m+5 внутри (0,6N) для X) повторяет процессорную: узел у края массива не пересчитывается, но rU обновляется.

Повторы узлов. На процессоре узел, записанный в блоке дважды, обрабатывается последовательно: обе копии читают одни и те же значения (другую компоненту), а в сетке остаётся то, что записала последняя. На карте копии выполнялись бы одновременно, и результат зависел бы от гонки. Поэтому Begin помечает все копии, кроме последней, типом −1: такая копия ничего не пишет в сетку, а только обновляет свой rU.

Недопустимые типы. Типы 1, 2, 4, 5, 8, 10 процессор считает ошибкой («Bad Absorber or Magnetic Type»). Если такой узел есть и он прошёл бы проверку границ, шаг остаётся на процессоре, чтобы ошибка была выдана так же, как без карты.

Порты: обмен узлами с процессором

Возбуждение портов (RunExciteInputs) и запись сигналов в файл остались на процессоре. Чтобы они видели актуальные значения, на каждом подтакте процессор получает с карты окно каждого порта — узел порта и все узлы квадрата ±4 узла вокруг него (то, что может затронуть возбуждение), плюс окно узла 0 (его читает возбуждение на концах порта). Окна объединяются, сортируются, повторы удаляются.

PortsDown собирает окна на карте в плотный буфер (hgather / xgather, 2 или 6 значений на узел) и читает его одним запросом; PortsUp пишет буфер обратно и раскладывает его по сетке (hscatter / xscatter). Объём обмена пропорционален числу узлов портов, а не размеру сетки.

Вся сетка копируется с карты (Download) только когда она действительно нужна процессору: при выводе FIELDS и пока время находится в окне накопления распределения поля для ДН (FIELD_DISTRIBUTION). Такие задания ускоряются на карте слабо.

Обработка ошибок

  • До начала цикла любая неудача (нет библиотеки, карты, памяти, сбой компиляции, ошибка создания буферов) не считается ошибкой расчёта: Begin возвращает false, шаг идёт на процессоре, причина — в csInfo.
  • Во время цикла каждый вызов OpenCL проверяется (Check); первая ошибка запоминается в csError в виде GPU что: код, метод возвращает false, а RunKernel1TGpu передаёт текст в объект ошибки ядра — расчёт шага останавливается с ошибкой. Затем End возвращает то, что удалось прочитать.
  • Коды ошибок переводятся в имена функцией TmcOclErr (короткий список частых кодов, остальные — CL_ERROR).

Окно «Compute»

Окно ComputeDialog открывается из меню ядра Config → Compute (GPU).... При создании оно читает Compute.ini и сразу запускает проверку в фоне (QtConcurrent):

  1. enumerateDevices — перечень карт и диагноз;
  2. если состояние Ok — selfTest каждой карты с двойной точностью (с замером скорости).

Пока идёт проверка, видна бегущая полоса, кнопки OK и «Check again» недоступны. По окончании:

  • строка хода показывает итог; при неполадке видна панель диагноза со ссылками на драйверы NVIDIA и AMD;
  • таблица карт: имя (подсказка — платформа), память, двойная точность, самотест («Passed», «Passed (no speed-up)» — карта считает верно, но её время на узел не меньше 0,8 времени процессора, «Failed»), драйвер;
  • панель подробностей выбранной карты: сведения, список проверок с отметками, журнал компиляции при сбое, оценка ускорения на пробной сетке;
  • флажок Use the video card for calculations доступен, только если хотя бы одна карта прошла проверку; список Video card виден при двух и более таких картах;
  • если карта ещё не выбиралась (в файле нет Device) или выбранная больше не годится, выбирается самая быстрая по замеру (fastestPassedGpu) — так встроенная графика, которая проверку проходит, но счёт не ускоряет, не будет выбрана сама.

OK записывает флажок, номер карты и итог её проверки (storeCheckResult) в Compute.ini и вызывает tmcApplyComputeSettings — следующий расчёт в этом же процессе пойдёт по новой настройке. Отметки нарисованы программно (markIcon, markImg), чтобы не зависеть от символов шрифта.

Диагноз

enumerateDevices ставит одно из состояний OclState:

Состояние Когда Что советует диагноз
Unsupported сборка не 64-битная Windows —
NoLibrary нет OpenCL.dll в системном каталоге установить драйвер видеокарты
OldLibrary OpenCL.dll есть, но без функций 1.2 обновить драйвер
NoPlatforms ни одного драйвера OpenCL установить драйвер; при удалённом рабочем столе карта может быть скрыта
NoGpu платформы есть, видеокарт нет установить или переустановить драйвер
NoDoubleGpu карты без двойной точности нужна дискретная карта NVIDIA или AMD
Ok есть карта с двойной точностью —

TmcOcl::Load не различает «нет файла» и «старый файл», поэтому loadOcl при неудаче отдельно пробует загрузить OpenCL.dll из системного каталога. Переменная окружения TMC_COMPUTE_SIMULATE (NoLibrary, NoPlatforms, NoGpu, NoDoubleGpu, FailTest) изображает поломку для проверки окна на исправной машине.

Самотест карты

selfTest(gpuIndex, measureSpeed) проверяет карту той же формулой узла H, что в ядре (kKernels — копия hpass):

  1. создать контекст и очередь (contextOk);
  2. скомпилировать программу с #pragma OPENCL FP_CONTRACT OFF (compileOk; при сбое — журнал компиляции до 4000 символов);
  3. на сетке 301 × 203 (не кратной группе 64 × 4 — проверяются и краевые рабочие элементы) заполнить данные одинаковым на всех машинах генератором Lcg, посчитать 200 тактов (400 подтактов) на карте и на процессоре (cpuPass) и сравнить буферы побайтно (bitExact, maxAbsDiff);
  4. по желанию — замер: сетка 2048 × 2048, 20 тактов на карте и 3 на процессоре во cpuThreadsForCalc() потоках (логических процессоров минус примерно 1/8), и пропускная способность памяти карты копированием буфера до 64 МБ.

Файл tmccompute.cpp собирается с -ffp-contract=off (MSVC — /fp:precise), иначе компилятор слил бы умножение и сложение процессорного эталона в одну операцию FMA и побитная сверка потеряла бы смысл. Каждый запуск ядра на карте короче миллисекунды, так что сторож драйвера (TDR, около 2 с) не срабатывает.

runFullCheck и reportText дают ту же проверку и текстовый отчёт для консоли (tmc_compute_demo --report).

Настройки Compute.ini

Файл %APPDATA%\TMC_Suite_Qt\Compute.ini общий для ядер H и X:

[Compute]
UseGpu=true        ; флажок «Use the video card for calculations»
Device=0           ; номер карты среди карт с двойной точностью
[LastCheck]
Name=...           ; имя карты последней сохранённой проверки
Driver=...         ; версия драйвера при проверке
Date=...           ; дата и время проверки, ISO 8601
Ok=true            ; проверка пройдена

Карта включается только при UseGpu=true и Ok=true: если после обновления драйвера проверка не пройдена, расчёт сам вернётся на процессор.

Замер времени расчёта

Ядро владеет одним объектом CTmcCalcTiming (GetTiming()). Время измеряется по QueryPerformanceCounter (TmcTimingNow, десятки наносекунд на вызов, несколько вызовов на такт) и копится в счётчиках текущего шага cur.q[TMCT_*] в тиках; перевод в секунды — Sec().

Группа Счётчики
A. Препроцессор и чтение TMCT_MEMFREE, TMCT_PREPR, TMCT_READTPL
B. Подготовка TMCT_OUTFILEINIT, TMCT_DISTRINIT, TMCT_MEMINIT, TMCT_BLOCKGEOM (в т. ч. TMCT_EPSFILE, TMCT_EPSREAD), TMCT_ADMITTANCE, TMCT_TOPOLOGYFILE
C. Цикл по времени TMCT_EXCITE (в т. ч. TMCT_SIGNALFILE), TMCT_SCATTER, TMCT_BLOCKNODE, TMCT_FIELDFILE, TMCT_DISTRINTEGR, TMCT_STATUS, TMCT_LOOPWALL
D. Постобработка TMCT_DISTRFINAL, TMCT_SMATRIX
E. Прочее TMCT_SOUND

Жизненный цикл: BeginStep при чтении шага; BeginRunStep / EndRunStep(состояние) вокруг расчёта шага; BeginRunAll / EndRunAll вокруг «Run all». Завершённые шаги текущего прогона хранятся в истории; продолжение остановленного шага заменяет его запись. Новый одиночный запуск очищает историю, если номер шага меньше последнего или тот же шаг запущен не как продолжение. Методы начала и конца защищены критической секцией, поэтому отчёт можно строить из потока окна во время расчёта.

IsDistrFinalCall повторяет условие CFieldIntegrated::Integrate, чтобы время итоговой записи .AMP/.FAZ/.DAT отнести к постобработке (D1), а не к накоплению (C6).

Особенности при расчёте на карте. В RunKernel1TGpu блоки считаются вместе с узлами, поэтому их время входит в TMCT_SCATTER, а TMCT_BLOCKNODE = 0. Запуски ядер OpenCL не ждут окончания счёта: TMCT_SCATTER измеряет постановку в очередь, а фактическое ожидание карты попадает в TMCT_EXCITE следующего подтакта (блокирующее чтение в PortsDown). Раздельные значения C1 и C2 на карте поэтому не показательны; сумма «чистого счёта» C1 + C2 + C3 и время цикла верны. Копирование сетки с карты при выводе поля входит в TMCT_FIELDFILE.

Отчёт «Calc. time...» и ключ /Time

BuildReport строит текст (по-английски, концы строк CRLF):

  1. шапка: ядро, платформа (win64/win32), дата сборки, файл .tpl, время создания отчёта и начала прогона, компьютер, процессор, число логических процессоров, память, частота таймера, пиковая память процесса;
  2. по каждому шагу — сетка, число тактов, dt, delta, строка Compute: (копия csInfo GPU-ветки: «CPU», «CPU (причина)» или «GPU n: ...»), файлы распределения .eps, таблица фаз A1–E1 (h:mm:ss.mmm, секунды, доля шага), «чистое время счёта» C1 + C2 + C3, запись на диск B1 + B2 + B5 + B7 + C4 + C5, полное время шага и скорость — наносекунд на узел за такт и миллионов обновлений узлов в секунду:
tузел=TC1+C2+C3Nузловnтактов;(6)
  1. сводка по всем шагам, время прогона по часам, процессорное время расчётного потока и доля «процессор / часы».

Окно статистики ядра показывает отчёт кнопкой «Calc. time...» и сохраняет его в TXT. С ключом командной строки /Time после «Run all» отчёт сам записывается рядом с заданием (SaveReport(DefaultReportName())) под именем <имя .tpl без расширения>.timing_<H|X>_<win32|win64>.txt.

Подводные камни

  • Строки программ OpenCL — это код. g_szTmcGpuHSrc, g_szTmcGpuXSrc и kKernels компилирует драйвер. Любое изменение формулы или порядка сложений нарушит совпадение с процессором. Изменение процессорной формулы узла требует того же изменения в строке, и наоборот; kKernels самотеста должен оставаться копией hpass.
  • Слоты проводимости узла X. В X шаг 6 на узел. Граничные узлы поглотителя и магнитной стенки берут проводимость шлейфа из слота 1 (prYNode[6n+1], на карте mY[1]), а не из слота 0 — так же, как процессорный RunBlockNode.
  • Компилятор процессорной части. Совпадение бит в бит держится на запрете FMA с обеих сторон: FP_CONTRACT OFF в программах OpenCL и -ffp-contract=off во всей сборке.
  • Строка состояния ≠ место счёта. «Расчёт: GPU» означает настройку; маленький шаг всё равно посчитается на процессоре. Смотрите строку Compute: отчёта о времени.
  • Номер карты. /GPU:n и TMC_GPU = n + 1 считают только карты с двойной точностью; несуществующий номер не подменяется картой 0 — шаг идёт на процессоре с пояснением.
  • 32-битная сборка на карте не считает никогда.

GPU computing and timing

Purpose and place in the package

The module moves the most expensive part of the PlanarRT_H and PlanarRT_X kernel computation — the time loop on the Rt-grid — to the video card, and measures how long each phase of the computation takes. It consists of three parts:

  1. The GPU branch of the kernels (tmcgpuh.h, tmcgpux.h, shared loader tmcocl.h). The classes CTmcGpuH and CTmcGpuX keep the grid of a step on the card and run OpenCL C programs on it. Everything else — preprocessor, block building, ports, file writing — remains the same CPU code as before.
  2. Dialog and settings (gui_common/compute). The "Compute" dialog finds the video cards, checks the driver and the card itself (a self-test with bitwise comparison) and saves the user's choice. Before a computation the setting is turned into the environment variable TMC_GPU, which the kernel reads.
  3. Timing (tmccalctiming.h). Counters of the step phases and a text report, which is shown by the "Calc. time..." button of the statistics window and saved by the /Time switch. For each step the report states where the time loop ran: on the CPU or on the card.

Key properties:

  • OpenCL 1.2, the OpenCL.dll library is loaded at run time — a single code branch for NVIDIA and AMD, without CUDA and without a link-time dependency;
  • the computation on the card matches the computation on the CPU bit for bit;
  • the card is used only if it has been requested, the grid is large enough and fits into the card memory; otherwise the step is silently computed on the CPU (the reason is given in the timing report);
  • 64-bit Windows build only.

The principle of parallelisation and of ensuring agreement with the CPU is described on the theory page "GPU computing".

Contents

File Role
src/Include/tmcocl.h loading of OpenCL.dll (TmcOcl), list of video cards (TmcOclListGpus, TmcOclDevice), error code names
src/kernels/planarrt_h/tmcgpuh.h CTmcGpuH and the OpenCL program of the H kernel (hpass, hmetal, habs, hgather, hscatter)
src/kernels/planarrt_x/tmcgpux.h CTmcGpuX and the OpenCL program of the X kernel (xpass, xmetal, xabs, xgather, xscatter)
src/Include/tmccalctiming.h CTmcCalcTiming, TmcTimingStep, the TMCT_* counters, the timing report
gui_common/compute/tmccompute.h/.cpp no widgets: list of cards and diagnosis, self-test, Compute.ini, tmcApplyComputeSettings, tmcComputeStatusText
gui_common/compute/computedialog.h/.cpp the ComputeDialog dialog (menu Config → Compute (GPU)...)
gui_common/compute/demo/main.cpp the test program tmc_compute_demo, not part of the package build

The calling code (described on the kernel pages): CTmcRTHRectNode::RunKernel and RunKernel1TGpu in tmcrthrectnode.cpp of each kernel; access to the block nodes — CTmcRTHNodeDiel::GpuView; the dialog and tmcApplyComputeSettings are called by the shell apps/planarrt_common (main.cpp, mainwindow.cpp).

Loading OpenCL

TmcOcl is a table of pointers to 28 OpenCL functions (the list TMC_OCL_FUNCS). Load() loads the library only from the system directory (<System32>\OpenCL.dll, full path), not from the task folder, and obtains the addresses of all functions. If the file is missing or lacks even one OpenCL 1.2 function, Load() returns false — the program continues to run on the CPU.

TmcOclListGpus enumerates GPU-type devices of all platforms in a stable "platform, then device" order and for each card reads the name, driver, OpenCL version, memory size, largest buffer, number of compute units, clock frequency and the double-precision flag bFP64 (cl_khr_fp64 or a non-zero CL_DEVICE_DOUBLE_FP_CONFIG).

Device choice: switches and variables

The card number is the number among cards with double precision, counting from zero, in the order of TmcOclListGpus. The kernel (Begin) and the dialog (usableDevices) use the same numbering.

The kernel's card request (IsRequested) is checked as follows:

Condition Result
switch /CPU or -CPU (a separate word outside quotes) no card is requested
variable TMC_GPU > 0 card number TMC_GPU − 1
switch /GPU card 0
switch /GPU:n or /GPU=n card n
none of the above no card is requested

A word inside quotes (for example, part of the path to a .tpl) is not treated as a switch.

The variable TMC_GPU is set by the kernel shell with the function tmcApplyComputeSettings before the first computation and again after OK in the "Compute" dialog:

  1. /CPU is present — TMC_GPU is removed;
  2. /GPU in any form is present — the environment is not touched, the kernel will read the switch itself;
  3. TMC_GPU was set externally before the program started — it is kept (the value is remembered on the first call);
  4. UseGpu is enabled in Compute.ini and the last check of the selected card passed — TMC_GPU = Device + 1;
  5. otherwise TMC_GPU is removed.

The kernel status bar (tmcComputeStatusText) shows the setting — "Compute: GPU — card name" or "Compute: CPU". The kernel decides for each step separately (see the next section); where the computation actually ran is visible only in the timing report.

Automatic CPU/GPU choice

CTmcGpuH::Begin / CTmcGpuX::Begin is called at the start of the time loop of each step. The checks are made in order; the first failure leaves the step on the CPU, and the reason is written to csInfo and goes into the Compute: line of the report.

No. Check csInfo text on failure
1 the card is requested (IsRequested) CPU or CPU (key /CPU)
2 64-bit build CPU (GPU needs the win64 build)
3 the number of nodes nX·nY is not below the threshold CPU (grid of N nodes is below the GPU threshold M; ...)
4 OpenCL.dll is loaded CPU (GPU requested, but OpenCL.dll was not found)
5 there is a card with double precision CPU (GPU requested, but no card with double precision)
6 there is a card with the requested number CPU (GPU card n not found: ...)
7 each block has nodes, the nodes are inside the grid, there are no invalid absorber node types CPU (a block has no nodes), CPU (a block node is outside the grid), CPU (bad absorber node type - the CPU reports it)
8 the card has enough memory CPU (the grid needs X GB, card ... has Y GB)
9 the context has been created, the program has been compiled CPU (OpenCL start on ... failed: ...)
10 the buffers have been created and filled CPU (memory on ...: ...)

On success csInfo = GPU n: name (OpenCL version, driver version, memory GB).

Node-count threshold. TMC_GPU_H_MIN_NODES = 150,000 for H and TMC_GPU_X_MIN_NODES = 60,000 for X. On every sub-step the CPU fetches the nodes around the ports from the card and returns them — this wait hardly depends on the grid size, and on a small grid the card loses to the CPU. The thresholds were measured on a single card; the environment variable TMC_GPU_MIN_NODES overrides the threshold (0 — always use the card).

Memory. The H kernel keeps 4 double arrays per node on the card (two voltage components and two admittances) — 32 bytes per node; the X kernel keeps 12 arrays, 96 bytes per node. The estimate

M=bN+20Nblock+pNport,b=32 (H), 96 (X),p=24 (H), 64 (X),(1)

is compared with 92 % of the card memory; in addition, one component array (8N bytes) must not exceed the largest buffer of the card (usually 1/4 of the memory). Because of this limit the grid on the card is stored component by component rather than interleaved as on the CPU: an interleaved H array (16N bytes) or X array (48N bytes) would not fit into a single buffer.

If a block violates the conditions of check 7, the step deliberately stays on the CPU: the CPU code itself will report the same error as without the card.

The time loop on the card

Life cycle of the object within a step:

RunKernel:
  Begin(prUNode1, prYNode, nX, nY, blocks) -> false: ordinary RunKernel1T on the CPU
  time-step loop:
    RunKernel1TGpu():
      for each sub-step k (H: 0..1, X: 0..3):
        PortsDown(prUNode1)          card -> CPU: nodes of the port windows
        RunExciteInputs..k()         CPU: port excitation, signal recording
        [X: RunSaveInputs()]
        PortsUp(prUNode1)            CPU -> card: nodes of the port windows
        Pass(k)                      all interior nodes (hpass / xpass)
        [X: Restore()]               port nodes (RunRestoreInputs)
        Blocks(k)                    METAL / ABSORBER / MAGNETIC
        Download(prUNode1)           only with FIELDS or inside the RP window
        PutField(k), DistributionIntegrated(k)
  End(prUNode1, blocks)              grid and absorber rU -> CPU

The order of calls exactly repeats the CPU RunKernel1T; only the place where the node update and the blocks are executed changes.

Synchronisation. There is a single command queue, executed in order. OpenCL kernel launches do not block the CPU; the synchronisation point is the blocking read in PortsDown at the start of the next sub-step (it waits for all previously enqueued commands to finish) and the read in Download. The write in PortsUp is non-blocking: its CPU-side buffer does not change until the next PortsDown, which comes later in the queue.

Context between steps. The context, the queue and the compiled program are created on the first Begin and live until the end of the process (they are recreated only when the card changes). The grid buffers are created in Begin and freed in End. The destructor frees nothing: OpenCL calls from destructors of static objects are unsafe, and the resources are freed by process termination.

End of a step. End is called on normal completion, on a stop by the user (bIsReadData cleared) and on an error. It copies the grid and the previous rU values of the absorber nodes back into the CPU arrays — after that the S-matrix, the next step and continuation after "Stop" work with the same data as without the card.

Buffers and OpenCL kernels of the H kernel

An H node on the CPU is two consecutive values: prUNode1[2n], prUNode1[2n+1] (components u0, u1) and prYNode[2n], prYNode[2n+1] (admittances y0, y1), n=ynX+x. On the card there are four buffers mU0, mU1, mY0, mY1 of N values each.

OpenCL kernel CPU counterpart Launch grid What it does
hpass RunScatteringNode1line / ...1line1 (via RunScatteringNode / RunScatteringNode1) 2D, work-group 64 × 4, work item = interior node update of the sub-step component
hmetal METAL branch of RunBlockNode / RunBlockNode1 1D, work-group 64, work item = block node zeroing of the component being written
habs ABSORBER, MAGNETIC branches of the same functions 1D boundary-node formulas by type
hgather / hscatter — 1D packing of the port-window nodes and back

Sub-step 0 updates u0 from u1, sub-step 1 updates u1 from u0:

u0[n]←y1[n](u1[n−1]+u1[n+1]+u1[n−nX]+u1[n+nX]+u1[n]y0[n])−u0[n].(2)

The terms are added from left to right in the same order as on the CPU. The grid edges (x=0, x=nX−1, y=0, y=nY−1) are updated in neither place. The global launch size is rounded up to a multiple of the work-group; surplus work items beyond the grid edge exit immediately.

Buffers and OpenCL kernels of the X kernel

An X node on the CPU is 6 consecutive values (stride 6 per node): components prUNode1[6n+c] and admittances prYNode[6n+c], c=0..5. On the card there are 12 buffers mU[c], mY[c]. A time step consists of 4 sub-steps k=0..3; on sub-step k the component w=uk is written, and also

  • s=u(k+3)mod4 — the component read at the neighbours and at the node;
  • o1=u(k+1)mod4, o2=u(k+2)mod4 — components of the node itself;
  • a and b — auxiliary components: a=u5, b=u4 on sub-steps 0 and 2; a=u4, b=u5 on 1 and 3.

The xpass kernel (counterpart of RunScatteringNode1line .. RunScatteringNode1line3):

r=s[n−1]+s[n+1]+s[n−nX]+s[n+nX]+y1s[n]+y2o2[n],(3)
w[n]←−w[n]−2o2[n]+y4(o1[n]+s[n])+y0(r+a[n]−y4b[n]+y3o2[n]−y5(s[n]+o1[n])),a[n]←r,(4)

where yc=yc[n]. The plasma terms (magnetized plasma) enter through the admittances y3, y4, y5 and the components a, b; the meaning of the terms is given on the page "E-polarization waves".

OpenCL kernel CPU counterpart Feature
xpass RunScatteringNode .. RunScatteringNode3 14 arguments: 6 components (each in its role) and 6 admittances
xmetal METAL branch of RunBlockNode .. RunBlockNode3 zeroes uk of the block nodes
xabs ABSORBER, MAGNETIC branches reads u(k+3)mod4; the stub admittance of the node is slot 1 (mY[1] = prYNode[6n+1])
xgather / xscatter — 6 components per node; pos is the position of the node in the packing buffer

Restoring the port nodes (Restore, counterpart of RunRestoreInputs): after the node update the port nodes themselves get back the values saved after the port excitation. They are taken from the same packing buffer mPPk that PortsUp wrote on this sub-step; vRestPos stores the position of each port node inside the window.

METAL, ABSORBER, MAGNETIC blocks

The nodes of all blocks of these types are collected in Begin into shared buffers (mBIdx — node index, mBTyp — type, mBRy — absorber node admittance rY, mBRu — previous value rU), one segment per block in the order of the blocks in the task file. Blocks(k) launches one kernel per segment; the queue is executed in order, so a node that belongs to two blocks gets the value of the last block — as on the CPU. EPS blocks are not moved to the card: their contribution is already built into the node admittances.

habs / xabs repeat the CPU dispatch on the node types CTMCRTH_BLCKNTYPE_ABSR_*. Let u1..u4 be the component read at the neighbours n−1, n+nX, n+1, n−nX, ut1 — at the node itself, ut2 = rU, y = rY, y5 — the node admittance. For a node with two "full" neighbours and two "half" neighbours (types 3, 6, 9, 12)

w=23+|0,75y5|+y/2(ui+uj+0,5(uk+ul)+0,75y5ut1+y2ut2)−ut2,(5)

for types 7, 11, 13, 14 — with coefficients 0.5 and denominator 2+|y5/2|+y, for corners 21–24 — with 0.25 and 1+|y5/4|+1,5y; types 15 and 16 zero the node. The physical meaning is given on the page "Boundary conditions". After the formula each node of the segment stores the current value of the read component in rU. The array bounds check (indices 2m+1 of the node and the neighbours inside (0,2N) for H, indices 6m+5 inside (0,6N) for X) repeats the CPU one: a node at the edge of the array is not recomputed, but rU is updated.

Duplicate nodes. On the CPU a node written twice in a block is processed sequentially: both copies read the same values (of the other component), and the grid keeps what the last one wrote. On the card the copies would run simultaneously, and the result would depend on a race. Therefore Begin marks all copies except the last with type −1: such a copy writes nothing into the grid and only updates its own rU.

Invalid types. Types 1, 2, 4, 5, 8, 10 are treated by the CPU as an error ("Bad Absorber or Magnetic Type"). If there is such a node and it would pass the bounds check, the step stays on the CPU so that the error is reported the same way as without the card.

Ports: exchanging nodes with the CPU

Port excitation (RunExciteInputs) and writing the signals to a file have remained on the CPU. So that they see up-to-date values, on every sub-step the CPU receives from the card the window of each port — the port node and all nodes of the square ±4 nodes around it (whatever the excitation can affect), plus the window of node 0 (it is read by the excitation at the ends of the port). The windows are merged, sorted, and duplicates are removed.

PortsDown gathers the windows on the card into a dense buffer (hgather / xgather, 2 or 6 values per node) and reads it in a single request; PortsUp writes the buffer back and scatters it over the grid (hscatter / xscatter). The amount of exchange is proportional to the number of port nodes, not to the grid size.

The whole grid is copied from the card (Download) only when the CPU really needs it: when FIELDS are output and while the time is inside the accumulation window of the field distribution for the RP (FIELD_DISTRIBUTION). Such task files gain little from the card.

Error handling

  • Before the loop starts any failure (no library, no card, no memory, compilation failure, buffer creation error) is not treated as a computation error: Begin returns false, the step runs on the CPU, and the reason is in csInfo.
  • During the loop every OpenCL call is checked (Check); the first error is stored in csError in the form GPU what: code, the method returns false, and RunKernel1TGpu passes the text to the kernel error object — the computation of the step stops with an error. Then End returns whatever could be read.
  • Error codes are converted to names by the function TmcOclErr (a short list of frequent codes, the rest — CL_ERROR).

The "Compute" dialog

The ComputeDialog dialog is opened from the kernel menu Config → Compute (GPU).... When created, it reads Compute.ini and immediately starts a check in the background (QtConcurrent):

  1. enumerateDevices — list of cards and diagnosis;
  2. if the state is Ok — selfTest of each card with double precision (with a speed measurement).

While the check is running, a busy bar is shown and the OK and "Check again" buttons are disabled. When it finishes:

  • the progress line shows the result; in case of a problem a diagnosis panel with links to the NVIDIA and AMD drivers is shown;
  • the table of cards: name (the tooltip shows the platform), memory, double precision, self-test ("Passed", "Passed (no speed-up)" — the card computes correctly, but its time per node is not less than 0.8 of the CPU time, "Failed"), driver;
  • the details panel of the selected card: information, a list of checks with marks, the compilation log on failure, an estimate of the speed-up on a test grid;
  • the Use the video card for calculations check box is available only if at least one card has passed the check; the Video card list is shown when there are two or more such cards;
  • if no card has been chosen yet (the file has no Device) or the chosen one is no longer suitable, the fastest by measurement is chosen (fastestPassedGpu) — so integrated graphics, which pass the check but do not speed up the computation, will not be chosen by themselves.

OK writes the check box, the card number and the result of its check (storeCheckResult) to Compute.ini and calls tmcApplyComputeSettings — the next computation in the same process will follow the new setting. The marks are drawn programmatically (markIcon, markImg) so as not to depend on font glyphs.

Diagnosis

enumerateDevices sets one of the OclState states:

State When What the diagnosis advises
Unsupported the build is not 64-bit Windows —
NoLibrary no OpenCL.dll in the system directory install the video card driver
OldLibrary OpenCL.dll is present but without the 1.2 functions update the driver
NoPlatforms no OpenCL driver at all install the driver; over Remote Desktop the card may be hidden
NoGpu there are platforms but no video cards install or reinstall the driver
NoDoubleGpu cards without double precision a discrete NVIDIA or AMD card is needed
Ok there is a card with double precision —

TmcOcl::Load does not distinguish between "no file" and "old file", so on failure loadOcl separately tries to load OpenCL.dll from the system directory. The environment variable TMC_COMPUTE_SIMULATE (NoLibrary, NoPlatforms, NoGpu, NoDoubleGpu, FailTest) simulates a failure for testing the dialog on a working machine.

Card self-test

selfTest(gpuIndex, measureSpeed) checks the card with the same H node formula as in the kernel (kKernels is a copy of hpass):

  1. create a context and a queue (contextOk);
  2. compile the program with #pragma OPENCL FP_CONTRACT OFF (compileOk; on failure — a compilation log of up to 4000 characters);
  3. on a 301 × 203 grid (not a multiple of the 64 × 4 work-group, so the edge work items are tested too) fill the data with the Lcg generator, identical on all machines, compute 200 time steps (400 sub-steps) on the card and on the CPU (cpuPass) and compare the buffers byte by byte (bitExact, maxAbsDiff);
  4. optionally — a measurement: a 2048 × 2048 grid, 20 time steps on the card and 3 on the CPU in cpuThreadsForCalc() threads (logical processors minus about 1/8), and the memory bandwidth of the card by copying a buffer of up to 64 MB.

The file tmccompute.cpp is compiled with -ffp-contract=off (MSVC — /fp:precise), otherwise the compiler would fuse the multiplication and addition of the CPU reference into a single FMA operation and the bitwise comparison would lose its meaning. Each kernel launch on the card is shorter than a millisecond, so the driver watchdog (TDR, about 2 s) does not trigger.

runFullCheck and reportText provide the same check and a text report for the console (tmc_compute_demo --report).

Compute.ini settings

The file %APPDATA%\TMC_Suite_Qt\Compute.ini is shared by the H and X kernels:

[Compute]
UseGpu=true        ; the "Use the video card for calculations" check box
Device=0           ; card number among the cards with double precision
[LastCheck]
Name=...           ; card name of the last saved check
Driver=...         ; driver version at the time of the check
Date=...           ; date and time of the check, ISO 8601
Ok=true            ; the check passed

The card is enabled only when UseGpu=true and Ok=true: if the check fails after a driver update, the computation automatically falls back to the CPU.

Timing the computation

The kernel owns a single CTmcCalcTiming object (GetTiming()). Time is measured with QueryPerformanceCounter (TmcTimingNow, tens of nanoseconds per call, a few calls per time step) and accumulated in the counters of the current step cur.q[TMCT_*] in ticks; conversion to seconds is done by Sec().

Group Counters
A. Preprocessor and reading TMCT_MEMFREE, TMCT_PREPR, TMCT_READTPL
B. Preparation TMCT_OUTFILEINIT, TMCT_DISTRINIT, TMCT_MEMINIT, TMCT_BLOCKGEOM (including TMCT_EPSFILE, TMCT_EPSREAD), TMCT_ADMITTANCE, TMCT_TOPOLOGYFILE
C. Time loop TMCT_EXCITE (including TMCT_SIGNALFILE), TMCT_SCATTER, TMCT_BLOCKNODE, TMCT_FIELDFILE, TMCT_DISTRINTEGR, TMCT_STATUS, TMCT_LOOPWALL
D. Post-processing TMCT_DISTRFINAL, TMCT_SMATRIX
E. Other TMCT_SOUND

Life cycle: BeginStep when a step is read; BeginRunStep / EndRunStep(state) around the computation of a step; BeginRunAll / EndRunAll around "Run all". The completed steps of the current run are kept in the history; continuing a stopped step replaces its record. A new single run clears the history if the step number is less than the last one or the same step is started not as a continuation. The begin and end methods are protected by a critical section, so the report can be built from the window thread during a computation.

IsDistrFinalCall repeats the condition of CFieldIntegrated::Integrate so that the time of the final writing of .AMP/.FAZ/.DAT is attributed to post-processing (D1) rather than to accumulation (C6).

Specifics when computing on the card. In RunKernel1TGpu the blocks are computed together with the nodes, so their time is included in TMCT_SCATTER, and TMCT_BLOCKNODE = 0. OpenCL kernel launches do not wait for the computation to finish: TMCT_SCATTER measures the enqueueing, and the actual wait for the card goes into TMCT_EXCITE of the next sub-step (the blocking read in PortsDown). The separate values C1 and C2 on the card are therefore not representative; the sum of "net computation" C1 + C2 + C3 and the loop time are correct. Copying the grid from the card when the field is output is included in TMCT_FIELDFILE.

The "Calc. time..." report and the /Time switch

BuildReport builds the text (in English, CRLF line endings):

  1. header: kernel, platform (win64/win32), build date, .tpl file, time of report creation and of the start of the run, computer, processor, number of logical processors, memory, timer frequency, peak process memory;
  2. for each step — grid, number of time steps, dt, delta, the line Compute: (a copy of csInfo of the GPU branch: "CPU", "CPU (reason)" or "GPU n: ..."), .eps distribution files, the table of phases A1–E1 (h:mm:ss.mmm, seconds, share of the step), the "net computation time" C1 + C2 + C3, disk writing B1 + B2 + B5 + B7 + C4 + C5, the total time of the step and the speed — nanoseconds per node per time step and millions of node updates per second:
tnode=TC1+C2+C3Nnodesnsteps;(6)
  1. a summary over all steps, the wall-clock time of the run, the CPU time of the computation thread and the "CPU / wall clock" ratio.

The kernel statistics window shows the report with the "Calc. time..." button and saves it as TXT. With the command-line switch /Time, after "Run all" the report is written automatically next to the task file (SaveReport(DefaultReportName())) under the name <.tpl name without extension>.timing_<H|X>_<win32|win64>.txt.

Pitfalls

  • The OpenCL program strings are code. g_szTmcGpuHSrc, g_szTmcGpuXSrc and kKernels are compiled by the driver. Any change in a formula or in the order of additions will break the agreement with the CPU. A change in the CPU node formula requires the same change in the string, and vice versa; the self-test kKernels must remain a copy of hpass.
  • Admittance slots of the X node. X has a stride of 6 per node. The boundary nodes of the absorber and of the magnetic wall take the stub admittance from slot 1 (prYNode[6n+1], on the card mY[1]), not from slot 0 — the same as the CPU RunBlockNode.
  • The compiler of the CPU part. Bit-for-bit agreement relies on forbidding FMA on both sides: FP_CONTRACT OFF in the OpenCL programs and -ffp-contract=off in the whole build.
  • Status bar ≠ where the computation runs. "Compute: GPU" means the setting; a small step will still be computed on the CPU. Look at the Compute: line of the timing report.
  • Card number. /GPU:n and TMC_GPU = n + 1 count only cards with double precision; a non-existent number is not replaced by card 0 — the step runs on the CPU with an explanation.
  • A 32-bit build never computes on the card.