exponenta event banner

Оптимизация типов данных для FPGA с фрагментами DSP

В этом примере показано, как использовать addSpecification способ fxpOptimizationOptions класс для достижения лучшего отображения блоков продуктов на срезах DSP для целей FPGA. Использовать addSpecification для указания известных типов данных в системе. После задания этих известных параметров при оптимизации типов данных в системе процесс оптимизации не изменяет указанный тип данных параметра блока.

Многие платы FPGA имеют специальные аппаратные ускорители многократного накопления, называемые срезами DSP, которые ускоряют выполнение функций обработки сигналов. Размеры фрагментов DSP зависят от поставщика. Для получения преимуществ аппаратного ускорения фрагментов DSP в конструкции FPGA обычно сопоставляют операции умножения и накопления в алгоритме с этими фрагментами.

В этом примере оптимизируйте типы данных для 3 семейств DSP плат Xilinx ®, а также для общего ввода 18x18 бит. Используйте addSpecification способ для достижения хорошего отображения между блоками продукта в конструкции и целевыми фрагментами DSP.

В этом примере приводятся следующие предположения:

  1. Только блоки Product и Gain предназначены для отображения на срезы DSP. Вы можете обрабатывать другие блоки аналогичным образом.

  2. Блоки продуктов имеют только 2 входа.

  3. Блоки драйверов (блоки, которые предшествуют блокам Product или Gain) имеют OutDataTypeStr в качестве параметра.

  4. Только блоки, для которых не установлено свойство HDL DSPStyle off являются целевыми.

Измерить диапазоны модели и сбора

Для начала откройте систему, для которой требуется оптимизировать типы данных. В этом примере типы данных оптимизированы для автоматического алгоритма регулировки усиления.

model = 'mQAMAGC';
sud = [model '/Automatic Gain Control'];
open_system(model);

Инициализируйте подсистему QAM Tx.

initQAM;

Создайте структурный массив, описывающий свойства целевого фрагмента DSP. dspStyle функция, включенная в этот пример, предоставляет информацию об общих фрагментах DSP Xilinx ®, включая DSP48A1 (18x18 бит), DSP48E1 (18x25 бит) и DSP48E2 (18x27 бит). Он также предоставляет пример общего фрагмента DSP с подписью 18x18.

dspStyle = getDSPStyle('DSP48E2');

В этом примере только блоки Product и Gain предназначены для отображения на фрагменты DSP. Найдите все блоки Product и Gain в проектируемой системе, для которых свойство блока HDL DSPStyle не имеет значения off. Для получения дополнительной информации см. DSPStyle (кодер HDL).

productBlocks = find_system(sud,'LookUnderMasks','on','BlockType','Product');
hasDSPOff = cellfun(@(x)(isequal(hdlget_param(x,'DSPStyle'),'off')), productBlocks);
productDSP = productBlocks(~hasDSPOff);

gainBlocks = find_system(sud,'LookUnderMasks','on','BlockType','Gain');
hasDSPOff = cellfun(@(x)(isequal(hdlget_param(x,'DSPStyle'),'off')), productBlocks);
gainDSP = gainBlocks(~hasDSPOff);

Включите инструментарий для регистрации минимальных, максимальных и переполненных данных во время моделирования для блоков продуктов и блоков драйверов, которые предшествуют блокам продуктов. Моделирование модели для сбора диапазонов.

c = DataTypeWorkflow.Converter(sud,'TopModel',model);
c.CurrentRunName = 'RangeCollection';
c.simulateSystem('MinMaxOverflowLogging','MinMaxAndOverflow');

Получение спецификаций для блоков продуктов

Для эффективного сопоставления блоков продукта с доступными фрагментами DSP следует учитывать требования к диапазону блоков продукта. Создайте структурный массив для хранения минимальных и максимальных значений моделирования для блоков продуктов, собранных во время выполнения сбора диапазонов.

specs = struct('Block',productDSP{1},'Drivers',[],'Min',[],'Max',[]); %#ok<*SAGROW>
r = c.results(c.CurrentRunName,@(x)(strcmp(x.ResultName,productDSP{1})));
specs.Min = r.SimMin;
specs.Max = r.SimMax;
predecessorBlocks = predecessors(productDSP{1});
for pIndex = 1:numel(predecessorBlocks)
    pBlkObj = get_param(predecessorBlocks{pIndex},'Object');
    specs.Drivers(pIndex) = pBlkObj.Handle;
    r = c.results(c.CurrentRunName,@(x)(strcmp(x.ResultName,pBlkObj.getFullName())));
    specs.Min(pIndex+1) = r.SimMin;
    specs.Max(pIndex+1) = r.SimMax;
end

