Here's a PyTorch implementation of a neural network for data modulation that incorporates OFDM and can add data to audio signals silently. This implementation follows your specifications, including an encoder, decoder, AWGN channel simulator, perceptual loss, and handles audio loading and slicing without loading all files into memory at once.
import os
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import librosa
import soundfile as sf
import numpy as np
from torch.utils.data import Dataset, DataLoader
# Constants and Hyperparameters
NUM_SYMBOLS = 256 # Configurable
SAMPLE_RATE = 8000 # 8 kHz sample rate
SYMBOL_RATE = 1000 # 1000 symbols/sec
SAMPLES_PER_SYMBOL = int(SAMPLE_RATE / SYMBOL_RATE) # 8 samples per symbol
EMBEDDING_DIM = 16 # Embedding dimension
NUM_SUBCARRIERS = 8 # Number of OFDM subcarriers
SNR_DB = 20 # Signal-to-noise ratio in dB
ALPHA = 0.1 # Weight for perceptual loss
BATCH_SIZE = 16
NUM_EPOCHS = 10
AUDIO_FOLDER = './audio' # Path to the audio folder
SLICE_LENGTH = SAMPLE_RATE # 1-second slices
# Custom Dataset for Audio Slices
class AudioDataset(Dataset):
def __init__(self, audio_folder, slice_length=SAMPLE_RATE):
self.audio_folder = audio_folder
self.slice_length = slice_length
self.file_list = [os.path.join(audio_folder, f) for f in os.listdir(audio_folder)
if os.path.isfile(os.path.join(audio_folder, f))]
self.slice_positions = []
self.get_slice_positions()
def get_slice_positions(self):
self.slice_positions = []
for file_idx, file_path in enumerate(self.file_list):
with sf.SoundFile(file_path) as f:
frames = len(f)
num_slices = int(np.ceil(frames / self.slice_length))
for i in range(num_slices):
self.slice_positions.append((file_idx, i))
def __len__(self):
return len(self.slice_positions)
def __getitem__(self, idx):
file_idx, slice_idx = self.slice_positions[idx]
file_path = self.file_list[file_idx]
start_frame = slice_idx * self.slice_length
with sf.SoundFile(file_path) as f:
f.seek(start_frame)
frames_to_read = min(self.slice_length, len(f) - start_frame)
audio_slice = f.read(frames_to_read)
if len(audio_slice) < self.slice_length:
audio_slice = np.pad(audio_slice, (0, self.slice_length - len(audio_slice)))
audio_slice = audio_slice.astype(np.float32)
return audio_slice
# Encoder Module
class Encoder(nn.Module):
def __init__(self, num_symbols=NUM_SYMBOLS, embedding_dim=EMBEDDING_DIM, num_subcarriers=NUM_SUBCARRIERS):
super(Encoder, self).__init__()
self.num_symbols = num_symbols
self.embedding_dim = embedding_dim
self.num_subcarriers = num_subcarriers
self.embedding = nn.Embedding(num_symbols, embedding_dim)
self.fc = nn.Linear(embedding_dim, num_subcarriers * 2) # *2 for real and imaginary parts
def forward(self, symbols):
x = self.embedding(symbols) # (batch_size, num_symbols, embedding_dim)
x = self.fc(x) # (batch_size, num_symbols, num_subcarriers * 2)
x = x.view(x.size(0), x.size(1), self.num_subcarriers, 2) # (batch_size, num_symbols, num_subcarriers, 2)
# Convert to complex numbers
x_complex = torch.complex(x[..., 0], x[..., 1]) # (batch_size, num_symbols, num_subcarriers)
# Perform IFFT to get time-domain signal
time_domain_signal = torch.fft.ifft(x_complex, dim=-1) # (batch_size, num_symbols, num_subcarriers)
time_domain_signal = time_domain_signal.real # Take the real part
# Flatten over symbols
time_domain_signal = time_domain_signal.view(time_domain_signal.size(0), -1)
return time_domain_signal
# AWGN Channel Module
class AWGNChannel(nn.Module):
def __init__(self, snr_db=SNR_DB):
super(AWGNChannel, self).__init__()
self.snr_db = snr_db
def forward(self, signal):
signal_power = signal.pow(2).mean(dim=-1, keepdim=True)
noise_power = signal_power / (10 ** (self.snr_db / 10))
noise = torch.randn_like(signal) * torch.sqrt(noise_power)
received_signal = signal + noise
return received_signal
# Decoder Module
class Decoder(nn.Module):
def __init__(self, num_symbols=NUM_SYMBOLS, num_subcarriers=NUM_SUBCARRIERS):
super(Decoder, self).__init__()
self.num_symbols = num_symbols
self.num_subcarriers = num_subcarriers
self.fc = nn.Linear(num_subcarriers * 2, num_symbols)
def forward(self, received_signal):
batch_size, num_samples = received_signal.shape
num_ofdm_symbols = num_samples // self.num_subcarriers
# Reshape to (batch_size, num_ofdm_symbols, num_subcarriers)
time_domain_signal = received_signal[:, :num_ofdm_symbols * self.num_subcarriers]
time_domain_signal = time_domain_signal.view(batch_size, num_ofdm_symbols, self.num_subcarriers)
# Prepare for FFT (add imaginary part of zeros)
time_domain_signal = torch.complex(time_domain_signal, torch.zeros_like(time_domain_signal))
# Perform FFT
x_complex = torch.fft.fft(time_domain_signal, dim=-1)
# Flatten real and imaginary parts
x_real_imag = torch.cat([x_complex.real, x_complex.imag], dim=-1) # (batch_size, num_ofdm_symbols, num_subcarriers * 2)
# Map to logits
logits = self.fc(x_real_imag) # (batch_size, num_ofdm_symbols, num_symbols)
return logits
# Modulation Model
class ModulationModel(nn.Module):
def __init__(self, num_symbols=NUM_SYMBOLS, embedding_dim=EMBEDDING_DIM,
num_subcarriers=NUM_SUBCARRIERS, snr_db=SNR_DB):
super(ModulationModel, self).__init__()
self.encoder = Encoder(num_symbols, embedding_dim, num_subcarriers)
self.channel = AWGNChannel(snr_db)
self.decoder = Decoder(num_symbols, num_subcarriers)
def forward(self, symbols, audio_signal):
modulated_signal = self.encoder(symbols) # (batch_size, num_samples)
# Ensure modulated_signal has same length as audio_signal
modulated_signal = modulated_signal[:, :audio_signal.shape[1]]
# Scale modulated signal to be less perceptible
modulated_signal = modulated_signal * 0.1 # Scaling factor can be adjusted
# Transmit signal
transmitted_signal = audio_signal + modulated_signal
# Pass through channel
received_signal = self.channel(transmitted_signal)
# Subtract audio to get the modulated part
received_modulated_signal = received_signal - audio_signal
# Decode
logits = self.decoder(received_modulated_signal)
return logits, transmitted_signal
# Loss Function
def compute_loss(logits, symbols, transmitted_signal, audio_signal, alpha=ALPHA):
batch_size, num_ofdm_symbols, _ = logits.shape
# Classification loss
classification_loss = nn.CrossEntropyLoss()(logits.view(-1, NUM_SYMBOLS), symbols.view(-1))
# Perceptual loss
perceptual_loss = nn.MSELoss()(transmitted_signal, audio_signal)
# Total loss
total_loss = classification_loss + alpha * perceptual_loss
return total_loss, classification_loss.item(), perceptual_loss.item()
# Training Loop
def train_model():
# Prepare dataset and dataloader
dataset = AudioDataset(AUDIO_FOLDER, slice_length=SLICE_LENGTH)
dataloader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True)
# Initialize model, optimizer
model = ModulationModel()
optimizer = optim.Adam(model.parameters(), lr=1e-3)
for epoch in range(NUM_EPOCHS):
total_loss = 0
total_classification_loss = 0
total_perceptual_loss = 0
for i, audio_signal in enumerate(dataloader):
batch_size = audio_signal.shape[0]
# Generate random symbols
num_symbols = (audio_signal.shape[1] // (NUM_SUBCARRIERS))
symbols = torch.randint(0, NUM_SYMBOLS, (batch_size, num_symbols), dtype=torch.long)
# Move to device
audio_signal = audio_signal.float()
symbols = symbols
# Forward pass
logits, transmitted_signal = model(symbols, audio_signal)
# Compute loss
loss, cls_loss, perc_loss = compute_loss(logits, symbols, transmitted_signal, audio_signal)
# Backward pass
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Accumulate losses
total_loss += loss.item()
total_classification_loss += cls_loss
total_perceptual_loss += perc_loss
# Save an audio sample for monitoring
if not os.path.exists('outputs'):
os.makedirs('outputs')
output_signal = transmitted_signal[0].detach().numpy()
sf.write(f'outputs/epoch_{epoch + 1}.wav', output_signal, SAMPLE_RATE)
print(f'Epoch {epoch + 1}/{NUM_EPOCHS}, Loss: {total_loss / len(dataloader):.4f}, '
f'Classification Loss: {total_classification_loss / len(dataloader):.4f}, '
f'Perceptual Loss: {total_perceptual_loss / len(dataloader):.4f}')
if __name__ == '__main__':
train_model()
Explanation:
-
Dataset: The AudioDataset class loads audio files from the specified folder, slices them into 1-second segments (default value of SLICE_LENGTH), and doesn't load all audio into memory at once. It reads slices on-the-fly using soundfile for efficient I/O operations.
-
Model:
Encoder: Maps input symbols through an embedding layer and a linear layer to obtain complex subcarrier symbols. Performs an IFFT to obtain time-domain OFDM symbols.
AWGNChannel: Simulates an additive white Gaussian noise channel with configurable SNR.
Decoder: Recovers symbols from the received signal by performing FFT and mapping the subcarrier symbols back to logits over the symbol classes.
ModulationModel: Combines the encoder, channel, and decoder.
-
Loss Function: The compute_loss function calculates the cross-entropy loss for symbol classification and adds a perceptual loss (mean squared error) weighted by ALPHA to ensure minimal audible distortion.
-
Training Loop: The training loop iterates over the dataset, generates random symbols, runs them through the model along with the audio signal, computes the loss, and updates the model parameters. After each epoch, it saves an example of the transmitted (modified) audio signal for monitoring purposes.
-
Audio Saving: At the end of each epoch, an example transmitted audio signal is saved as a WAV file in the outputs directory. This allows you to listen to the audio and verify that there is no noticeable distortion.
Notes:
-
Perceptual Loss Weight (ALPHA): You may need to adjust ALPHA to balance between symbol recovery accuracy and audio quality.
-
Scaling Modulated Signal: The modulated signal is scaled down before being added to the audio to make the data embedding imperceptible.
-
SNR Adjustments: The SNR_DB parameter controls the amount of noise introduced in the channel simulation.
-
Audio Formats: The soundfile library supports various audio formats including WAV, FLAC, and OGG. For formats like MP3 and OPUS, you might need to install additional codecs or use librosa for loading.
Remember to install the required libraries before running the script:
pip install torch librosa soundfile numpy
Usage:
- Place your audio files in the
./audio directory.
- Run the script.
- Check the
outputs folder after each epoch for the modified audio samples.
Let me know if you need any further assistance or modifications!