Contenido principal

AI-Native Differentiable 6G Link using Autoencoder

R2026b
Since R2026b

This example implements the differentiable pre-6G physical-layer link as an end-to-end bit-wise autoencoder [1] .

At the transmitter, the encoder network learns constellation shaping to map bits to complex-valued symbols. After transmission through an additive white Gaussian noise (AWGN) channel, the decoder network maps the received symbols to log-likelihood ratio (LLR) values.

In this example, you:

  1. Train an encoder to learn a geometrically shaped constellation.

  2. Train a decoder to demap the learned constellation to log-likelihood ratio (LLR) values.

  3. Compare the block error rate (BLER) performance with that of a baseline 6G link.

Introduction

AI-native differentiable links can improve link performance by replacing selected components with neural networks and jointly optimizing signal representations and detection. 3GPP has studied constellation shaping techniques for potential use in 6G [2], [3]. These techniques include:

  • Geometric constellation shaping (GCS) — Optimizes the positions of constellation points in the I/Q plane.

  • Probabilistic constellation shaping (PCS) — Optimizes the transmission probabilities of constellation points.

For more information about constellation shaping techniques, see Constellation Shaping for 6G.

This example uses neural networks to implement GCS in an end-to-end pre-6G physical-layer link. The encoder maps input bits to complex-valued symbols and learns the constellation geometry. The decoder maps noisy received symbols to log-likelihood ratio (LLR) values. The example jointly trains the encoder and decoder over an additive white Gaussian noise (AWGN) channel using binary cross-entropy (BCE) loss, as shown in the following diagram.

End-to-end 6G autoencoder training diagram showing input bits encoded, passed through an AWGN channel, decoded, and optimized using binary cross-entropy (BCE) loss.

For each simulation iteration, the example:

  1. Generates transport block bits.

  2. Modulates the bits using conventional modulation or the encoder neural network (hAINativeEncoder).

  3. Maps the modulated symbols to the transmit resource grid.

  4. Passes the waveform through an frequency domain AWGN channel at the specified SNR.

  5. Performs perfect channel estimation and minimum mean square error (MMSE) equalization using pre6GPerfectChannelEstimate and pre6GEqualizeMMSE.

  6. Demodulates the equalized symbols using conventional demodulation or the decoder neural network (hAINativeDecoder) to generate per-bit LLR values.

Configure 6G Link

This example builds on the 6G Link-Level Simulation example by replacing conventional symbol modulation and demodulation with encoder and decoder neural networks. The example supports single-layer single-input-single-output (SISO) transmission. Set the batch size equal to the number of slots to process all slots in parallel. Use gpu to control GPU usage during training and inference by setting it to on, off, or auto.

% Parameter setup
simParameters = struct();

% Modulation and coding configuration
simParameters.Modulation = "64QAM";
simParameters.SNRdBMin = 8;
simParameters.SNRdBMax = 11;
simParameters.NSlots = 10;
simParameters.NSizeGrid = 6;
simParameters.SubcarrierSpacing = 15; % in kHz
simParameters.PRGBundleSize = 2;

% Computation on GPU or CPU
simParameters.gpu = "off"; % GPU acceleration

Train Autoencoder

In this section, you create and jointly train the encoder and decoder networks using end-to-end 6G link-level simulations. By default, the encoder initializes the constellation using the standard 3GPP 64-QAM ordering [4] and learns a geometrically shaped constellation. The decoder learns to map received complex-valued symbols to bitwise LLRs. The decoder takes the real and imaginary parts of the received symbols and the noise variance in decibels (dB) as inputs. The example trains both networks using the adamupdate (Deep Learning Toolbox) with a piecewise learning-rate schedule.

In each training iteration, the example:

  1. Samples an SNR uniformly from the range [SNRdBMin, SNRdBMax] and generates data using the end-to-end pre-6G link.

  2. Computes the estimated LLRs and the multilabel BCE loss relative to the transmitted bits.

  3. Jointly updates the learnable parameters of the encoder and decoder networks.

To reduce simulation time and computational complexity, the example models the propagation channel in the frequency domain. After training, the example saves the encoder and decoder networks to ModelPath for evaluation.

