end_to_end.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. import json
  2. import math
  3. import os
  4. from datetime import datetime as dt
  5. import tensorflow as tf
  6. import numpy as np
  7. import matplotlib.pyplot as plt
  8. from sklearn.metrics import accuracy_score
  9. from sklearn.preprocessing import OneHotEncoder
  10. from tensorflow.keras import layers, losses
  11. from models.layers import ExtractCentralMessage, OpticalChannel, DigitizationLayer, BitsToSymbols, SymbolsToBits
  12. class EndToEndAutoencoder(tf.keras.Model):
  13. def __init__(self,
  14. cardinality,
  15. samples_per_symbol,
  16. messages_per_block,
  17. channel,
  18. custom_loss_fn=False):
  19. """
  20. The autoencoder that aims to find a encoding of the input messages. It should be noted that a "block" consists
  21. of multiple "messages" to introduce memory into the simulation as this is essential for modelling inter-symbol
  22. interference. The autoencoder architecture was heavily influenced by IEEE 8433895.
  23. :param cardinality: Number of different messages. Chosen such that each message encodes log_2(cardinality) bits
  24. :param samples_per_symbol: Number of samples per transmitted symbol
  25. :param messages_per_block: Total number of messages in transmission block
  26. :param channel: Channel Layer object. Must be a subclass of keras.layers.Layer with an implemented forward pass
  27. """
  28. super(EndToEndAutoencoder, self).__init__()
  29. # Labelled M in paper
  30. self.cardinality = cardinality
  31. self.bits_per_symbol = int(math.log(self.cardinality, 2))
  32. # Labelled n in paper
  33. self.samples_per_symbol = samples_per_symbol
  34. # Labelled N in paper - conditional +=1 to ensure odd value
  35. if messages_per_block % 2 == 0:
  36. messages_per_block += 1
  37. self.messages_per_block = messages_per_block
  38. # Channel Model Layer
  39. if isinstance(channel, layers.Layer):
  40. self.channel = tf.keras.Sequential([
  41. layers.Flatten(),
  42. channel,
  43. ExtractCentralMessage(self.messages_per_block, self.samples_per_symbol)
  44. ], name="channel_model")
  45. else:
  46. raise TypeError("Channel must be a subclass of \"tensorflow.keras.layers.layer\"!")
  47. # Boolean identifying if bit mapping is to be learnt
  48. self.custom_loss_fn = custom_loss_fn
  49. # other parameters/metrics
  50. self.symbol_error_rate = None
  51. self.bit_error_rate = None
  52. self.snr = 20 * math.log(0.5 / channel.rx_stddev, 10)
  53. # Model Hyper-parameters
  54. leaky_relu_alpha = 0
  55. relu_clip_val = 1.0
  56. # Encoding Neural Network
  57. self.encoder = tf.keras.Sequential([
  58. layers.Input(shape=(self.messages_per_block, self.cardinality)),
  59. layers.TimeDistributed(layers.Dense(2 * self.cardinality)),
  60. layers.TimeDistributed(layers.LeakyReLU(alpha=leaky_relu_alpha)),
  61. layers.TimeDistributed(layers.Dense(2 * self.cardinality)),
  62. layers.TimeDistributed(layers.LeakyReLU(alpha=leaky_relu_alpha)),
  63. layers.TimeDistributed(layers.Dense(self.samples_per_symbol, activation='sigmoid')),
  64. # layers.TimeDistributed(layers.Dense(self.samples_per_symbol)),
  65. # layers.TimeDistributed(layers.ReLU(max_value=relu_clip_val))
  66. ], name="encoding_model")
  67. # Decoding Neural Network
  68. self.decoder = tf.keras.Sequential([
  69. layers.Dense(2 * self.cardinality),
  70. layers.LeakyReLU(alpha=leaky_relu_alpha),
  71. layers.Dense(2 * self.cardinality),
  72. layers.LeakyReLU(alpha=leaky_relu_alpha),
  73. layers.Dense(self.cardinality, activation='softmax')
  74. ], name="decoding_model")
  75. def save_end_to_end(self):
  76. # extract all params and save
  77. params = {"fs": self.channel.layers[1].fs,
  78. "cardinality": self.cardinality,
  79. "samples_per_symbol": self.samples_per_symbol,
  80. "messages_per_block": self.messages_per_block,
  81. "dispersion_factor": self.channel.layers[1].dispersion_factor,
  82. "fiber_length": float(self.channel.layers[1].fiber_length),
  83. "fiber_length_stddev": float(self.channel.layers[1].fiber_length_stddev),
  84. "lpf_cutoff": self.channel.layers[1].lpf_cutoff,
  85. "rx_stddev": self.channel.layers[1].rx_stddev,
  86. "sig_avg": self.channel.layers[1].sig_avg,
  87. "enob": self.channel.layers[1].enob,
  88. "custom_loss_fn": self.custom_loss_fn
  89. }
  90. dir_str = os.path.join("exports", dt.utcnow().strftime("%Y%m%d-%H%M%S"))
  91. if not os.path.exists(dir_str):
  92. os.makedirs(dir_str)
  93. with open(os.path.join(dir_str, 'params.json'), 'w') as outfile:
  94. json.dump(params, outfile)
  95. ################################################################################################################
  96. # This section exports the weights of the encoder formatted using python variable instantiation syntax
  97. ################################################################################################################
  98. enc_weights, dec_weights = self.extract_weights()
  99. enc_weights = [x.tolist() for x in enc_weights]
  100. dec_weights = [x.tolist() for x in dec_weights]
  101. enc_w = enc_weights[::2]
  102. enc_b = enc_weights[1::2]
  103. dec_w = dec_weights[::2]
  104. dec_b = dec_weights[1::2]
  105. with open(os.path.join(dir_str, 'enc_weights.py'), 'w') as outfile:
  106. outfile.write("enc_weights = ")
  107. outfile.write(str(enc_w))
  108. outfile.write("\n\nenc_bias = ")
  109. outfile.write(str(enc_b))
  110. with open(os.path.join(dir_str, 'dec_weights.py'), 'w') as outfile:
  111. outfile.write("dec_weights = ")
  112. outfile.write(str(dec_w))
  113. outfile.write("\n\ndec_bias = ")
  114. outfile.write(str(dec_b))
  115. ################################################################################################################
  116. self.encoder.save(os.path.join(dir_str, 'encoder'))
  117. self.decoder.save(os.path.join(dir_str, 'decoder'))
  118. def extract_weights(self):
  119. enc_weights = self.encoder.get_weights()
  120. dec_weights = self.encoder.get_weights()
  121. return enc_weights, dec_weights
  122. def encode_stream(self, x):
  123. enc_weights, dec_weights = self.extract_weights()
  124. for i in range(len(enc_weights) // 2):
  125. x = np.matmul(x, enc_weights[2 * i]) + enc_weights[2 * i + 1]
  126. if i == len(enc_weights) // 2 - 1:
  127. x = tf.keras.activations.sigmoid(x).numpy()
  128. else:
  129. x = tf.keras.activations.relu(x).numpy()
  130. return x
  131. def cost(self, y_true, y_pred):
  132. symbol_cost = losses.CategoricalCrossentropy()(y_true, y_pred)
  133. y_bits_true = SymbolsToBits(self.cardinality)(y_true)
  134. y_bits_pred = SymbolsToBits(self.cardinality)(y_pred)
  135. bit_cost = losses.BinaryCrossentropy()(y_bits_true, y_bits_pred)
  136. a = 1
  137. return symbol_cost + a * bit_cost
  138. def generate_random_inputs(self, num_of_blocks, return_vals=False):
  139. """
  140. A method that generates a list of one-hot encoded messages. This is utilized for generating the test/train data.
  141. :param num_of_blocks: Number of blocks to generate. A block contains multiple messages to be transmitted in
  142. consecutively to model ISI. The central message in a block is returned as the label for training.
  143. :param return_vals: If true, the raw decimal values of the input sequence will be returned
  144. """
  145. cat = [np.arange(self.cardinality)]
  146. enc = OneHotEncoder(handle_unknown='ignore', sparse=False, categories=cat)
  147. mid_idx = int((self.messages_per_block - 1) / 2)
  148. rand_int = np.random.randint(self.cardinality, size=(num_of_blocks * self.messages_per_block, 1))
  149. out = enc.fit_transform(rand_int)
  150. out_arr = np.reshape(out, (num_of_blocks, self.messages_per_block, self.cardinality))
  151. if return_vals:
  152. out_val = np.reshape(rand_int, (num_of_blocks, self.messages_per_block, 1))
  153. return out_val, out_arr, out_arr[:, mid_idx, :]
  154. return out_arr, out_arr[:, mid_idx, :]
  155. def train(self, num_of_blocks=1e6, epochs=1, batch_size=None, train_size=0.8, lr=1e-3):
  156. """
  157. Method to train the autoencoder. Further configuration to the loss function, optimizer etc. can be made in here.
  158. :param num_of_blocks: Number of blocks to generate for training. Analogous to the dataset size.
  159. :param batch_size: Number of samples to consider on each update iteration of the optimization algorithm
  160. :param train_size: Float less than 1 representing the proportion of the dataset to use for training
  161. :param lr: The learning rate of the optimizer. Defines how quickly the algorithm converges
  162. """
  163. X_train, y_train = self.generate_random_inputs(int(num_of_blocks * train_size))
  164. X_test, y_test = self.generate_random_inputs(int(num_of_blocks * (1 - train_size)))
  165. opt = tf.keras.optimizers.Adam(learning_rate=lr)
  166. if self.custom_loss_fn:
  167. loss_fn = self.cost
  168. else:
  169. loss_fn = losses.CategoricalCrossentropy()
  170. self.compile(optimizer=opt,
  171. loss=loss_fn,
  172. metrics=['accuracy'],
  173. loss_weights=None,
  174. weighted_metrics=None,
  175. run_eagerly=False
  176. )
  177. self.fit(x=X_train,
  178. y=y_train,
  179. batch_size=batch_size,
  180. epochs=epochs,
  181. shuffle=True,
  182. validation_data=(X_test, y_test)
  183. )
  184. def test(self, num_of_blocks=1e4, length_plot=False, plt_show=True):
  185. X_test, y_test = self.generate_random_inputs(int(num_of_blocks))
  186. y_out = self.call(X_test)
  187. y_pred = tf.argmax(y_out, axis=1)
  188. y_true = tf.argmax(y_test, axis=1)
  189. self.symbol_error_rate = 1 - accuracy_score(y_true, y_pred)
  190. bits_pred = SymbolsToBits(self.cardinality)(tf.one_hot(y_pred, self.cardinality)).numpy().flatten()
  191. bits_true = SymbolsToBits(self.cardinality)(y_test).numpy().flatten()
  192. self.bit_error_rate = 1 - accuracy_score(bits_true, bits_pred)
  193. if length_plot:
  194. lengths = np.linspace(0, 70, 50)
  195. ber_l = []
  196. for l in lengths:
  197. tx_channel = OpticalChannel(fs=self.channel.layers[1].fs,
  198. num_of_samples=self.channel.layers[1].num_of_samples,
  199. dispersion_factor=self.channel.layers[1].dispersion_factor,
  200. fiber_length=l,
  201. lpf_cutoff=self.channel.layers[1].lpf_cutoff,
  202. rx_stddev=self.channel.layers[1].rx_stddev,
  203. sig_avg=self.channel.layers[1].sig_avg,
  204. enob=self.channel.layers[1].enob)
  205. test_channel = tf.keras.Sequential([
  206. layers.Flatten(),
  207. tx_channel,
  208. ExtractCentralMessage(self.messages_per_block, self.samples_per_symbol)
  209. ], name="test channel (variable length)")
  210. X_test_l, y_test_l = self.generate_random_inputs(int(num_of_blocks))
  211. encoded = self.encoder(X_test_l)
  212. after_ch = test_channel(encoded)
  213. y_out_l = self.decoder(after_ch)
  214. y_pred_l = tf.argmax(y_out_l, axis=1)
  215. # y_true_l = tf.argmax(y_test_l, axis=1)
  216. bits_pred_l = SymbolsToBits(self.cardinality)(tf.one_hot(y_pred_l, self.cardinality)).numpy().flatten()
  217. bits_true_l = SymbolsToBits(self.cardinality)(y_test_l).numpy().flatten()
  218. bit_error_rate_l = 1 - accuracy_score(bits_true_l, bits_pred_l)
  219. ber_l.append(bit_error_rate_l)
  220. plt.plot(lengths, ber_l)
  221. plt.yscale('log')
  222. if plt_show:
  223. plt.show()
  224. print("SYMBOL ERROR RATE: {}".format(self.symbol_error_rate))
  225. print("BIT ERROR RATE: {}".format(self.bit_error_rate))
  226. pass
  227. def view_encoder(self):
  228. '''
  229. A method that views the learnt encoder for each distint message. This is displayed as a plot with a subplot for
  230. each message/symbol.
  231. '''
  232. mid_idx = int((self.messages_per_block - 1) / 2)
  233. # Generate inputs for encoder
  234. messages = np.zeros((self.cardinality, self.messages_per_block, self.cardinality))
  235. idx = 0
  236. for msg in messages:
  237. msg[mid_idx, idx] = 1
  238. idx += 1
  239. # Pass input through encoder and select middle messages
  240. encoded = self.encoder(messages)
  241. enc_messages = encoded[:, mid_idx, :]
  242. # Compute subplot grid layout
  243. i = 0
  244. while 2 ** i < self.cardinality ** 0.5:
  245. i += 1
  246. num_x = int(2 ** i)
  247. num_y = int(self.cardinality / num_x)
  248. # Plot all symbols
  249. fig, axs = plt.subplots(num_y, num_x, figsize=(2.5 * num_x, 2 * num_y))
  250. t = np.arange(self.samples_per_symbol)
  251. if isinstance(self.channel.layers[1], OpticalChannel):
  252. t = t / self.channel.layers[1].fs
  253. sym_idx = 0
  254. for y in range(num_y):
  255. for x in range(num_x):
  256. axs[y, x].plot(t, enc_messages[sym_idx].numpy().flatten(), 'x')
  257. axs[y, x].set_title('Symbol {}'.format(str(sym_idx)))
  258. sym_idx += 1
  259. for ax in axs.flat:
  260. ax.set(xlabel='Time', ylabel='Amplitude', ylim=(0, 1))
  261. for ax in axs.flat:
  262. ax.label_outer()
  263. plt.show()
  264. pass
  265. def view_sample_block(self):
  266. '''
  267. Generates a random string of input message and encodes them. In addition to this, the output is passed through
  268. digitization layer without any quantization noise for the low pass filtering.
  269. '''
  270. # Generate a random block of messages
  271. val, inp, _ = self.generate_random_inputs(num_of_blocks=1, return_vals=True)
  272. # Encode and flatten the messages
  273. enc = self.encoder(inp)
  274. flat_enc = layers.Flatten()(enc)
  275. chan_out = self.channel.layers[1](flat_enc)
  276. # Instantiate LPF layer
  277. lpf = DigitizationLayer(fs=self.channel.layers[1].fs,
  278. num_of_samples=self.messages_per_block * self.samples_per_symbol,
  279. sig_avg=0)
  280. # Apply LPF
  281. lpf_out = lpf(flat_enc)
  282. a = np.fft.fft(lpf_out.numpy()).flatten()
  283. f = np.fft.fftfreq(a.shape[-1]).flatten()
  284. plt.plot(f, a)
  285. plt.show()
  286. # Time axis
  287. t = np.arange(self.messages_per_block * self.samples_per_symbol)
  288. if isinstance(self.channel.layers[1], OpticalChannel):
  289. t = t / self.channel.layers[1].fs
  290. # Plot the concatenated symbols before and after LPF
  291. plt.figure(figsize=(2 * self.messages_per_block, 6))
  292. for i in range(1, self.messages_per_block):
  293. plt.axvline(x=t[i * self.samples_per_symbol], color='black')
  294. plt.plot(t, flat_enc.numpy().T, 'x')
  295. plt.plot(t, lpf_out.numpy().T)
  296. plt.plot(t, chan_out.numpy().flatten())
  297. plt.ylim((0, 1))
  298. plt.xlim((t.min(), t.max()))
  299. plt.title(str(val[0, :, 0]))
  300. plt.show()
  301. def call(self, inputs, training=None, mask=None):
  302. tx = self.encoder(inputs)
  303. rx = self.channel(tx)
  304. outputs = self.decoder(rx)
  305. return outputs
  306. def load_model(model_name=None):
  307. if model_name is None:
  308. models = os.listdir("exports")
  309. if not models:
  310. raise Exception("Unable to find a trained model. Please first train and save a model.")
  311. model_name = models[-1]
  312. param_file_path = os.path.join("exports", model_name, "params.json")
  313. if not os.path.isfile(param_file_path):
  314. raise Exception("Invalid File Name/Directory")
  315. else:
  316. with open(param_file_path, 'r') as param_file:
  317. params = json.load(param_file)
  318. optical_channel = OpticalChannel(fs=params["fs"],
  319. num_of_samples=params["messages_per_block"] * params["samples_per_symbol"],
  320. dispersion_factor=params["dispersion_factor"],
  321. fiber_length=params["fiber_length"],
  322. fiber_length_stddev=params["fiber_length_stddev"],
  323. lpf_cutoff=params["lpf_cutoff"],
  324. rx_stddev=params["rx_stddev"],
  325. sig_avg=params["sig_avg"],
  326. enob=params["enob"])
  327. ae_model = EndToEndAutoencoder(cardinality=params["cardinality"],
  328. samples_per_symbol=params["samples_per_symbol"],
  329. messages_per_block=params["messages_per_block"],
  330. channel=optical_channel,
  331. custom_loss_fn=params["custom_loss_fn"])
  332. ae_model.encoder = tf.keras.models.load_model(os.path.join("exports", model_name, "encoder"))
  333. ae_model.decoder = tf.keras.models.load_model(os.path.join("exports", model_name, "decoder"))
  334. return ae_model, params
  335. if __name__ == '__main__':
  336. params = {"fs": 336e9,
  337. "cardinality": 32,
  338. "samples_per_symbol": 32,
  339. "messages_per_block": 9,
  340. "dispersion_factor": (-21.7 * 1e-24),
  341. "fiber_length": 50,
  342. "fiber_length_stddev": 1,
  343. "lpf_cutoff": 32e9,
  344. "rx_stddev": 0.01,
  345. "sig_avg": 0.5,
  346. "enob": 8,
  347. "custom_loss_fn": True
  348. }
  349. force_training = False
  350. model_save_name = ""
  351. param_file_path = os.path.join("exports", model_save_name, "params.json")
  352. if os.path.isfile(param_file_path) and not force_training:
  353. print("Importing model {}".format(model_save_name))
  354. with open(param_file_path, 'r') as file:
  355. params = json.load(file)
  356. optical_channel = OpticalChannel(fs=params["fs"],
  357. num_of_samples=params["messages_per_block"] * params["samples_per_symbol"],
  358. dispersion_factor=params["dispersion_factor"],
  359. fiber_length=params["fiber_length"],
  360. fiber_length_stddev=params["fiber_length_stddev"],
  361. lpf_cutoff=params["lpf_cutoff"],
  362. rx_stddev=params["rx_stddev"],
  363. sig_avg=params["sig_avg"],
  364. enob=params["enob"])
  365. ae_model = EndToEndAutoencoder(cardinality=params["cardinality"],
  366. samples_per_symbol=params["samples_per_symbol"],
  367. messages_per_block=params["messages_per_block"],
  368. channel=optical_channel,
  369. custom_loss_fn=params["custom_loss_fn"])
  370. if os.path.isfile(param_file_path) and not force_training:
  371. ae_model.encoder = tf.keras.models.load_model(os.path.join("exports", model_save_name, "encoder"))
  372. ae_model.decoder = tf.keras.models.load_model(os.path.join("exports", model_save_name, "decoder"))
  373. else:
  374. ae_model.train(num_of_blocks=1e5, epochs=5)
  375. ae_model.save_end_to_end()
  376. pass