Храните эти известные спецификации параметров для блоков продуктов в Simulink.Simulation.BlockParameter объект.

bpProductBlock = Simulink.Simulation.BlockParameter.empty(0,3);

fout = fi(max([abs(specs.Min(1)) abs(specs.Max(1))]),dspStyle.sout,dspStyle.wout);
bpProductBlock(1) = Simulink.Simulation.BlockParameter(specs.Block, ...
    'OutDataTypeStr', ...
    sprintf('fixdt(%i,%i,%i)',dspStyle.sout,dspStyle.wout,fout.FractionLength));

Назначьте наибольший тип наибольшему диапазону блоков драйверов. Это гарантирует, что наибольший тип данных, доступный в целевом оборудовании, будет применен к блоку с наибольшим требованием диапазона.

dMax1 = max([abs(specs.Min(2)) abs(specs.Max(2))]);
dMax2 = max([abs(specs.Min(3)) abs(specs.Max(3))]);
if dMax1 < dMax2
    win_1 = dspStyle.win_1;
    sin_1 = dspStyle.sin_1;
    win_2 = dspStyle.win_2;
    sin_2 = dspStyle.sin_2;
    if dspStyle.win_1 >= dspStyle.win_2
        win_1 = dspStyle.win_2;
        sin_1 = dspStyle.sin_2;
        win_2 = dspStyle.win_1;
        sin_2 = dspStyle.sin_1;
    end
else
    win_1 = dspStyle.win_2;
    sin_1 = dspStyle.sin_2;
    win_2 = dspStyle.win_1;
    sin_2 = dspStyle.sin_1;
    if dspStyle.win_1 >= dspStyle.win_2
        win_1 = dspStyle.win_1;
        sin_1 = dspStyle.sin_1;
        win_2 = dspStyle.win_2;
        sin_2 = dspStyle.sin_2;
    end
end

Получение спецификаций для блоков, предшествующих блокам продукта. Обратите внимание, что в этом примере предполагается, что блоки продукта имеют два входа.

fin1 = fi(dMax1, sin_1, win_1);
blkObj = get_param(specs.Drivers(1), 'Object');
bpProductBlock(2) = Simulink.Simulation.BlockParameter(blkObj.getFullName, ...
    'OutDataTypeStr', ...
    sprintf('fixdt(%i, %i, %i)', sin_1, win_1, fin1.FractionLength));

fin2 = fi(dMax2, sin_2, win_2);
blkObj = get_param(specs.Drivers(2), 'Object');
bpProductBlock(3) = Simulink.Simulation.BlockParameter(blkObj.getFullName, ...
    'OutDataTypeStr', ...
    sprintf('fixdt(%i, %i, %i)', sin_2, win_2, fin2.FractionLength));

Получение спецификаций для блоков усиления

Сохранение известных спецификаций параметров для блоков усиления в Simulink.Simulation.BlockParameter объект.

bpGainBlock = Simulink.Simulation.BlockParameter.empty(0,3);
specs = struct('Block',gainDSP{1},'Drivers',[],'Min',[],'Max',[]); %#ok<*SAGROW>
r = c.results(c.CurrentRunName,@(x)(strcmp(x.ResultName,gainDSP{1})));
specs.Min = r.SimMin;
specs.Max = r.SimMax;
predecessorBlocks = predecessors(gainDSP{1});
pBlkObj = get_param(predecessorBlocks{1},'Object');
specs.Drivers(1) = pBlkObj.Handle;
r = c.results(c.CurrentRunName,@(x)(strcmp(x.ResultName,pBlkObj.getFullName())));
specs.Min(2) = r.SimMin;
specs.Max(2) = r.SimMax;

Получение спецификаций для вывода блоков усиления.

fout = fi(max(abs([specs.Min(1) specs.Max(1)])),dspStyle.sout,dspStyle.wout);
bpGainBlock(1) = Simulink.Simulation.BlockParameter(gainDSP{1}, ...
    'OutDataTypeStr', ...
    sprintf('fixdt(%i, %i, %i)',dspStyle.sout,dspStyle.wout,fout.FractionLength));

Получите спецификации для блоков, предшествующих блокам Gains, и назначьте их первой конфигурации Simulink.Simulation.BlockParameter объект bpGainBlock.

blkObj = get_param(specs.Drivers(1),'Object');
fin = fi(max(abs([specs.Min(2) specs.Max(2)])),dspStyle.sin_1,dspStyle.win_1);
bpGainBlock(2) = Simulink.Simulation.BlockParameter(blkObj.getFullName, ...
    'OutDataTypeStr', ...
    sprintf('fixdt(%i,%i,%i)',dspStyle.sin_1,dspStyle.win_1,fin.FractionLength));

