├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── arch_hyper.png ├── data ├── BCH_63_51_G.npy └── BCH_63_51_H.npy ├── main.py ├── requirements.txt └── scripts ├── data.py ├── model.py ├── solver.py └── utils.py /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to make participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies within all project spaces, and it also applies when 49 | an individual is representing the project or its community in public spaces. 50 | Examples of representing a project or community include using an official 51 | project e-mail address, posting via an official social media account, or acting 52 | as an appointed representative at an online or offline event. Representation of 53 | a project may be further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at . All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to HyperNetDecoder 2 | We want to make contributing to this project as easy and transparent as 3 | possible. 4 | 5 | ## Pull Requests 6 | We actively welcome your pull requests. 7 | 8 | 1. Fork the repo and create your branch from `master`. 9 | 2. If you've added code that should be tested, add tests. 10 | 3. If you've changed APIs, update the documentation. 11 | 4. Ensure the test suite passes. 12 | 5. Make sure your code lints. 13 | 6. If you haven't already, complete the Contributor License Agreement ("CLA"). 14 | 15 | ## Contributor License Agreement ("CLA") 16 | In order to accept your pull request, we need you to submit a CLA. You only need 17 | to do this once to work on any of Facebook's open source projects. 18 | 19 | Complete your CLA here: 20 | 21 | ## Issues 22 | We use GitHub issues to track public bugs. Please ensure your description is 23 | clear and has sufficient instructions to be able to reproduce the issue. 24 | 25 | ## License 26 | By contributing to HyperNetDecoder, you agree that your contributions will be licensed 27 | under the LICENSE file in the root directory of this source tree. 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More_considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | Section 1 -- Definitions. 71 | 72 | a. Adapted Material means material subject to Copyright and Similar 73 | Rights that is derived from or based upon the Licensed Material 74 | and in which the Licensed Material is translated, altered, 75 | arranged, transformed, or otherwise modified in a manner requiring 76 | permission under the Copyright and Similar Rights held by the 77 | Licensor. For purposes of this Public License, where the Licensed 78 | Material is a musical work, performance, or sound recording, 79 | Adapted Material is always produced where the Licensed Material is 80 | synched in timed relation with a moving image. 81 | 82 | b. Adapter's License means the license You apply to Your Copyright 83 | and Similar Rights in Your contributions to Adapted Material in 84 | accordance with the terms and conditions of this Public License. 85 | 86 | c. Copyright and Similar Rights means copyright and/or similar rights 87 | closely related to copyright including, without limitation, 88 | performance, broadcast, sound recording, and Sui Generis Database 89 | Rights, without regard to how the rights are labeled or 90 | categorized. For purposes of this Public License, the rights 91 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 92 | Rights. 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. NonCommercial means not primarily intended for or directed towards 116 | commercial advantage or monetary compensation. For purposes of 117 | this Public License, the exchange of the Licensed Material for 118 | other material subject to Copyright and Similar Rights by digital 119 | file-sharing or similar means is NonCommercial provided there is 120 | no payment of monetary compensation in connection with the 121 | exchange. 122 | 123 | j. Share means to provide material to the public by any means or 124 | process that requires permission under the Licensed Rights, such 125 | as reproduction, public display, public performance, distribution, 126 | dissemination, communication, or importation, and to make material 127 | available to the public including in ways that members of the 128 | public may access the material from a place and at a time 129 | individually chosen by them. 130 | 131 | k. Sui Generis Database Rights means rights other than copyright 132 | resulting from Directive 96/9/EC of the European Parliament and of 133 | the Council of 11 March 1996 on the legal protection of databases, 134 | as amended and/or succeeded, as well as other essentially 135 | equivalent rights anywhere in the world. 136 | 137 | l. You means the individual or entity exercising the Licensed Rights 138 | under this Public License. Your has a corresponding meaning. 139 | 140 | Section 2 -- Scope. 141 | 142 | a. License grant. 143 | 144 | 1. Subject to the terms and conditions of this Public License, 145 | the Licensor hereby grants You a worldwide, royalty-free, 146 | non-sublicensable, non-exclusive, irrevocable license to 147 | exercise the Licensed Rights in the Licensed Material to: 148 | 149 | a. reproduce and Share the Licensed Material, in whole or 150 | in part, for NonCommercial purposes only; and 151 | 152 | b. produce, reproduce, and Share Adapted Material for 153 | NonCommercial purposes only. 154 | 155 | 2. Exceptions and Limitations. For the avoidance of doubt, where 156 | Exceptions and Limitations apply to Your use, this Public 157 | License does not apply, and You do not need to comply with 158 | its terms and conditions. 159 | 160 | 3. Term. The term of this Public License is specified in Section 161 | 6(a). 162 | 163 | 4. Media and formats; technical modifications allowed. The 164 | Licensor authorizes You to exercise the Licensed Rights in 165 | all media and formats whether now known or hereafter created, 166 | and to make technical modifications necessary to do so. The 167 | Licensor waives and/or agrees not to assert any right or 168 | authority to forbid You from making technical modifications 169 | necessary to exercise the Licensed Rights, including 170 | technical modifications necessary to circumvent Effective 171 | Technological Measures. For purposes of this Public License, 172 | simply making modifications authorized by this Section 2(a) 173 | (4) never produces Adapted Material. 174 | 175 | 5. Downstream recipients. 176 | 177 | a. Offer from the Licensor -- Licensed Material. Every 178 | recipient of the Licensed Material automatically 179 | receives an offer from the Licensor to exercise the 180 | Licensed Rights under the terms and conditions of this 181 | Public License. 182 | 183 | b. No downstream restrictions. You may not offer or impose 184 | any additional or different terms or conditions on, or 185 | apply any Effective Technological Measures to, the 186 | Licensed Material if doing so restricts exercise of the 187 | Licensed Rights by any recipient of the Licensed 188 | Material. 189 | 190 | 6. No endorsement. Nothing in this Public License constitutes or 191 | may be construed as permission to assert or imply that You 192 | are, or that Your use of the Licensed Material is, connected 193 | with, or sponsored, endorsed, or granted official status by, 194 | the Licensor or others designated to receive attribution as 195 | provided in Section 3(a)(1)(A)(i). 196 | 197 | b. Other rights. 198 | 199 | 1. Moral rights, such as the right of integrity, are not 200 | licensed under this Public License, nor are publicity, 201 | privacy, and/or other similar personality rights; however, to 202 | the extent possible, the Licensor waives and/or agrees not to 203 | assert any such rights held by the Licensor to the limited 204 | extent necessary to allow You to exercise the Licensed 205 | Rights, but not otherwise. 206 | 207 | 2. Patent and trademark rights are not licensed under this 208 | Public License. 209 | 210 | 3. To the extent possible, the Licensor waives any right to 211 | collect royalties from You for the exercise of the Licensed 212 | Rights, whether directly or through a collecting society 213 | under any voluntary or waivable statutory or compulsory 214 | licensing scheme. In all other cases the Licensor expressly 215 | reserves any right to collect such royalties, including when 216 | the Licensed Material is used other than for NonCommercial 217 | purposes. 218 | 219 | Section 3 -- License Conditions. 220 | 221 | Your exercise of the Licensed Rights is expressly made subject to the 222 | following conditions. 223 | 224 | a. Attribution. 225 | 226 | 1. If You Share the Licensed Material (including in modified 227 | form), You must: 228 | 229 | a. retain the following if it is supplied by the Licensor 230 | with the Licensed Material: 231 | 232 | i. identification of the creator(s) of the Licensed 233 | Material and any others designated to receive 234 | attribution, in any reasonable manner requested by 235 | the Licensor (including by pseudonym if 236 | designated); 237 | 238 | ii. a copyright notice; 239 | 240 | iii. a notice that refers to this Public License; 241 | 242 | iv. a notice that refers to the disclaimer of 243 | warranties; 244 | 245 | v. a URI or hyperlink to the Licensed Material to the 246 | extent reasonably practicable; 247 | 248 | b. indicate if You modified the Licensed Material and 249 | retain an indication of any previous modifications; and 250 | 251 | c. indicate the Licensed Material is licensed under this 252 | Public License, and include the text of, or the URI or 253 | hyperlink to, this Public License. 254 | 255 | 2. You may satisfy the conditions in Section 3(a)(1) in any 256 | reasonable manner based on the medium, means, and context in 257 | which You Share the Licensed Material. For example, it may be 258 | reasonable to satisfy the conditions by providing a URI or 259 | hyperlink to a resource that includes the required 260 | information. 261 | 262 | 3. If requested by the Licensor, You must remove any of the 263 | information required by Section 3(a)(1)(A) to the extent 264 | reasonably practicable. 265 | 266 | 4. If You Share Adapted Material You produce, the Adapter's 267 | License You apply must not prevent recipients of the Adapted 268 | Material from complying with this Public License. 269 | 270 | Section 4 -- Sui Generis Database Rights. 271 | 272 | Where the Licensed Rights include Sui Generis Database Rights that 273 | apply to Your use of the Licensed Material: 274 | 275 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 276 | to extract, reuse, reproduce, and Share all or a substantial 277 | portion of the contents of the database for NonCommercial purposes 278 | only; 279 | 280 | b. if You include all or a substantial portion of the database 281 | contents in a database in which You have Sui Generis Database 282 | Rights, then the database in which You have Sui Generis Database 283 | Rights (but not its individual contents) is Adapted Material; and 284 | 285 | c. You must comply with the conditions in Section 3(a) if You Share 286 | all or a substantial portion of the contents of the database. 287 | 288 | For the avoidance of doubt, this Section 4 supplements and does not 289 | replace Your obligations under this Public License where the Licensed 290 | Rights include other Copyright and Similar Rights. 291 | 292 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 293 | 294 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 295 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 296 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 297 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 298 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 299 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 300 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 301 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 302 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 303 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 304 | 305 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 306 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 307 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 308 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 309 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 310 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 311 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 312 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 313 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 314 | 315 | c. The disclaimer of warranties and limitation of liability provided 316 | above shall be interpreted in a manner that, to the extent 317 | possible, most closely approximates an absolute disclaimer and 318 | waiver of all liability. 319 | 320 | Section 6 -- Term and Termination. 321 | 322 | a. This Public License applies for the term of the Copyright and 323 | Similar Rights licensed here. However, if You fail to comply with 324 | this Public License, then Your rights under this Public License 325 | terminate automatically. 326 | 327 | b. Where Your right to use the Licensed Material has terminated under 328 | Section 6(a), it reinstates: 329 | 330 | 1. automatically as of the date the violation is cured, provided 331 | it is cured within 30 days of Your discovery of the 332 | violation; or 333 | 334 | 2. upon express reinstatement by the Licensor. 335 | 336 | For the avoidance of doubt, this Section 6(b) does not affect any 337 | right the Licensor may have to seek remedies for Your violations 338 | of this Public License. 339 | 340 | c. For the avoidance of doubt, the Licensor may also offer the 341 | Licensed Material under separate terms or conditions or stop 342 | distributing the Licensed Material at any time; however, doing so 343 | will not terminate this Public License. 344 | 345 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 346 | License. 347 | 348 | Section 7 -- Other Terms and Conditions. 349 | 350 | a. The Licensor shall not be bound by any additional or different 351 | terms or conditions communicated by You unless expressly agreed. 352 | 353 | b. Any arrangements, understandings, or agreements regarding the 354 | Licensed Material not stated herein are separate from and 355 | independent of the terms and conditions of this Public License. 356 | 357 | Section 8 -- Interpretation. 358 | 359 | a. For the avoidance of doubt, this Public License does not, and 360 | shall not be interpreted to, reduce, limit, restrict, or impose 361 | conditions on any use of the Licensed Material that could lawfully 362 | be made without permission under this Public License. 363 | 364 | b. To the extent possible, if any provision of this Public License is 365 | deemed unenforceable, it shall be automatically reformed to the 366 | minimum extent necessary to make it enforceable. If the provision 367 | cannot be reformed, it shall be severed from this Public License 368 | without affecting the enforceability of the remaining terms and 369 | conditions. 370 | 371 | c. No term or condition of this Public License will be waived and no 372 | failure to comply consented to unless expressly agreed to by the 373 | Licensor. 374 | 375 | d. Nothing in this Public License constitutes or may be interpreted 376 | as a limitation upon, or waiver of, any privileges and immunities 377 | that apply to the Licensor or You, including from the legal 378 | processes of any jurisdiction or authority. 379 | 380 | ======================================================================= 381 | 382 | Creative Commons is not a party to its public 383 | licenses. Notwithstanding, Creative Commons may elect to apply one of 384 | its public licenses to material it publishes and in those instances 385 | will be considered the “Licensor.” The text of the Creative Commons 386 | public licenses is dedicated to the public domain under the CC0 Public 387 | Domain Dedication. Except for the limited purpose of indicating that 388 | material is shared under a Creative Commons public license or as 389 | otherwise permitted by the Creative Commons policies published at 390 | creativecommons.org/policies, Creative Commons does not authorize the 391 | use of the trademark "Creative Commons" or any other trademark or logo 392 | of Creative Commons without its prior written consent including, 393 | without limitation, in connection with any unauthorized modifications 394 | to any of its public licenses or any other arrangements, 395 | understandings, or agreements concerning use of licensed material. For 396 | the avoidance of doubt, this paragraph does not form part of the 397 | public licenses. 398 | 399 | Creative Commons may be contacted at creativecommons.org. 400 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HyperNetDecoder 2 | 3 | An implementation of Hyper-Graph-Network described in ["Hyper-Graph-Network Decoders for Block Codes" (NeurIPS 2019)](https://arxiv.org/abs/1909.09036). 4 | 5 | 6 |