Configure Training Parameters

In this section, you configure the autoencoder training parameters. Use NumIterations, LearnRate, LearnRateDropPeriod, and LearnRateDropFactor to configure the Adam optimizer and learning-rate schedule.

Set simParameters.TrainNow to:

  • true — Jointly train the encoder and decoder networks using dlarray data and automatic differentiation. During training, the example bypasses scrambling and descrambling to maintain a differentiable signal path.

  • false — The example runs the complete link-level simulation using either the pretrained encoder and decoder networks or conventional modulation and demodulation. The evaluation includes scrambling, descrambling, channel estimation, and equalization.

% Configure training visualization
simParameters.TrainNow = false;

% Training parameters, ignored if TrainNow is false 
simParameters.MaxIterations = 3000; % training iterations
simParameters.LearnRate = 0.001;
simParameters.LearnRateDropPeriod = 1000;
simParameters.LearnRateDropFactor = 0.8;
simParameters.ModelPath = "trainedAutoencoder.mat"; % path/filename to save the trained model

Training Loop

% Show training loss, encoder constellation, and decoder decision boundaries
simParameters.ShowTrainingPlots = true;

When simParameters.TrainNow and simParameters.ShowTrainingPlots are both true, the example displays:

  • BCE loss as a function of training iteration.

  • The learned constellation, showing the encoder constellation points relative to the reference QAM constellation.

  • The decoder decision regions, showing how the decoder partitions the I/Q plane according to the learned bit labels.

After training, the example saves the encoder and decoder networks to the file specified by simParameters.ModelPath for testing. When simParameters.TrainNow is false, the example skips training and instead loads autoencoder_3k.mat, which contains pretrained encoder and decoder networks trained for 3000 iterations.

Training visualization for a learned 64-QAM autoencoder. The top plot shows the BCE training loss, which drops sharply in the first 150 iterations and then levels off. The bottom-left plot compares the learned constellation with the standard 64-QAM reference grid: the learned points form tight clusters of nearby symbols, and the outermost points move beyond the reference grid. The bottom-right plot shows the corresponding decoder decision regions across the in-phase and quadrature plane.

Train the encoder, encNet, and decoder, decNet, jointly using a custom training loop that minimizes the binary cross-entropy (BCE) loss. At each iteration, randomly select an SNR from [simParameters.SNRdBMin, simParameters.SNRdBMax] and update both networks. Training at low SNRs encourages the encoder to learn a nonuniform constellation that improves noise resilience and reduces block error rate (BLER) after LDPC decoding.

