exponenta event banner

DVB-S.2 Моделирование системы с использованием системного объекта декодера LDPC на основе GPU

В этом примере показано, как использовать object™ системы декодера LDPC на основе графического процессора для увеличения скорости моделирования системы связи. Повышение производительности иллюстрируется моделирующей частью стандарта ETSI (Европейский институт телекоммуникационных стандартов) EN 302 307 для вещания, интерактивных услуг, сбора новостей и других широкополосных спутниковых приложений (DVB-S.2) [1]. Дополнительные сведения об использовании системных объектов для моделирования DVB-S.2 системы см. в разделе DVB-S.2 Link, включая кодирование LDPC в Simulink. Для использования декодера LDPC на базе графического процессора необходимо иметь лицензию пользователя Parallel Computing Toolbox™.

Введение

Алгоритм декодирования LDPC является дорогостоящим в вычислительном отношении и составляет подавляющее большинство времени, затраченного на моделирование DVB-S.2. Использование системного объекта comm.gpu.LDPCDecoder для выполнения алгоритма декодирования на GPU значительно увеличивает время выполнения моделирования. Пример моделирует систему DVB-S.2, получая тест на скорость (время выполнения), один раз с декодером LDPC на базе CPU (comm.LDPCDecoderи один раз с декодером LDPC на основе GPU (comm.gpu.LDPCDecoder). Пример фиксирует частоту битовых ошибок для обеих версий, чтобы показать отсутствие потерь в производительности декодирования с использованием графического процессора.

fprintf(...
    'DVB-S.2 Digital Video Broadcast Standard Bit Error Rate Simulation\n\n');
DVB-S.2 Digital Video Broadcast Standard Bit Error Rate Simulation
fprintf(...
    'Performance comparison of CPU- and GPU- accelerated decoders.\n');
Performance comparison of CPU- and GPU- accelerated decoders.

Обнаружение присутствия GPU

В примере предпринимается попытка запросить графический процессор, чтобы обнаружить пользовательскую лицензию Parallel Computing Toolbox и наличие поддерживаемого графического процессора. Если графический процессор или панель параллельных вычислений недоступны, можно выполнить моделирование только ЦП.

try
    % Query the GPU
    dev = parallel.gpu.GPUDevice.current;
    
    % Print out information about the GPU that was found
    fprintf(...
        'GPU detected (%s, %d multiprocessors, Compute Capability %s)\n',...
        dev.Name,dev.MultiprocessorCount,dev.ComputeCapability);
    
    % Include a GPU-based simulation.
    doGPU = true;
    
catch % #ok<CTCH>
    
    % The GPU is not supported or not present, or the Parallel Computing
    %Toolbox was not present and licensed. Consider a CPU-only simulation.
    
    inp = input(['***NOTE: GPU not detected. ', ...
        'Continue with CPU-only simulation? [Y]/N '],'s');
    if strcmpi(inp, 'y') || isempty(inp)
        doGPU = false;
    else
        return;
    end
end
GPU detected (Quadro P620, 4 multiprocessors, Compute Capability 6.1)

Инициализация

Функция getParamsDVBS2Demo.m генерирует структуру dvb, которая содержит конфигурационную информацию для DVB-S.2 системы с учетом приведенных ниже параметров. Далее пример включает создание и настройку системных объектов на основе структуры dvb.

Сценарий createSimObjDVBS2Demo.m создает большинство системных объектов, используемых в DVB-S.2, и настраивает их на основе структуры dvb.

Затем создаются и конфигурируются идентичные объекты системы декодера LDPC на основе CPU и GPU.

% DVB-S.2 System Parameters
subsystemType = 'QPSK 1/2'; % Constellation and LDPC code rate
EsNodB = 0.75;              % Energy per symbol to noise PSD ratio in dB
numFrames = 10;             % Number of frames to simulate
maxNumLDPCIterations = 50;  % LDPC Decoder iterations

dvb = getParamsDVBS2Demo(subsystemType,EsNodB,maxNumLDPCIterations);

% Create and configure the BCH Encoder and Decoder, Modulator, Demodulator,
% AWGN Channel.

createSimObjDVBS2Demo;

% Construct the LDPC Encoder
encldpc = comm.LDPCEncoder(dvb.LDPCParityCheckMatrix);

% Construct the LDPC Decoder System objects

% LDPC Decoder Configuration
ldpcPropertyValuePairs = { ...
    'MaximumIterationCount',dvb.LDPCNumIterations, ...
    'ParityCheckMatrix',dvb.LDPCParityCheckMatrix, ...
    'DecisionMethod','Hard Decision', ...
    'IterationTerminationCondition','Maximum iteration count', ...
    'OutputValue','Information part'};

% Construct the LDPC Decoder System objects (CPU and GPU versions)
decldpc = comm.LDPCDecoder(ldpcPropertyValuePairs{:});
if doGPU
    gpuLDPCDecoder = comm.gpu.LDPCDecoder(ldpcPropertyValuePairs{:});
end

% Create an ErrorRate object to analyze the differences in bit error rate
% between the CPU and GPU.

BER = comm.ErrorRate;

Сравнение производительности ЦП и графического процессора

В этом примере система DVB-S.2 моделируется сначала с использованием объекта системы декодера LDPC на базе CPU, а затем объекта системы декодера LDPC на основе GPU. Пример получает системные тесты для каждого LDPC-декодера, передавая несколько кадров данных через систему и измеряя общее время моделирования системы. Первый кадр данных имеет большое время инициализации моделирования, и поэтому он исключается из контрольных расчетов. Время моделирования для каждого кадра и среднее время моделирования системы печатаются в окне команд. Частота битовых ошибок (BER) системы также печатается в окне команд для иллюстрации того, что декодеры LDPC на основе CPU и GPU достигают одинакового BER.

if doGPU
    architectures = 2;
else
    architectures = 1;
end

% Initialize run time results vectors
runtime = zeros(architectures,numFrames);
avgtime = zeros(1,architectures);

% Seed the random number generator used for the channel and message
% creation.  This will allow a fair BER comparison between CPU and GPU.
% Cache the original random stream to restore later.

original_rs = RandStream.getGlobalStream;
rs = RandStream.create('mrg32k3a','seed',25);
RandStream.setGlobalStream(rs);

% Loop for each processing unit - CPU and GPU
for ii = 1:architectures
    
    % Do some initial setup for the execution loop
    if (ii == 1)
        arch = 'CPU';
        decoder = decldpc; % Use CPU LDPC Decoder
    else
        arch = 'GPU';
        decoder = gpuLDPCDecoder;% Use GPU LDPC Decoder
    end
    
    % Reset the Error Rate object
    reset(BER);
    
    % Reset the random stream
    reset(rs);
    
    % Notice to the user that DVB-S.2 simulation is beginning.
    fprintf(['\nUsing ' arch '-based LDPC Decoder:\n']);
    dels = repmat('\b',1,fprintf('  Initializing ...'));
    
    
    % Main simulation loop. Run numFrames+1 times and ignore the first
    % frame (which has initialization overhead) for the run time
    % calculation. Use the first run for the BER calculation.
    for rr = 1:(numFrames+1)
        
        % Start timer
        ts = tic;
        
        % ***Create an input Message*** %
        msg = zeros(encbch.MessageLength, 1);
        msg(1:dvb.NumInfoBitsPerCodeword) = ...
            logical(randi([0 1],dvb.NumInfoBitsPerCodeword,1));
        
        % ***Transmit*** %
        bchencOut = encbch(msg);
        ldpcencOut = encldpc(bchencOut);
        xlvrOut = intrlv(ldpcencOut,dvb.InterleaveOrder);
        modOut = pskModulator(xlvrOut);
        
        % ***Corrupt with noise*** %
        chanOut = chan(modOut);
        
        % ***Receive*** %y
        demodOut = pskDemodulator(chanOut);
        dexlvrOut = deintrlv(demodOut,dvb.InterleaveOrder);
        
        % Use whichever LDPC Decoder was set above.
        ldpcdecOut = decoder(dexlvrOut);
        
        bchdecOut = decbch(ldpcdecOut);
        
        % ***Compute BER *** % Calculate BER at output of LDPC, not BCH.
        ber = BER(logical(bchencOut),ldpcdecOut);
        
        % Stop timer
        runtime(ii, rr) = toc(ts);
        
        % Don't report the first frame with the initialization overhead.
        if (rr > 1)
            fprintf(dels);
            newCharsToDelete = fprintf('  Frame %d decode : %.2f sec', ...
                rr-1, runtime(ii,rr));
            dels = repmat('\b',1,newCharsToDelete);
        end
    end % end of running a frame through the DVB-S.2 system.
    
    
    % Report the run time results to the Command Window.
    fprintf(dels); % Delete the last line printed out.
    
    % Calculate the average run time. Don't include frame 1 because it
    % includes some System object initialization time.
    avgtime(ii) = mean(runtime(ii,2:end));
    
    fprintf('  %d frames decoded, %.2f sec/frame\n',numFrames,avgtime(ii));
    fprintf('  Bit error rate: %g \n',ber(1) );
    
end % architecture loop
Using CPU-based LDPC Decoder:
  Initializing ...
  Frame 1 decode : 0.17 sec  Frame 2 decode : 0.17 sec  Frame 3 decode : 0.17 sec  Frame 4 decode : 0.19 sec  Frame 5 decode : 0.15 sec  Frame 6 decode : 0.17 sec  Frame 7 decode : 0.15 sec  Frame 8 decode : 0.17 sec  Frame 9 decode : 0.18 sec  Frame 10 decode : 0.15 sec
  10 frames decoded, 0.17 sec/frame
  Bit error rate: 0.00785634 
Using GPU-based LDPC Decoder:
  Initializing ...
  Frame 1 decode : 0.14 sec  Frame 2 decode : 0.13 sec  Frame 3 decode : 0.13 sec  Frame 4 decode : 0.14 sec  Frame 5 decode : 0.11 sec  Frame 6 decode : 0.13 sec  Frame 7 decode : 0.12 sec  Frame 8 decode : 0.14 sec  Frame 9 decode : 0.13 sec  Frame 10 decode : 0.12 sec
  10 frames decoded, 0.13 sec/frame
  Bit error rate: 0.00785634 
% Reset the random stream to the cached object
RandStream.setGlobalStream(original_rs);

Используя код, аналогичный показанному выше, измерение частоты битовых ошибок было выполнено в автономном режиме. Частота битовых ошибок декодеров LDPC на базе GPU и CPU идентична, как видно на этом графике.

Резюме

Если использовался графический процессор, покажите ускорение на основе среднего времени работы системы DVB-S.2, использующей декодер LDPC графического процессора, по сравнению с декодером LDPC CPU.

if ~doGPU
    fprintf('\n*** GPU not present ***\n\n');
else
    %Calculate system-wide speedup
    fprintf(['\nFull system simulation runs %.2f times faster using ' ...
        'the GPU-based LDPC Decoder.\n\n'],avgtime(1) / avgtime(2));
end
Full system simulation runs 1.32 times faster using the GPU-based LDPC Decoder.

Приложение

В этом примере используется скрипт createSimObjDVBS2Demo.m и вспомогательная функция getParamsDVBS2Demo.m.

Избранная библиография

  1. Стандарт ETSI EN 302 307 V1.1.1: цифровое видеовещание (DVB); Структура кадров второго поколения, системы кодирования и модуляции каналов для вещания, интерактивных услуг, нового сбора и других широкополосных спутниковых приложений (DVB-S.2), Европейский институт телекоммуникационных стандартов, Вальбонн, Франция, 2005-03.