7 | Hyper-Graph-Network

9 | 10 | 11 | 12 | 13 | ## Abstract 14 | 15 | Neural decoders were shown to outperform classical message passing techniques for short BCH codes. In this work, we extend these results to much larger families of algebraic block codes, by performing message passing with graph neural networks. The parameters of the sub-network at each variable-node in the Tanner graph are obtained from a hypernetwork that receives the absolute values of the current message as input. To add stability, we employ a simplified version of the arctanh activation that is based on a high order Taylor approximation of this activation function. Our results show that for a large number of algebraic block codes, from diverse families of codes (BCH, LDPC, Polar), the decoding obtained with our method outperforms the vanilla belief propagation method as well as other learning techniques from the literature. 16 | 17 | 18 | ## Install 19 | - TensorFlow 1.13.1 20 | - Python3 (Recommend Anaconda) 21 | - `pip install -r requirements.txt` 22 | 23 | ## Results reproduction 24 | To reproduce the performance of the main model in our paper for BCH(63,51): 25 | 26 | 1. Run `python main.py` 27 | 2. Training with GPU. For 3 days of training with V100 32GB GPU. At epoch ±316 you should get this BER results: 28 | 29 | SNR range in [dB] - [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0] 30 | 31 | Bit Error rate - [8.042e-02, 5.039e-02, 2.653e-02, 9.793e-03, 2.322e-03, 3.000e-04, 2.169e-05, 7.936e-07] 32 | 33 | 34 | ## Hyperparameters 35 | - start_snr - start value of SNR (in dB) 36 | - step - step value of SNR (in dB) 37 | - stop_snr - stop value of SNR (in dB) 38 | - weights_path - the path for the checkpoint. should be ckpt file 39 | - num_hidden_layers - how may iteration of the method 40 | - numOfWordSim_train - how many codeword per snr 41 | - batches_for_val_per_snr - how may batches per snr in the evaluation step 42 | - batch_in_epoch - how many batches in epoch 43 | - num_of_batch - total number of batches 44 | - learning_rate - learning rate 45 | - train_on_zero_word - True if you want to train only with the zero code word 46 | - test_on_zero_word - False if you want to eval in valid codeword (not only the zero code word) 47 | - n_hidden_1 - how many neurons in the first layer of network 'g' 48 | - n_hidden_2 - how many neurons in the second layer of network 'g' 49 | - sf_n_hidden_1 - how many neurons in the first layer of network 'f' 50 | - sf_n_hidden_2 - how many neurons in the second layer of network 'f' 51 | - sf_n_hidden_3 - how many neurons in the third layer of network 'f' 52 | 53 | ## Reference 54 | If you find this repo helpful, please consider citing: 55 | 56 | @inproceedings{nachmani2019hyper, 57 | title={Hyper-graph-network decoders for block codes}, 58 | author={Nachmani, Eliya and Wolf, Lior}, 59 | booktitle={Advances in Neural Information Processing Systems}, 60 | pages={2326--2336}, 61 | year={2019}, 62 | } 63 | 64 | ## License 65 | This repo is CC-BY-NC 4.0 licensed, as found in the LICENSE file. 66 | -------------------------------------------------------------------------------- /arch_hyper.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/HyperNetworkDecoder/dcb2614458283505b9a1993570b811128f71a3f6/arch_hyper.png -------------------------------------------------------------------------------- /data/BCH_63_51_G.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/HyperNetworkDecoder/dcb2614458283505b9a1993570b811128f71a3f6/data/BCH_63_51_G.npy -------------------------------------------------------------------------------- /data/BCH_63_51_H.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/HyperNetworkDecoder/dcb2614458283505b9a1993570b811128f71a3f6/data/BCH_63_51_H.npy -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | 8 | 9 | import tensorflow as tf 10 | import numpy as np 11 | import os 12 | import sys 13 | sys.path.append(os.getcwd()+'/scripts') 14 | from data import DataSet 15 | from model import HyperNetworkDecoder 16 | from solver import Solver 17 | 18 | import argparse 19 | parser = argparse.ArgumentParser("Hyper-Graph-Network Decoders for Block Codes") 20 | 21 | 22 | # General Configuration 23 | parser.add_argument('--code_parityCheckMatrix_path', type=str, default='./data/BCH_63_51_H.npy', 24 | help='Parity check matrix file') 25 | parser.add_argument('--code_generatorMatrix_path', type=str, default='./data/BCH_63_51_G.npy', 26 | help='Generator matrix file') 27 | parser.add_argument('--code_n', type=int, default=63, 28 | help='Block length - N') 29 | parser.add_argument('--code_k', type=int, default=51, 30 | help='Number of information bits - K') 31 | parser.add_argument('--start_snr', default=1.0, type=float, 32 | help='SNR start value, in dB.') 33 | parser.add_argument('--stop_snr', default=8.0, type=float, 34 | help='SNR stop value, in dB.') 35 | parser.add_argument('--step', default=1.0, type=float, 36 | help='SNR step, in dB.') 37 | parser.add_argument('--word_seed', default=786000, type=int, 38 | help='Seed for word generator') 39 | parser.add_argument('--noise_seed', default=345000, type=int, 40 | help='Seed for noise generator') 41 | parser.add_argument('--weights_path', default='', type=str, 42 | help='Path for checkpoint') 43 | parser.add_argument('--num_hidden_layers', default=5, type=int, 44 | help='Number of iteration of BP') 45 | parser.add_argument('--numOfWordSim_train', default=15, type=int, 46 | help='Number of word simulated') 47 | parser.add_argument('--batches_for_val_per_snr', default=500, type=int, 48 | help='Number batches per SNR') 49 | parser.add_argument('--batch_in_epoch', default=500, type=int, 50 | help='Number of batches in epoch') 51 | parser.add_argument('--num_of_batch', default=100000000, type=int, 52 | help='Total number of batches in training') 53 | parser.add_argument('--learning_rate', default=0.0001, type=float, 54 | help='Learning rate') 55 | parser.add_argument('--gpu_mem_fraction', default=0.99, type=float, 56 | help='Percentage of memory GPU useage') 57 | parser.add_argument('--train_on_zero_word', action='store_true', 58 | help='Does train on zero codeword only?') 59 | parser.add_argument('--test_on_zero_word', action='store_true', 60 | help='Does test on zero codeword only?') 61 | parser.add_argument('--n_hidden_1', default=16, type=int, 62 | help='Number of neurons in the first layer of g') 63 | parser.add_argument('--n_hidden_2', default=16, type=int, 64 | help='Number of neurons in the second layer of g') 65 | parser.add_argument('--sf_n_hidden_1', default=32, type=int, 66 | help='Number of neurons in the first layer of f') 67 | parser.add_argument('--sf_n_hidden_2', default=32, type=int, 68 | help='Number of neurons in the second layer of f') 69 | parser.add_argument('--sf_n_hidden_3', default=32, type=int, 70 | help='Number of neurons in the third layer of f') 71 | parser.add_argument('--weights_path_save', default=os.getcwd(), type=str, 72 | help='Path to save checkpoint') 73 | parser.add_argument('--var_type', default=np.float32, type=type, 74 | help='Variable type') 75 | 76 | 77 | def main(args): 78 | 79 | # Loading Dataset 80 | dataLoader = DataSet(args) 81 | 82 | # Build Model 83 | model = HyperNetworkDecoder(args, dataLoader) 84 | 85 | # Init GPU 86 | gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=args.gpu_mem_fraction) 87 | 88 | # Init Solver 89 | solver = Solver(args, dataLoader, model) 90 | 91 | # Training & Evaluating 92 | solver.train() 93 | 94 | 95 | if __name__ == '__main__': 96 | 97 | args = parser.parse_args() 98 | 99 | ### General Parameters 100 | args.code_parityCheckMatrix = np.load(args.code_parityCheckMatrix_path) 101 | args.code_generatorMatrix = np.load(args.code_generatorMatrix_path) 102 | args.code_rate = 1.0*args.code_k/args.code_n 103 | args.snr_db = np.arange(args.start_snr, args.stop_snr+args.step, args.step, dtype=np.float32) 104 | args.batch_size = args.numOfWordSim_train * len(args.snr_db) 105 | args.batches_for_val_per_snr_all = np.ones((len(args.snr_db),)) * args.batches_for_val_per_snr 106 | args.batches_for_val_per_snr_all = args.batches_for_val_per_snr_all.astype(int) 107 | args.n_odd = int(np.sum(args.code_parityCheckMatrix)) 108 | args.n_even = args.n_odd 109 | args.n_input = args.n_odd + 1 # plus 1 for skip connection 110 | args.sf_n_input = args.n_odd 111 | args.snr_lin = 10.0**(args.snr_db/10.0) 112 | args.weights_path_format = args.weights_path_save + '/weights/weights_epoch_%03d.ckpt' 113 | 114 | main(args) 115 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | tensorflow==1.13.1 2 | numpy==1.16.3 3 | matplotlib==2.2.3 4 | scipy==1.2.1 5 | -------------------------------------------------------------------------------- /scripts/data.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | 8 | import numpy as np 9 | 10 | class DataSet(): 11 | 12 | def __init__(self, args): 13 | 14 | self.scaling_factor = np.sqrt(1.0/(2.0*args.snr_lin*args.code_rate)) 15 | self.wordRandom = np.random.RandomState(args.word_seed) 16 | self.random = np.random.RandomState(args.noise_seed) 17 | self.numOfWordSim = args.numOfWordSim_train 18 | self.code_n = args.code_n 19 | self.code_k = args.code_k 20 | self.code_parityCheckMatrix = args.code_parityCheckMatrix 21 | self.code_generatorMatrix = args.code_generatorMatrix 22 | 23 | 24 | def get_batch(self, is_zeros_word, numOfWordSim_new=None, scaling_factor_new=None): 25 | """Short summary. 26 | 27 | Parameters 28 | ---------- 29 | is_zeros_word : type 30 | Description of parameter `is_zeros_word`. 31 | numOfWordSim_new : type 32 | Description of parameter `numOfWordSim_new`. 33 | scaling_factor_new : type 34 | Description of parameter `scaling_factor_new`. 35 | 36 | Returns 37 | ------- 38 | type 39 | Description of returned object. 40 | 41 | """ 42 | 43 | self.X = np.zeros([1, self.code_n], dtype=np.float32) 44 | self.Y = np.zeros([1, self.code_n], dtype=np.int32) 45 | 46 | if scaling_factor_new: 47 | scaling_factor = scaling_factor_new 48 | else: 49 | scaling_factor = self.scaling_factor 50 | 51 | if numOfWordSim_new: 52 | numOfWordSim = numOfWordSim_new 53 | else: 54 | numOfWordSim = self.numOfWordSim 55 | 56 | # Build set for epoch 57 | for sf_i in scaling_factor: 58 | if is_zeros_word: 59 | infoWord_i = 0*self.wordRandom.randint(0, 2, size=(numOfWordSim, self.code_k)) 60 | else: 61 | infoWord_i = self.wordRandom.randint(0, 2, size=(numOfWordSim, self.code_k)) 62 | 63 | Y_i = np.dot(infoWord_i, self.code_generatorMatrix) % 2 64 | X_p_i = self.random.normal(0.0, 1.0, Y_i.shape)*sf_i + (-1)**(Y_i) 65 | x_llr_i = 2*X_p_i/(sf_i**2) 66 | self.X = np.vstack((self.X, x_llr_i)) 67 | self.Y = np.vstack((self.Y, Y_i)) 68 | 69 | self.X = self.X[1:] 70 | self.Y = self.Y[1:] 71 | 72 | return self.X, self.Y 73 | -------------------------------------------------------------------------------- /scripts/model.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | 8 | import tensorflow as tf 9 | import numpy as np 10 | 11 | 12 | class HyperNetworkDecoder(): 13 | 14 | def __init__(self, args, data): 15 | 16 | self.data = data 17 | self.args = args 18 | 19 | # F network 20 | init_xav = tf.contrib.layers.xavier_initializer() 21 | self.f_weights = { 22 | 'f_h1': tf.get_variable('f_h1', [args.sf_n_input, args.sf_n_hidden_1], initializer=init_xav), 23 | 'f_h2': tf.get_variable('f_h2', [args.sf_n_hidden_1, args.sf_n_hidden_2], initializer=init_xav), 24 | 'f_h3': tf.get_variable('f_h3', [args.sf_n_hidden_2, args.sf_n_hidden_3], initializer=init_xav), 25 | 'f_h4': tf.get_variable('f_h4', [args.sf_n_hidden_3, args.sf_n_hidden_3], initializer=init_xav), 26 | 'f_head1': tf.get_variable('f_head1',[args.sf_n_hidden_3, args.n_input*args.n_hidden_1], initializer=init_xav), 27 | 'f_head2': tf.get_variable('f_head2',[args.sf_n_hidden_3, args.n_hidden_2], initializer=init_xav) 28 | } 29 | 30 | # Input/Output placeholders 31 | self.x = tf.placeholder(tf.float32, shape=[args.batch_size, args.code_n]) 32 | self.y = tf.placeholder(tf.float32, shape=[args.batch_size, args.code_n]) 33 | 34 | # Generate matrices for graph construction 35 | self.generate_graph_matrix(args) 36 | self.W_odd2even_graphnn_var = tf.Variable(self.W_odd2even_graphnn) 37 | self.W_output_var = tf.Variable(self.W_output.copy()) 38 | 39 | # Input layer 40 | self.x_tile = tf.tile(self.x, multiples=[1, args.n_odd]) 41 | self.W_input = tf.reshape(self.W_input.transpose(), [-1]) 42 | self.x_tile = tf.multiply(self.x_tile, self.W_input) 43 | self.x_tile = tf.reshape(self.x_tile, [args.batch_size, args.n_odd, args.code_n]) 44 | self.u_i = tf.tanh(0.5*tf.clip_by_value(self.x_tile, clip_value_min=-10, clip_value_max=10)) 45 | self.u_i = tf.add(self.u_i, 1-tf.to_float(tf.abs(self.u_i) > 0)) 46 | self.z_input = tf.reduce_prod(self.u_i, reduction_indices=2) 47 | self.x_hv = tf.log(tf.div(1+self.z_input, 1-self.z_input)) 48 | 49 | self.net_dict = {} 50 | self.arg_loss = 0 51 | for i in range(0, args.num_hidden_layers-1, 1): 52 | 53 | # parity layer 54 | fw1, fw2 = self.f_hyper(tf.abs(self.x_hv), self.f_weights) 55 | self.x_hv_c = tf.expand_dims(self.x_hv, 1) 56 | 57 | f_weights = {'h1':tf.reshape(fw1, [args.batch_size, args.n_input, args.n_hidden_1]), 'out':tf.reshape(fw2, [args.batch_size, args.n_hidden_2, 1])} 58 | self.W_odd2even_graphnn_var = tf.multiply(self.W_odd2even_graphnn, self.W_odd2even_graphnn_var) 59 | self.x_input_tile = tf.einsum('aij,bjk->abik', self.x_hv_c, self.W_odd2even_graphnn_var) 60 | self.x_hv_c = tf.squeeze(self.x_input_tile, 2) 61 | 62 | self.x_sc = tf.expand_dims(tf.matmul(self.x, self.W_skipconn2even), 2) 63 | self.x_all = tf.concat([self.x_hv_c, self.x_sc], 2) 64 | self.x_hp = self.mlp_vn(self.x_all, f_weights) 65 | 66 | # check layer 67 | self.x_hv_c = tf.tile(self.x_hp, multiples=[1, args.n_odd]) 68 | self.x_hv_c = tf.multiply(self.x_hv_c, tf.reshape(self.W_even2odd.transpose(), [-1])) 69 | self.x_hv_c = tf.reshape(self.x_hv_c,[args.batch_size, args.n_odd, args.n_even]) 70 | self.x_hv_c = tf.add(self.x_hv_c, 1 - tf.to_float(tf.abs(self.x_hv_c) > 0)) 71 | self.x_hv_c = tf.reduce_prod(self.x_hv_c, reduction_indices=2) 72 | self.x_hv = 2*self.arc_tanh_like(self.x_hv_c, order=1005) 73 | 74 | # marginalization & loss calculating 75 | self.W_output_var = tf.multiply(self.W_output_var, self.W_output) 76 | self.out_i = tf.add(self.x, tf.matmul(self.x_hv, self.W_output)) 77 | self.arg_loss += tf.nn.sigmoid_cross_entropy_with_logits(logits=self.out_i, labels=1-self.y) 78 | 79 | self.y_output = self.out_i 80 | self.loss = tf.reduce_mean(self.arg_loss) 81 | self.train_step = tf.train.AdamOptimizer(learning_rate=args.learning_rate).minimize(self.loss) 82 | 83 | def mlp_vn(self, x, weights): 84 | """Short summary. 85 | 86 | Parameters 87 | ---------- 88 | x : type 89 | Description of parameter `x`. 90 | weights : type 91 | Description of parameter `weights`. 92 | 93 | Returns 94 | ------- 95 | type 96 | Description of returned object. 97 | 98 | """ 99 | 100 | # First Layer 101 | layer_1 = tf.einsum('aij,ajb->aib', x, weights['h1']) 102 | layer_1 = tf.nn.tanh(layer_1) 103 | 104 | # Second layer 105 | out_layer = tf.einsum('aij,ajb->aib', layer_1, weights['out']) 106 | out_layer = tf.nn.tanh(out_layer) 107 | 108 | out_layer = tf.squeeze(out_layer, 2) 109 | 110 | return out_layer 111 | 112 | def f_hyper(self, x, f_weights): 113 | """Short summary. 114 | 115 | Parameters 116 | ---------- 117 | x : type 118 | Description of parameter `x`. 119 | f_weights : type 120 | Description of parameter `f_weights`. 121 | 122 | Returns 123 | ------- 124 | type 125 | Description of returned object. 126 | 127 | """ 128 | 129 | layer_1 = tf.einsum('aj,jb->ab', x, f_weights['f_h1']) 130 | layer_1 = tf.nn.tanh(layer_1) 131 | 132 | # Hidden layer with tanh activation 133 | layer_2 = tf.einsum('aj,jb->ab', layer_1, f_weights['f_h2']) 134 | layer_2 = tf.nn.tanh(layer_2) 135 | 136 | # Hidden layer with tanh activation 137 | layer_3 = tf.einsum('aj,jb->ab', layer_2, f_weights['f_h3']) 138 | layer_3 = tf.nn.tanh(layer_3) 139 | 140 | # Hidden layer with tanh activation 141 | layer_4 = tf.einsum('aj,jb->ab', layer_3, f_weights['f_h4']) 142 | layer_4 = tf.nn.tanh(layer_4) 143 | 144 | # Output layer with linear activation 145 | out_1 = tf.einsum('aj,jb->ab', layer_4, f_weights['f_head1']) 146 | out_2 = tf.einsum('aj,jb->ab', layer_4, f_weights['f_head2']) 147 | 148 | return out_1, out_2 149 | 150 | 151 | def arc_tanh_like(self, x, order): 152 | """Short summary. 153 | 154 | Parameters 155 | ---------- 156 | x : type 157 | Description of parameter `x`. 158 | order : type 159 | Description of parameter `order`. 160 | 161 | Returns 162 | ------- 163 | type 164 | Description of returned object. 165 | 166 | """ 167 | 168 | out = x 169 | for i in range(3, order+1): 170 | if (i-1) % 2 == 0: 171 | out += (1.0/i)*tf.pow(x, i*tf.ones_like(x)) 172 | 173 | return out 174 | 175 | def generate_graph_matrix(self, args): 176 | """Short summary. 177 | 178 | Parameters 179 | ---------- 180 | args : type 181 | Description of parameter `args`. 182 | 183 | Returns 184 | ------- 185 | type 186 | Description of returned object. 187 | 188 | """ 189 | 190 | self.W_input = np.zeros((args.code_n, args.n_odd), dtype=args.var_type) 191 | self.W_odd2even = np.zeros((args.n_odd, args.n_even), dtype=args.var_type) 192 | self.W_odd2even_graphnn = np.zeros((args.n_odd, args.n_even, args.n_odd), dtype=args.var_type) 193 | self.W_skipconn2even = np.zeros((args.code_n,args.n_even), dtype=args.var_type) 194 | self.W_even2odd = np.zeros((args.n_even, args.n_odd), dtype=args.var_type) 195 | self.W_output = np.zeros((args.n_odd, args.code_n), dtype=args.var_type) 196 | 197 | # init W_input 198 | k = 0 199 | for i in range(0,self.data.code_parityCheckMatrix.shape[0],1): 200 | for j in range(0,self.data.code_parityCheckMatrix.shape[1],1): 201 | if(self.data.code_parityCheckMatrix[i,j] == 1): 202 | vec = self.data.code_parityCheckMatrix[i,:].copy() 203 | vec[j] = 0 204 | self.W_input[:,k] = vec 205 | k += 1 206 | 207 | # init W_odd2even & W_skipconn2even 208 | k = 0 209 | vec_tmp = np.zeros((args.n_odd),dtype=args.var_type) 210 | for j in range(0,self.data.code_parityCheckMatrix.shape[1],1): 211 | for i in range(0,self.data.code_parityCheckMatrix.shape[0],1): 212 | if(self.data.code_parityCheckMatrix[i,j] == 1): 213 | 214 | num_of_conn = np.sum(self.data.code_parityCheckMatrix[:,j]) # get the number of connection of the variable node 215 | idx = np.argwhere(self.data.code_parityCheckMatrix[:,j] ==1) # get the indexes 216 | for l in range(0, num_of_conn, 1): # adding num_of_conn columns to W 217 | vec_tmp = np.zeros((args.n_odd),dtype=args.var_type) 218 | for r in range(0, self.data.code_parityCheckMatrix.shape[0], 1): # adding one to the right place 219 | if(self.data.code_parityCheckMatrix[r,j] == 1 and idx[l][0] != r): 220 | idx_vec = np.cumsum(self.data.code_parityCheckMatrix[r,0:j+1])[-1] - 1 221 | vec_tmp[int(idx_vec + np.sum(self.data.code_parityCheckMatrix[:r,:]))] = 1.0 222 | self.W_odd2even[:,k] = vec_tmp.transpose() 223 | k += 1 224 | break 225 | 226 | # init W_odd2even_graphnn 227 | for j in range(0,self.W_odd2even.shape[1],1): 228 | for i in range(0,self.W_odd2even.shape[0],1): 229 | self.W_odd2even_graphnn[j, i, i] = self.W_odd2even[i, j] 230 | 231 | # init W_even2odd, W_skipconn2even & W_output 232 | k, m = 0, 0 233 | for j in range(0,self.data.code_parityCheckMatrix.shape[1],1): 234 | for i in range(0,self.data.code_parityCheckMatrix.shape[0],1): 235 | if(self.data.code_parityCheckMatrix[i,j] == 1): 236 | 237 | # W_even2odd 238 | idx_row = np.cumsum(self.data.code_parityCheckMatrix[i,0:j+1])[-1] - 1 239 | till_d_c = np.sum(self.data.code_parityCheckMatrix[:i,:]) 240 | this_d_c = np.sum(self.data.code_parityCheckMatrix[:(i+1),:]) 241 | self.W_even2odd[k,int(till_d_c):int(this_d_c)] = 1.0 242 | self.W_even2odd[k,int(till_d_c+idx_row)] = 0.0 243 | 244 | # W_skipconn2even 245 | self.W_skipconn2even[j,k] = 1.0 246 | 247 | # W_output 248 | idx_row = np.cumsum(self.data.code_parityCheckMatrix[i,0:j+1])[-1] - 1 249 | till_d_c = np.sum(self.data.code_parityCheckMatrix[:i,:]) 250 | self.W_output[int(till_d_c+idx_row), m] = 1.0 251 | 252 | k += 1 253 | m += 1 254 | -------------------------------------------------------------------------------- /scripts/solver.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | 8 | import tensorflow as tf 9 | import numpy as np 10 | from utils import * 11 | 12 | 13 | 14 | class Solver(): 15 | 16 | def __init__(self, args, data, model): 17 | 18 | self.args = args 19 | self.data = data 20 | self.model = model 21 | 22 | def train(self): 23 | """Short summary. 24 | 25 | Returns 26 | ------- 27 | type 28 | Description of returned object. 29 | 30 | """ 31 | 32 | # Init Session 33 | sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) 34 | sess.run(tf.global_variables_initializer()) 35 | merged = tf.summary.merge_all() 36 | saver = tf.train.Saver() 37 | 38 | # Load model 39 | if self.args.weights_path: 40 | saver.restore(sess, self.args.weights_path) 41 | 42 | for i in range(self.args.num_of_batch): 43 | 44 | # Generate data 45 | training_data, training_labels = self.data.get_batch(self.args.train_on_zero_word) 46 | 47 | # Train 48 | y_train, train_loss, _ = sess.run(fetches=[self.model.y_output, self.model.loss, self.model.train_step], feed_dict={self.model.x: training_data, self.model.y: training_labels}) 49 | 50 | # Evaluate 51 | if(i%self.args.batch_in_epoch == 0) and (i != 0): 52 | 53 | y_v = np.zeros([1,self.args.code_n], dtype=self.args.var_type) 54 | y_v_pred = np.zeros([1,self.args.code_n], dtype=self.args.var_type) 55 | loss_v = np.zeros([1, 1], dtype=self.args.var_type) 56 | for kk, k_sf in enumerate(self.data.scaling_factor): 57 | for j in range(self.args.batches_for_val_per_snr_all[kk]): 58 | 59 | x_v_j, y_v_j = self.data.get_batch(self.args.test_on_zero_word, self.args.batch_size, [k_sf]) 60 | y_v_pred_j, loss_v_j = sess.run(fetches = [self.model.y_output, self.model.loss], feed_dict={self.model.x:x_v_j, self.model.y:y_v_j}) 61 | 62 | y_v = np.vstack((y_v,y_v_j)) 63 | y_v_pred = np.vstack((y_v_pred,y_v_pred_j)) 64 | loss_v = np.vstack((loss_v, loss_v_j)) 65 | 66 | y_v_pred = 1.0 / (1.0 + np.exp(-1.0 * y_v_pred)) 67 | ber_val, fer_val = calc_ber_fer(self.args.snr_db, y_v_pred[1:,:], y_v[1:,:], self.args.batch_size*self.args.batches_for_val_per_snr_all) 68 | 69 | # Print results 70 | print('Results for epoch - ', int(i/self.args.batch_in_epoch)) 71 | print('SNR range in [dB] - ', self.args.snr_db) 72 | print('Bit Error rate for validation - ', ber_val) 73 | print('Frame Error rate for validation - ', fer_val) 74 | 75 | # Save weights 76 | saver.save(sess, self.args.weights_path_format % i) 77 | -------------------------------------------------------------------------------- /scripts/utils.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | import numpy as np 8 | 9 | 10 | def calc_ber_fer(snr_db, Y_v_pred, Y_v, batches_for_val_per_snr): 11 | """Short summary. 12 | 13 | Parameters 14 | ---------- 15 | snr_db : type 16 | Description of parameter `snr_db`. 17 | Y_v_pred : type 18 | Description of parameter `Y_v_pred`. 19 | Y_v : type 20 | Description of parameter `Y_v`. 21 | batches_for_val_per_snr : type 22 | Description of parameter `batches_for_val_per_snr`. 23 | 24 | Returns 25 | ------- 26 | type 27 | Description of returned object. 28 | 29 | """ 30 | 31 | ber_test = np.zeros(snr_db.shape[0]) 32 | fer_test = np.zeros(snr_db.shape[0]) 33 | last_ind = 0 34 | 35 | for i in range(0,snr_db.shape[0]): 36 | 37 | numOfWordSim = int(batches_for_val_per_snr[i]*1.0) 38 | Y_v_pred_i = Y_v_pred[last_ind:(last_ind + numOfWordSim),:] 39 | Y_v_i = Y_v[last_ind:(last_ind + numOfWordSim),:] 40 | ber_test[i] = np.abs(((Y_v_pred_i<0.5)-Y_v_i)).sum()/(Y_v_i.shape[0]*Y_v_i.shape[1]) 41 | fer_test[i] = (np.abs(np.abs(((Y_v_pred_i<0.5)-Y_v_i))).sum(axis=1)>0).sum()*1.0/Y_v_i.shape[0] 42 | last_ind = last_ind + numOfWordSim 43 | 44 | return ber_test, fer_test 45 | --------------------------------------------------------------------------------