if simParameters.TrainNow
    
    % Training parameter initialization
    iteration = 0;
    maxIterations = simParameters.MaxIterations;
    learnRate = simParameters.LearnRate;
    lrDropPeriod = simParameters.LearnRateDropPeriod;
    lrDropFactor = simParameters.LearnRateDropFactor;
    gradDecay = 0.9;
    sqGradDecay = 0.999;
    epsilon = 1e-8;

    % Configure the carrier, modulation and physical channel parameters for
    % autoencoder training and link-level evaluation
    simParameters = configure6GPhysicalChannel(simParameters);
    
    % Resolve the simulation hardware
    gpu = simParameters.gpu;
    simParameters.ExecEnv = resolveExecutionEnvironment(gpu);

    % Build encoder network
    encNet = dlnetwork([
        inputLayer([simParameters.Ch.Qm NaN], 'CB', 'Name', 'encoder_input')
        constellationEmbeddingLayer(simParameters.NumBitsPerSym,Use3GPPSymbolOrder=true)
        ]);

    % Build decoder network
    decNet = dlnetwork([
        inputLayer([3 NaN], 'CB', 'Name', 'decoder_input')  % [real, imag, N0]
        fullyConnectedLayer(128, 'Name', 'fc1')
        reluLayer('Name', 'relu1')
        fullyConnectedLayer(128, 'Name', 'fc2')
        reluLayer('Name', 'relu2')
        fullyConnectedLayer(simParameters.NumBitsPerSym, 'Name', 'fc3')  % Output LLRs
        ]);
    
    % Print the link level simulation details
    printTrainingSummary(simParameters,encNet,decNet);
    
    % Initialize the training plots
    if simParameters.ShowTrainingPlots
        f = figure(Position=[0 0 960 720]);
        set(f,'Visible','on')
        movegui(f,'center')
        T = tiledlayout(2,2,"TileSpacing","tight");

        % Training loss plot
        ax1 = nexttile([1 2]);
        ax1 = initializeTrainingPlot(ax1);        

        % Encoder constellation plot
        ax2 = nexttile;
        ax2 = initializeConstellationPlot(ax2,simParameters.ModulationOrder);

        % Decoder decision region plot
        ax3 = nexttile;
        ax3 = initializeDecisionBoundariesPlot(ax3,simParameters.ModulationOrder);
    end

    % Training loop
    encAvgGrad = [];
    encAvgSqGrad = [];

    decAvgGrad = [];
    decAvgSqGrad = [];

    while iteration < maxIterations
        
        % Increment the iteration counter
        iteration = iteration + 1;

        % Random SNR selection for the current batch [1-by-B]
        SNRdB = (simParameters.SNRdBMax-simParameters.SNRdBMin).*rand(1,simParameters.BatchSize) + simParameters.SNRdBMin;

        % Calculate gradients and loss
        outputs = dlfeval(@hSimulateConventionalAndAILink,simParameters,SNRdB,Encoder=encNet,Decoder=decNet);
        loss = outputs.Loss;
        encGrads = outputs.EncGrads;
        decGrads = outputs.DecGrads;

        % Adam update (encoder)
        [encNet,encAvgGrad,encAvgSqGrad] = adamupdate(encNet,encGrads,encAvgGrad,encAvgSqGrad,iteration,learnRate,gradDecay,sqGradDecay,epsilon);

        % Adam update (decoder)
        [decNet,decAvgGrad,decAvgSqGrad] = adamupdate(decNet,decGrads,decAvgGrad,decAvgSqGrad,iteration,learnRate,gradDecay,sqGradDecay,epsilon);

        % Piece-wise learning rate
        if mod(iteration,lrDropPeriod) == 0
            learnRate = lrDropFactor*learnRate;
        end
        
        % Update training plot once per iteration
        if simParameters.ShowTrainingPlots
            ax1 = updateTrainingPlot(ax1,iteration,extractdata(loss));            
        end

        % Display progress and update rest of the plots
        if mod(iteration,100) == 0 || iteration == 1 || iteration == maxIterations
            fprintf('Iteration %5d / %d | Learning Rate: %.4f | BCE: %.4f\n',iteration,maxIterations,learnRate,loss);

            % Update training plots
            if simParameters.ShowTrainingPlots
                ax2 = updateConstellationPlot(ax2,iteration,simParameters.ModulationOrder,encNet);
                ax3 = updateDecisionBoundariesPlot(ax3,iteration,simParameters.SNRdBMin,simParameters.SNRdBMax,simParameters.ModulationOrder,decNet);
            end
        end

    end
    
    % Save the model
    save(simParameters.ModelPath,"encNet","decNet")

end

Simulate End-to-End 6G Link

In this section, you evaluate the autoencoder link and compare its performance with the baseline 6G link. The calculateBLER helper function sweeps the SNR values in testParameters.SNRdBVec, runs Monte Carlo trials at each SNR point, and uses a parfor loop to parallelize the simulations (requires Parallel Computing Toolbox™). If Parallel Computing Toolbox™ is unavailable, only one CPU core is available, or the maximum number of workers is set to 0, MATLAB executes the parfor loop serially.

Configure Test Parameters

You can configure the link parameters to test both AI-native autoencoder-based and baseline 6G links.

% Test parameters
testParameters = simParameters;
testParameters.UseParallel = false; % use parallel pool to accelerate
testParameters.SNRdBMin = 8.5;
testParameters.SNRdBMax = 10.5;
testParameters.NumTrialsPerSNRPoint = 100; % Monte Carlo trials per SNR

% SNR vector in dB
testParameters.SNRdBVec = testParameters.SNRdBMin:0.5:testParameters.SNRdBMax;