Получите спецификации для параметра Gain проектируемой системы и присвойте это значение второй конфигурации bpGainBlock.

paramValue = str2double(get_param(sud,'AGC_Gain'));
fParam = fi(paramValue,dspStyle.sin_2,dspStyle.win_2);
bpGainBlock(3) = Simulink.Simulation.BlockParameter(gainDSP{1}, ...
    'ParamDataTypeStr', ...
    sprintf('fixdt(%i,%i,%i)',dspStyle.sin_2,dspStyle.win_2,fParam.FractionLength));

Определение ограничений и допусков

Создание fxpOptimizationOptions объект для определения зависимостей и допусков. Укажите допустимую длину слова от 8 бит до 32 бит.

options = fxpOptimizationOptions('AllowableWordLengths',8:2:32);

Используйте addTolerance метод определения допусков для различий между исходным поведением системы и поведением с использованием оптимизированных типов данных с фиксированной точкой.

addTolerance(options,sud,1,'RelTol',1e-2);
addTolerance(options,sud,2,'RelTol',1e-2);
addTolerance(options,sud,1,'AbsTol',1e-3);
addTolerance(options,sud,2,'AbsTol',1e-3);

Используйте addSpecification метод определения спецификаций для блоков Product и Gain.

addSpecification(options,'BlockParameter',bpProductBlock); % set the specifications for the product block
addSpecification(options,'BlockParameter',bpGainBlock); % set the specifications for the gain block
showSpecifications(options);
    Index          Name                            BlockPath                            Value       
    _____    ________________    _____________________________________________    __________________

      1      OutDataTypeStr      mQAMAGC/Automatic Gain Control/LoopGain          'fixdt(1, 45, 53)'
      2      ParamDataTypeStr    mQAMAGC/Automatic Gain Control/LoopGain          'fixdt(1,27,35)'  
      3      OutDataTypeStr      mQAMAGC/Automatic Gain Control/LoopGainDriver    'fixdt(1,18,16)'  
      4      OutDataTypeStr      mQAMAGC/Automatic Gain Control/Product           'fixdt(1,45,43)'  
      5      OutDataTypeStr      mQAMAGC/Automatic Gain Control/ProductDriverA    'fixdt(1, 27, 25)'
      6      OutDataTypeStr      mQAMAGC/Automatic Gain Control/ProductDriverB    'fixdt(1, 18, 17)'

Оптимизация типов данных с фиксированной точкой

Используйте fxpopt для выполнения оптимизации. Программное обеспечение анализирует диапазоны объектов в проектируемой системе и ограничения, указанные в fxpOptimizationOptions объект для применения разнородных типов данных к системе при минимизации общей ширины битов. Известные характеристики параметров, включенные с помощью addSpecification на метод не влияет процесс оптимизации.

