Offline CSI Feedback Training in Python with MATLAB Data Generation
R2026bThis example shows how to generate realistic 5G NR channel state information (CSI) data in MATLAB® and use it to train a PyTorch® autoencoder for CSI feedback compression in Python®. The workflow uses the MATLAB Engine API for Python to run MATLAB and use 5G Toolbox™ software to generate the channel data. The generated channel data is passed to Python to train a PyTorch based CSI feedback neural network. Predictions are passed to MATLAB to compute performance metrics.
In this example, you:
Connect Python to MATLAB using the MATLAB Engine API.
Generate and prepare realistic 5G NR channel data using the CDL channel object of 5G Toolbox.
Train a CLNet autoencoder in PyTorch for CSI compression using the generated data.
Evaluate the trained network and compute performance metrics (NMSE, correlation) in MATLAB.

Before running this example, install the MATLAB Engine API for Python as described in Get Started with MATLAB Engine API for Python.
Share MATLAB Engine
You can connect to an existing MATLAB session or start a new one from Python. To make an existing MATLAB session available to Python, set shareMATLABSession to true, which calls the matlab.engine.shareEngine function.
shareMATLABSession =true; if shareMATLABSession if matlab.engine.isEngineShared fprintf('MATLAB session already shared: %s\n', matlab.engine.engineName); else matlab.engine.shareEngine; fprintf('MATLAB session is now shared\n'); end end
MATLAB session already shared: MATLAB_34688
In the Python script, use matlab.engine.connect_matlab to connect to the shared MATLAB session. Connecting to a shared session lets you analyze variables directly in the MATLAB workspace while the Python script runs. The shared session remains available until you close MATLAB.
The following workflow assumes you shared your MATLAB session. To launch a new MATLAB session from the Python script, see Get Started with MATLAB Engine API for Python.
Run Python Script
The csi_feedback_offline_training.py script implements the complete workflow for offline training of the CSI feedback compression model by calling MATLAB in Python. The following sections in the example explain each step of this workflow in detail. Ensure the libraries listed in the requirements_csi_feedback.txt file are installed. For more information, see Install and Configure Python for Use in MATLAB.
After you start a shared session and configure Python, execute the Python script from the terminal where your Python environment is set up:
python csi_feedback_offline_training.py
The Python script calls MATLAB to generate the whole data set and trains the PyTorch neural network.
Required Python Libraries
The Python script imports the libraries listed in requirements_csi_feedback.txt file and the following modules for MATLAB integration:
import matlab import matlab.engine import csi_feedback_wrapper
The imported libraries include:
matlab: A Python package installed as part of the MATLAB Engine API. It provides data types compatible with MATLAB (such asmatlab.double) that let you pass data between Python and MATLAB.matlab.engine: A submodule of the MATLAB package. It provides the MATLAB Engine API functions to start, connect, and communicate with MATLAB sessions from Python.csi_feedback_wrapper: A custom Python module that defines functions for constructing, training, and evaluating the CLNet model
Neural Network Training Parameters
The Python script sets the neural network, training, and data preprocessing parameters. The split_ratio variable defines how the generated data is divided into training, validation and test sets.
# shared MATLAB Engine session
share_MATLAB_session = True
# Model and training configuration
autoencoder_network = "CLNet"
compression_factor = 16 # CSI compression ratio
num_samples = 1500 # Number of channel realizations
initial_learning_rate = 1e-4 # Learning rate
max_epochs = 2 # Training epochs (set to 2 for faster
# execution; increase to ensure complete
# training of the network)
mini_batch_size = 1000 # Batch size
# Data preprocessing configuration
split_ratio = [10, 3, 2] # Train:Valid:Test ratio
Connection to MATLAB Engine
The Python script connects to the shared MATLAB session, if share_MATLAB_session is set to True, with the following code:
print("Connecting to MATLAB Engine...")
eng = matlab.engine.connect_matlab()
If you have not shared a MATLAB session, the Python script uses the following code to a launch a new MATLAB session:
print("Starting a MATLAB Engine...")
eng = matlab.engine.start_matlab("-nodesktop")
The current directory is added to MATLAB search path with the following code:
eng.addpath(os.getcwd())
Ensure the shareMATLABSession variable in MATLAB and the share_MATLAB_session variable in Python are both set to true for connecting Python to the shared MATLAB session.
5G NR Channel Data Generation
The Python script calls the MATLAB helper function hCSIPrepareSplits to generate and preprocess channel state estimations for training. You can edit the parameters inside hCSIPrepareSplits helper function to customize the channel, carrier, and data generation parameters.
print(f"Generating and splitting {num_samples} samples in MATLAB ...")
# Generate and prepare Data
HTrain, HValid, HTest, inputLayerSize = eng.hCSIPrepareSplits(
num_samples,
matlab.double(split_ratio),
nargout=4
)
The hCSIPrepareSplits function performs the following operations:
Configures a 5G NR carrier with CDL-C channel model.
Generates channel realizations using parallel processing.
Computes perfect channel estimates for ground truth.
Preprocesses the data (truncation, normalization).
Splits data into training, validation, and test sets.
The returned data has the format [maxDelay, nTx, 2, nSamples] where the third dimension represents real and imaginary components stored separately. For details on the data generation and preprocessing steps, see Preprocess Data for AI-Based CSI Feedback Compression.
Neural Network Architecture
The script initializes the neural network model based on the configured parameters by using the csi_feedback_wrapper.py file. For more details on the PyTorch wrapper file, see Offline Training and Testing of PyTorch Model for CSI Feedback Compression.
input_layer_size = np.array(inputLayerSize, dtype=np.int64).squeeze() model = csi_feedback_wrapper.construct_model(autoencoder_network,input_layer_size,int(compression_factor))
The model uses an autoencoder architecture with an encoder (at the user equipment) and decoder (at the base station) to compress and reconstruct the CSI.
Neural Network Training
The Python script trains the PyTorch autoencoder using the data set generated in MATLAB:
trained_net, training_loss, validation_loss = csi_feedback_wrapper.train(model,HTrain, HValid, HTest,float(initial_learning_rate),int(max_epochs),int(mini_batch_size))
The MATLAB arrays are passed directly to the Python wrapper function, which handles the necessary data type conversions and calls the training loop function of the trainer. The autoencoder is trained to minimize the reconstruction error (NMSE) between the input and reconstructed channel estimates. The function returns the trained network, and the training and validation losses.
Inference
The Python script uses the generated test set to compute inference from the trained model using the predict function.
HPred = np.asarray(csi_feedback_wrapper.predict(trained_net, HTest),dtype=np.float32)
Performance Metrics Evaluation
The Python script calls the hCSIComputeMetrics helper function to evaluate the correlation and normalized mean squared error (NMSE) between the input and output of the autoencoder network.
mean_nmse, mean_rho = eng.hCSIComputeMetrics(
HTest,
HPred,
nargout=2
)
eng.workspace['meanNMSE'] = mean_nmse
eng.workspace['meanRho'] = mean_rho
For more details on the computation of correlation and NMSE, see the Offline Training and Testing of PyTorch Model for CSI Feedback Compression.
Saving The Trained Network
The Python script saves the trained model in a .pt file with configuration metadata for future use.
checkpoint_name = f"{autoencoder_network}{compression_factor}"
csi_feedback_wrapper.save(trained_net,checkpoint_name,autoencoder_network,input_layer_size,int(compression_factor))
The checkpoint includes the model state dictionary (all learned weights and biases) and configuration metadata for reproducibility.
Helper Functions and PyTorch Wrapper Template
helper3GPPChannelRealizations.mhelperComplexCosineSimilarity.mhCSIComputeMetrics.mhelperCSINMSELossdB.mhCSIPrepareSplits.mhelperCSISplitData.mhelperPreprocess3GPPChannelData.mhelperNMSE.mrequirements_csi_feedback.txtCSIFeedback.pyclnet.pycsi_feedback_wrapper.pycsi_feedback_offline_training.py
For details on the PyTorch wrapper template, see the Offline Training and Testing of PyTorch Model for CSI Feedback Compression example.
Further Exploration
For the inverse workflow (calling Python from MATLAB), see:
For more information about CSI feedback compression and AI in wireless communications, see:
References
[1] Ji, Sijie, and Mo Li. "CLNet: Complex Input Lightweight Neural Network Designed for Massive MIMO CSI Feedback." IEEE Wireless Communications Letters, 10(10), 2318–2322. doi:10.1109/lwc.2021.3100493.