% Load the trained networks
[encNet,decNet] = loadPretrainedModel(simParameters.ModelPath);

% Fetch the modulation from the pretrained network
testParameters.Modulation = getModulationScheme(encNet.Layers(1).InputSize(1));

Unlike during training, the example can use channel coding during testing.

testParameters.TargetCodeRate = 0.5;
testParameters.MaxLDPCIterations = 12;
testParameters.LDPCDecodingAlgorithm = "Layered belief propagation";

Finally, configure the carrier, modulation, and physical channel parameters used to evaluate both the AI-native and baseline 6G links.

% Set TrainNow to false to test the link after training
testParameters.TrainNow = false;

% Configure the carrier, modulation, and physical channel parameters
testParameters = configure6GPhysicalChannel(testParameters);

Evaluate Autoencoder Performance in 6G Link

The example performs the SNR sweep for two configurations:

  • Benchmark 6G simulation — Uses 3GPP symbol mapping and demapping as specified in TS 38.211 [4].

  • AI-native simulation — Uses the trained encoder and decoder networks for symbol modulation and demodulation.

The example compares the BLER performance of the two configurations as a function of SNR. The autoencoder_3k.mat file contains pretrained encoder and decoder networks for 64-QAM. To evaluate a different modulation order, set simParameters.TrainNow to true to retrain the encoder and decoder networks.

% Simulate the BLER performance of the baseline 6G link
blerRef = calculateBLER(testParameters);
--- Baseline 6G Simulation ---
SNR   8.5 dB: BLER = 1.0000
SNR   9.0 dB: BLER = 1.0000
SNR   9.5 dB: BLER = 0.9820
SNR  10.0 dB: BLER = 0.1460
SNR  10.5 dB: BLER = 0.0040
% Simulate the BLER performance of the AI-native autoencoder link 
blerAI = calculateBLER(testParameters,Encoder=encNet,Decoder=decNet);
--- AI-native Autoencoder Simulation ---
SNR   8.5 dB: BLER = 0.9970
SNR   9.0 dB: BLER = 0.6000
SNR   9.5 dB: BLER = 0.0250
SNR  10.0 dB: BLER = 0.0010
SNR  10.5 dB: BLER = 0.0000

Plot BLER Performance

For the frequency-domain AWGN channel, the autoencoder learns a geometrically shaped constellation that outperforms the conventional 64-QAM baseline. The learned modulation and demodulation mappings provide more reliable soft-bit information to the LDPC decoder, resulting in an SNR gain of approximately 0.7 dB at a given BLER compared with the baseline 6G link.

% Plot the results
figure;
semilogy(testParameters.SNRdBVec,blerRef,'o-',LineWidth=2,MarkerSize=8)
hold on
semilogy(testParameters.SNRdBVec,blerAI,'^-',LineWidth=2,MarkerSize=8)
grid on
xlabel('SNR (dB)')
ylabel('BLER')
legend(["Baseline 6G","AI-Native (autoencoder)"],Location="southwest")
title('BLER Performance: Autoencoder vs. pre6G')
subtitle(sprintf('%s | Code Rate %.4f',testParameters.Modulation, testParameters.TargetCodeRate));

Figure contains an axes object. The axes object with title BLER Performance: Autoencoder vs. pre6G, xlabel SNR (dB), ylabel BLER contains 2 objects of type line. These objects represent Baseline 6G, AI-Native (autoencoder).

References

[1] S. Cammerer, F. A. Aoudia, J. Hoydis, A. Vem, N. Binder, G. Marcus, and A. Keller, “A trainable neural network for constellation shaping and coded modulation,” IEEE Transactions on Wireless Communications, 2022.

[2] vivo, “Discussion on modulation for 6GR air interface,” 3GPP TSG RAN WG1 Meeting #124, Gothenburg, Sweden, R1-2600501, Feb. 9–13, 2026. [Online]. Available: https://www.3gpp.org/ftp/tsg_ran/WG1_RL1/TSGR1_124/Docs/R1-2600501.zip