result = fxpopt(model,sud,options);
	+ Starting data type optimization...
	+ Checking for unsupported constructs.
	+ Preprocessing
	+ Modeling the optimization problem
		- Constructing decision variables
	+ Running the optimization solver
		- Evaluating new solution: cost 200, does not meet the behavioral constraints.
		- Evaluating new solution: cost 250, does not meet the behavioral constraints.
		- Evaluating new solution: cost 300, does not meet the behavioral constraints.
		- Evaluating new solution: cost 350, does not meet the behavioral constraints.
		- Evaluating new solution: cost 400, does not meet the behavioral constraints.
		- Evaluating new solution: cost 450, does not meet the behavioral constraints.
		- Evaluating new solution: cost 500, meets the behavioral constraints.
		- Updated best found solution, cost: 500
		- Evaluating new solution: cost 494, meets the behavioral constraints.
		- Updated best found solution, cost: 494
		- Evaluating new solution: cost 492, meets the behavioral constraints.
		- Updated best found solution, cost: 492
		- Evaluating new solution: cost 490, does not meet the behavioral constraints.
		- Evaluating new solution: cost 486, does not meet the behavioral constraints.
		- Evaluating new solution: cost 490, meets the behavioral constraints.
		- Updated best found solution, cost: 490
		- Evaluating new solution: cost 488, meets the behavioral constraints.
		- Updated best found solution, cost: 488
		- Evaluating new solution: cost 478, meets the behavioral constraints.
		- Updated best found solution, cost: 478
		- Evaluating new solution: cost 474, meets the behavioral constraints.
		- Updated best found solution, cost: 474
		- Evaluating new solution: cost 470, meets the behavioral constraints.
		- Updated best found solution, cost: 470
		- Evaluating new solution: cost 466, meets the behavioral constraints.
		- Updated best found solution, cost: 466
		- Evaluating new solution: cost 462, meets the behavioral constraints.
		- Updated best found solution, cost: 462
		- Evaluating new solution: cost 458, meets the behavioral constraints.
		- Updated best found solution, cost: 458
		- Evaluating new solution: cost 452, meets the behavioral constraints.
		- Updated best found solution, cost: 452
		- Evaluating new solution: cost 450, meets the behavioral constraints.
		- Updated best found solution, cost: 450
		- Evaluating new solution: cost 448, does not meet the behavioral constraints.
		- Evaluating new solution: cost 444, does not meet the behavioral constraints.
		- Evaluating new solution: cost 448, meets the behavioral constraints.
		- Updated best found solution, cost: 448
		- Evaluating new solution: cost 446, meets the behavioral constraints.
		- Updated best found solution, cost: 446
		- Evaluating new solution: cost 436, meets the behavioral constraints.
		- Updated best found solution, cost: 436
		- Evaluating new solution: cost 432, meets the behavioral constraints.
		- Updated best found solution, cost: 432
		- Evaluating new solution: cost 428, meets the behavioral constraints.
		- Updated best found solution, cost: 428
		- Evaluating new solution: cost 424, meets the behavioral constraints.
		- Updated best found solution, cost: 424
		- Evaluating new solution: cost 420, meets the behavioral constraints.
		- Updated best found solution, cost: 420
		- Evaluating new solution: cost 416, meets the behavioral constraints.
		- Updated best found solution, cost: 416
		- Evaluating new solution: cost 410, meets the behavioral constraints.
		- Updated best found solution, cost: 410
		- Evaluating new solution: cost 408, meets the behavioral constraints.
		- Updated best found solution, cost: 408
		- Evaluating new solution: cost 406, does not meet the behavioral constraints.
		- Evaluating new solution: cost 402, does not meet the behavioral constraints.
		- Evaluating new solution: cost 406, meets the behavioral constraints.
		- Updated best found solution, cost: 406
		- Evaluating new solution: cost 404, meets the behavioral constraints.
		- Updated best found solution, cost: 404
		- Evaluating new solution: cost 394, meets the behavioral constraints.
		- Updated best found solution, cost: 394
		- Evaluating new solution: cost 390, meets the behavioral constraints.
		- Updated best found solution, cost: 390
		- Evaluating new solution: cost 386, meets the behavioral constraints.
		- Updated best found solution, cost: 386
		- Evaluating new solution: cost 382, meets the behavioral constraints.
		- Updated best found solution, cost: 382
		- Evaluating new solution: cost 378, meets the behavioral constraints.
		- Updated best found solution, cost: 378
		- Evaluating new solution: cost 374, meets the behavioral constraints.
		- Updated best found solution, cost: 374
		- Evaluating new solution: cost 368, does not meet the behavioral constraints.
		- Evaluating new solution: cost 372, meets the behavioral constraints.
		- Updated best found solution, cost: 372
		- Evaluating new solution: cost 370, does not meet the behavioral constraints.
		- Evaluating new solution: cost 366, does not meet the behavioral constraints.
		- Evaluating new solution: cost 370, meets the behavioral constraints.
		- Updated best found solution, cost: 370
		- Evaluating new solution: cost 368, meets the behavioral constraints.
		- Updated best found solution, cost: 368
		- Evaluating new solution: cost 358, does not meet the behavioral constraints.
		- Evaluating new solution: cost 364, meets the behavioral constraints.
		- Updated best found solution, cost: 364
		- Evaluating new solution: cost 360, meets the behavioral constraints.
		- Updated best found solution, cost: 360
		- Evaluating new solution: cost 356, meets the behavioral constraints.
		- Updated best found solution, cost: 356
		- Evaluating new solution: cost 352, meets the behavioral constraints.
		- Updated best found solution, cost: 352
		- Evaluating new solution: cost 348, meets the behavioral constraints.
		- Updated best found solution, cost: 348
		- Evaluating new solution: cost 342, does not meet the behavioral constraints.
	+ Optimization has finished.
		- Neighborhood search complete.
		- Maximum number of iterations completed.
	+ Fixed-point implementation that satisfies the behavioral constraints found. The best found solution is applied on the model.
		- Total cost: 348
		- Maximum absolute difference: 0.006126
		- Use the explore method of the result to explore the implementation.

Используйте explore способ OptimizationResult объект, resultдля запуска инспектора данных моделирования и изучения конструкции.

explore(result)
ans = 

  OptimizationSolution with properties:

             Cost: 348
             Pass: 1
    MaxDifference: 0.0061
            RunID: 21632
          RunName: {'solution_61d4a5478350738e21dfd31a47760c2cbf2e4794_1'}