[3] InterDigital, Inc., “Modulation, joint channel coding and modulation for 6GR air interface,” 3GPP TSG RAN WG1 Meeting #124-bis, St. Julian’s, Malta, R1-2602353, Apr. 13–17, 2026. [Online]. Available: https://www.3gpp.org/ftp/tsg_ran/WG1_RL1/TSGR1_124b/Docs/R1-2602353.zip

[4] 3GPP, NR; Physical Channels and Modulation, 3GPP TS 38.211, Tech. Spec. Group Radio Access Network, Release 18, ver. 18.4.0, 2025. [Online]. Available: https://www.3gpp.org/ftp/Specs/archive/38_series/38.211/38211-j40.zip

Local Functions

function [encNet,decNet] = loadPretrainedModel(modelPath)
    if isfile(modelPath)
        data = load(modelPath);
    else % load the shipped network
        data = load("autoencoder_3k.mat");
    end
    encNet = data.encNet;
    decNet = data.decNet;
end


function mod = getModulationScheme(Qm)
    switch Qm
        case 2
            mod = "QPSK";
        case 4
            mod = "16QAM";
        case 6
            mod = "64QAM";
        case 8
            mod = "256QAM";
        case 10
            mod = "1024QAM";
        case 12
            mod = "4096QAM";
        otherwise
            error("Unsupported modulation format.")
    end
end

function execEnv = resolveExecutionEnvironment(gpu)
    if any(strcmp(gpu,["on","auto"])) && canUseGPU
        execEnv = "GPU";
    else
        execEnv = "CPU";
    end
end

function simParameters = configure6GPhysicalChannel(simParameters)

    % The batch size is fixed to the number of slots in this example,
    % changing the batch size might result in dimension mismatches
    simParameters.BatchSize = simParameters.NSlots;

    % Carrier configuration
    carrier = pre6GCarrierConfig;
    carrier.SubcarrierSpacing = simParameters.SubcarrierSpacing;
    carrier.NSizeGrid = simParameters.NSizeGrid;
    
    % Physical channel configuration
    ch = pre6GPhysicalChannelConfig;
    ch.PRBSet = 0:(carrier.NSizeGrid-1);
    
    % This example supports only single layer SISO configuration
    ch.NumLayers = 1;
    ch.Modulation = simParameters.Modulation;
    ch.SymbolAllocation = [0 carrier.SymbolsPerSlot];
    chextra = struct;
    chextra.PRGBundleSize = simParameters.PRGBundleSize;
    
    % This example does not support hybrid automatic repeat request (HARQ),
    % HARQ processes are disabled during training and testing
    chextra.EnableHARQ = false;
    chextra.NHARQProcesses = 1;

    % Channel coding configuration
    if simParameters.TrainNow
        chextra.EnableCoding = false;
    else
        chextra.EnableCoding = true; % channel coding is always enabled during testing
        chextra.TargetCodeRate = simParameters.TargetCodeRate;
    end
    simParameters.NumBitsPerSym = ch.Qm;
    simParameters.ModulationOrder = 2^ch.Qm;
    simParameters.Carrier = carrier;
    simParameters.Ch = ch;
    simParameters.ChExtra = chextra;
    [~,chIndicesInfo] = pre6GPhysicalChannelIndices(carrier,ch,UseGPU=simParameters.gpu);
    simParameters.CWLength = chIndicesInfo.G;
end

function printTrainingSummary(simParameters,encNet,decNet)
    encParams = sum(cellfun(@(X) numel(X),encNet.Learnables.Value));
    decParams = sum(cell2mat(cellfun(@(X) numel(X),decNet.Learnables(decNet.Learnables.Parameter == "Weights",:).Value,'UniformOutput',false))); % weights
    decParams = decParams + sum(cellfun(@(X) numel(X),decNet.Learnables(decNet.Learnables.Parameter == "Bias",:).Value)); % biases
    
    fprintf('\n');
    fprintf('Autoencoder Training\n');
    fprintf('--------------------\n');
    fprintf('Training hardware          : %s\n',simParameters.ExecEnv);
    fprintf('Training Iterations        : %d\n',simParameters.MaxIterations);
    fprintf('Encoder learnables         : %g\n',encParams);
    fprintf('Decoder learnables         : %.1fk\n',decParams/1e3);
    fprintf('SNR range                  : %.1f to %.1f dB\n',simParameters.SNRdBMin,simParameters.SNRdBMax);
    fprintf('Channel Profile            : AWGN\n');
    fprintf('Trainable Constellation    : %s (%d bits per symbol)\n',simParameters.Modulation,simParameters.NumBitsPerSym);
    fprintf('Codeword length            : %d bits (%d symbols)\n',simParameters.CWLength,simParameters.CWLength/simParameters.NumBitsPerSym);
    fprintf('Batch size                 : %d\n',simParameters.BatchSize);
    fprintf('\n');
end

% Training plot
function ax = initializeTrainingPlot(ax)
    titleTrainPlot = "Training Progress Plot";
    semilogy(ax,NaN,NaN,LineWidth=2,DisplayName="Training Loss");
    xlabel(ax,"Iterations");
    ylabel(ax,"BCE Loss");
    grid(ax,"on");
    legend(ax,Location="northeast");
    title(ax,titleTrainPlot);
    ax.UserData = titleTrainPlot; % save the title
end

function ax = updateTrainingPlot(ax,iter,loss)
    objHandle = findobj(ax,DisplayName='Training Loss');
    objHandle.XData(end+1) = iter;
    objHandle.YData(end+1) = loss;
    title(ax,ax.UserData + sprintf(' (Iteration %d)',iter));
    drawnow
end

% Constellation plot
function ax = initializeConstellationPlot(ax,modulationOrder)
    if modulationOrder == 4
        titleEncPlot = sprintf("Learned QPSK");
    else
        titleEncPlot = sprintf("Learned %d-QAM",modulationOrder);
    end
    qamRef = qammod((0:modulationOrder-1).',modulationOrder,UnitAveragePower=true);
    plot(ax,real(qamRef),imag(qamRef),'x',MarkerSize=10,LineWidth=2,DisplayName="QAM Reference");
    hold(ax,"on");
    plot(ax,NaN,NaN,'o',MarkerSize=7,LineWidth=1.5,DisplayName="Autoencoder");
    hold(ax,"off");
    axis(ax,"equal");
    grid(ax,"on");
    xlim(ax,[-2 2]);
    ylim(ax,[-2 2]);
    xlabel(ax,'In-Phase');
    ylabel(ax,'Quadrature');
    legend(ax,Location="southoutside");
    title(ax,titleEncPlot);
    ax.UserData = titleEncPlot; % save the title
end

function ax = updateConstellationPlot(ax,iter,modulationOrder,encNet)
    objHandle = findobj(ax,DisplayName="Autoencoder");
    pts = getConstellationPoints(modulationOrder,encNet);
    set(objHandle,XData=real(pts),YData=imag(pts));
    title(ax,ax.UserData + sprintf(" (Iteration %d)",iter));
    drawnow
end

% Decision boundaries plot
function ax = initializeDecisionBoundariesPlot(ax,modulationOrder)
    colormap("jet");
    if modulationOrder == 4
        titleDecPlot = sprintf("QPSK Decision Regions");
    else
        titleDecPlot = sprintf("%d-QAM Decision Regions",modulationOrder);
    end
    x = linspace(-2,2,100);
    y = linspace(-2,2,100);
    X = meshgrid(x,y);
    imagesc(ax,x,y,X);
    axis(ax,"xy");
    axis(ax,"tight");
    axis(ax,"equal");
    xticks(ax,-2:0.5:2);
    yticks(ax,-2:0.5:2);
    grid(ax,"on");
    xlabel(ax,"In-Phase");
    ylabel(ax,"Quadrature");
    title(ax,titleDecPlot);
    ax.UserData = titleDecPlot; % save the title
end

function ax = updateDecisionBoundariesPlot(ax,iter,SNRdBMin,SNRdBMax,modulationOrder,decNet)
    objHandle = findobj(ax,'-property','CData');
    dec = gather(extractdata(getDecisionBoundaries(mean([SNRdBMin SNRdBMax]),log2(modulationOrder),decNet)));
    set(objHandle,"CData",dec)
    colorbar(ax,Ticks=unique(dec),FontSize=7)
    title(ax,ax.UserData + sprintf(" (Iteration %d)",iter));
    drawnow
end

% Get the required points/boundaries for the plots
function pts = getConstellationPoints(modulationOrder,encNet)
    % Obtain the encoder mapping rule for plotting
    nBitsPerSym = log2(modulationOrder);
    b = de2bi(0:modulationOrder-1,nBitsPerSym,"left-msb").';
    pts = gather(extractdata(predict(encNet,dlarray(b,'CB'))));
    pts = complex(pts(1,:),pts(2,:));
end

function dec = getDecisionBoundaries(SNRdBMean,Qm,decNet)
    % Obtain the decoder demapping decision boundaries for plotting
    x = linspace(-2,2,100);
    y = linspace(-2,2,100);
    [X,Y] = meshgrid(x,y);
    symReal = reshape(X,1,[]);
    symImag = reshape(Y,1,[]);
    
    % Calculate a representative noise power in Bel (B)
    % Note that the transmit/receive symbols are normalized power. Thus,
    % nvar = 1/SNR = 10^-(SNRdB/10)
    nvarBel = repmat(-(SNRdBMean/10),size(symReal));

    % Prediction
    features = cat(1,symReal,symImag,nvarBel);
    llr = extractdata(-predict(decNet,features));
    dec = reshape(bit2int(llr < 0,Qm),numel(x),[]);
end

function bler = calculateBLER(simParameters,opts)
    arguments
        simParameters
        opts.Encoder = []
        opts.Decoder = []
    end

    simParameters.TrainNow = false; % testing
    gpu = simParameters.gpu;
    ch = simParameters.Ch;
    numTrials = simParameters.NumTrialsPerSNRPoint;
    encNet = opts.Encoder;
    decNet = opts.Decoder;
    numSNR = length(simParameters.SNRdBVec);
    bler = zeros(numSNR,1);
    
    % Validate the trained network input size against Qm, if applicable
    if ~isempty(encNet)
        assert(encNet.Layers(1).InputSize(1) == ch.Qm, "Modulation order must match the input size expected by the trained encoder network.")
    end

    % Set the random CPU stream for reproducibility
    streamConst = parallel.pool.Constant(RandStream("Threefry",Seed=42));

    % Configure the parallel pool before the SNR loop, if a pool exists use
    % it
    pool = hCreateParallelPool(simParameters.UseParallel); 
    
    % Progress header
    if (isempty(opts.Encoder) && isempty(opts.Decoder))
        fprintf('\n--- Baseline 6G Simulation ---\n');
    else
        fprintf('\n--- AI-native Autoencoder Simulation ---\n');
    end

    % SNR loop
    for ind = 1:numSNR
        numBlkErrLocal = 0;
        numBlksLocal = 0;
        SNRdB = simParameters.SNRdBVec(ind);

        % Monte Carlo trials loop
        parfor (mc = 1:numTrials,pool.NumWorkers)

            % CPU random stream
            stream = streamConst.Value;
            stream.Substream = mc;
            RandStream.setGlobalStream(stream);

            % GPU random stream
            if any(strcmp(gpu,["on","auto"])) && canUseGPU
                gpuStream = parallel.gpu.RandStream.create("Threefry",Seed=42,NumStreams=numTrials,StreamIndices=mc);
                parallel.gpu.RandStream.setGlobalStream(gpuStream);
            end

            % Link simulation
            outputs = hSimulateConventionalAndAILink(simParameters,SNRdB,Encoder=encNet,Decoder=decNet);

            % Calculate block errors
            numBlkErrLocal = numBlkErrLocal + sum(outputs.BlkErr);
            numBlksLocal = numBlksLocal + simParameters.BatchSize;
        end

        % Calculate BLER
        bler(ind) = numBlkErrLocal / numBlksLocal;

        % Display progress
        fprintf('SNR %5.1f dB: BLER = %6.4f\n',SNRdB, bler(ind));
    end
end

See Also

|

Topics