├── .gitignore ├── .travis.yml ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── deploy-ghpages.sh ├── examples ├── example.png └── example_grad.png ├── index.html ├── src ├── codegen │ ├── eigen.rs │ ├── graphviz.rs │ ├── matlab.rs │ └── mod.rs ├── core │ ├── grammar.rs │ ├── graph.rs │ ├── mod.rs │ ├── node.rs │ ├── operator.rs │ └── parser.rs ├── lib.rs ├── linking.rs ├── main.rs └── optimization │ ├── constant_folding.rs │ └── mod.rs └── tests ├── codegen └── mod.rs ├── core ├── gradient.rs ├── mod.rs └── parser.rs ├── linking ├── linking_rust.rs └── mod.rs ├── macros.rs ├── mod.rs └── optimization ├── constant_folding.rs └── mod.rs /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled files 2 | *.o 3 | *.so 4 | *.rlib 5 | *.dll 6 | 7 | # Executables 8 | *.exe 9 | 10 | # Testing files 11 | *.meta 12 | 13 | # Generated by Cargo 14 | /target/ 15 | 16 | # Personal testing 17 | /kras/ 18 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: nightly 3 | 4 | after_success: 5 | - chmod 775 deploy-ghpages.sh 6 | - ./deploy-ghpages.sh 7 | 8 | env: 9 | global: 10 | - GH_REF: github.com/Botev/meta_diff.git 11 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | [root] 2 | name = "meta_diff" 3 | version = "0.0.1" 4 | dependencies = [ 5 | "docopt 0.6.67 (registry+https://github.com/rust-lang/crates.io-index)", 6 | "rustc-serialize 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)", 7 | "tempdir 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)", 8 | ] 9 | 10 | [[package]] 11 | name = "advapi32-sys" 12 | version = "0.1.2" 13 | source = "registry+https://github.com/rust-lang/crates.io-index" 14 | dependencies = [ 15 | "winapi 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", 16 | "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", 17 | ] 18 | 19 | [[package]] 20 | name = "aho-corasick" 21 | version = "0.2.1" 22 | source = "registry+https://github.com/rust-lang/crates.io-index" 23 | dependencies = [ 24 | "memchr 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", 25 | ] 26 | 27 | [[package]] 28 | name = "docopt" 29 | version = "0.6.67" 30 | source = "registry+https://github.com/rust-lang/crates.io-index" 31 | dependencies = [ 32 | "regex 0.1.38 (registry+https://github.com/rust-lang/crates.io-index)", 33 | "rustc-serialize 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)", 34 | "strsim 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", 35 | ] 36 | 37 | [[package]] 38 | name = "libc" 39 | version = "0.1.8" 40 | source = "registry+https://github.com/rust-lang/crates.io-index" 41 | 42 | [[package]] 43 | name = "memchr" 44 | version = "0.1.3" 45 | source = "registry+https://github.com/rust-lang/crates.io-index" 46 | dependencies = [ 47 | "libc 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", 48 | ] 49 | 50 | [[package]] 51 | name = "rand" 52 | version = "0.3.9" 53 | source = "registry+https://github.com/rust-lang/crates.io-index" 54 | dependencies = [ 55 | "advapi32-sys 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", 56 | "libc 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", 57 | "winapi 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", 58 | ] 59 | 60 | [[package]] 61 | name = "regex" 62 | version = "0.1.38" 63 | source = "registry+https://github.com/rust-lang/crates.io-index" 64 | dependencies = [ 65 | "aho-corasick 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", 66 | "memchr 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", 67 | "regex-syntax 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", 68 | ] 69 | 70 | [[package]] 71 | name = "regex-syntax" 72 | version = "0.1.2" 73 | source = "registry+https://github.com/rust-lang/crates.io-index" 74 | 75 | [[package]] 76 | name = "rustc-serialize" 77 | version = "0.3.15" 78 | source = "registry+https://github.com/rust-lang/crates.io-index" 79 | 80 | [[package]] 81 | name = "strsim" 82 | version = "0.3.0" 83 | source = "registry+https://github.com/rust-lang/crates.io-index" 84 | 85 | [[package]] 86 | name = "tempdir" 87 | version = "0.3.4" 88 | source = "registry+https://github.com/rust-lang/crates.io-index" 89 | dependencies = [ 90 | "rand 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", 91 | ] 92 | 93 | [[package]] 94 | name = "winapi" 95 | version = "0.2.1" 96 | source = "registry+https://github.com/rust-lang/crates.io-index" 97 | 98 | [[package]] 99 | name = "winapi-build" 100 | version = "0.1.1" 101 | source = "registry+https://github.com/rust-lang/crates.io-index" 102 | 103 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "meta_diff" 3 | version = "0.0.1" 4 | authors = ["Alexander Botev "] 5 | description = "Autodiff tool for developing scalable Machine Learning algorithms across different platforms with a single source file." 6 | documentation = "http://botev.github.io/meta_diff/index.html" 7 | homepage = "https://github.com/Botev/meta_diff" 8 | repository = "https://github.com/Botev/meta_diff" 9 | readme = "README.md" 10 | keywords = ["autodiff","machine-learning","deep-learning"] 11 | license = "GPL-3.0+" 12 | 13 | [lib] 14 | name = "meta_diff" 15 | path = "src/lib.rs" 16 | test = true 17 | doctest = true 18 | bench = true 19 | doc = true 20 | 21 | [[bin]] 22 | name = "diff" 23 | path = "src/main.rs" 24 | test = false 25 | 26 | [dependencies] 27 | docopt = "*" 28 | rustc-serialize = "*" 29 | tempdir = "0.3.4" 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Meta Diff 2 | [![Build Status](https://travis-ci.org/Botev/meta_diff.svg?branch=master)](https://travis-ci.org/Botev/meta_diff) 3 | [![Crates.io](https://img.shields.io/crates/v/meta_diff.svg)](https://crates.io/crates/meta_diff) 4 | [![License](http://img.shields.io/:license-GPLv3+-blue.svg)](https://github.com/Botev/meta_diff/blob/master/LICENSE) 5 | 6 | Meta Diff is a tool for automatic differentiation and code generation for developing scalable Machine Learning algorithms across different platforms with a single source file. It is implemented in Rust and will be distributed as binaries for different platforms. 7 | 8 | [Documentation website] (http://botev.github.io/meta_diff/index.html) 9 | 10 | ## Usage and Installation 11 | 12 | When the project is ready it will be distributed as a binary file and will not requrie any form of installation. The usage is from the command line in the format: 13 | 14 | ```cmd 15 | diff 16 | 17 | ``` 18 | The command will create a new folder in the current directory with the name of the input file and in it you will find all of the auto generate sources. Note that these might need to be compiled on their own (in the case of C/C++, CUDA or OpenCL) or might directly be used (in the case of Matlab or Python). 19 | 20 | ## The source language 21 | 22 | The source file follows a subset of Matlab syntax, but has several important differences. The parser has been generated from the `grammar.rs` file using [rust-peg] (https://github.com/kevinmehall/rust-peg) with small alternations. 23 | 24 | Consider the simple source file below for a feed forward network: 25 | 26 | ```matlab 27 | function [L] = mat(@w1,@w2,x,y) 28 | h = tanh(w1 dot vertcat(x,1)); 29 | h = tanh(w2 dot vertcat(h,1)); 30 | L = l2(h-y,0); 31 | end 32 | ``` 33 | 34 | The first line defines a funciton `mat` with four arguments - the first two are parameters and the second two are constatns, which means no gradients will be taken with respect to them. All of the standard operation are considered to be an elementwise operation. Thus the operator `*` is the so called Hadammart product. The multiplications in the Linear Algebra sense is implemented via the keyword `dot`. Thus, this snippet calclulates a forward pass over a network, by adding a bias term to each layer using `vertcat`. The last line specify that we are taking an `L2` squared norm of `h-y`. The second argument to the function specifies along which dimension and `0` has the meaning of all dimensions. When parsing the tool will automatically take a gradient operation, thus for the example this results in the following computation graph (picutre generated by the graphviz module): 35 | 36 | ![gradient](https://github.com/Botev/meta_diff/blob/master/examples/example_grad.png?raw=true "Gradient Graph") 37 | 38 | ## Current stage of development 39 | 40 | At the moment the core building blocks of the project have been implemented - the `ComputeGraph` and the parser. 41 | Currently there are several very important parts which are being implemented: 42 | 43 | 1. Optimisation over the structure of the computation gprah 44 | * Pruning - remove any nodes, which are irrelevant to the output 45 | * Removing redundacies - exhcange nodes which preform the same computation with a single node 46 | * Inverse manipulation - functions which perform an invertion to be replaced by original node - e.g. `log(exp(x))` converted to `x` 47 | * Constants folding - combine constatns present in the same operation 48 | * Negation and Division reordering - e.g. convert `-(b + c) + d` to `(-b) + (-c) + d` 49 | * Collect n-ary oeprators - e.g. convert `(a+b) + (c+d)` to `a + b + c + d` 50 | * Logarithm of a multiplication operator to be exchanged by a sum of lograithm operators 51 | * Product of exponential operators to be exchanged by an exponential of the sum 52 | * Sub indexing optimisation 53 | 2. Matlab and Eigen code generators 54 | 55 | ## Future goals 56 | 57 | There are troumendous amount of possible extensions that can be done in time, but currently what is considered to be the most crucial are: 58 | 59 | 1. Consideration of array support, or some form of map reduce functionality 60 | 2. For loops and sub routines importing 61 | 3. OpenCL or CUDA code generation 62 | 4. Hessian-vector product 63 | 64 | Please for any suggestions open an Issue on the issues tracker. 65 | Also if you happen to implement some interesting examples please notify us to add them to the example folder! 66 | -------------------------------------------------------------------------------- /deploy-ghpages.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | cargo doc 3 | (cd target/doc 4 | git init 5 | git config user.name "Botev" 6 | git config user.email "botevmg@gmail.com" 7 | cp ../../README.md ./README.md 8 | cp ../../LICENSE ./LICENSE 9 | cp ../../index.html ./index.html 10 | cp -r ../../examples . 11 | git add . 12 | git commit -m "Deployed to Github Pages" 13 | git push --force --quiet "https://${GH_TOKEN}@${GH_REF}" master:gh-pages) 14 | -------------------------------------------------------------------------------- /examples/example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/botev/meta_diff/2499d7c5885f98324c3f8afe5cdede8c9b624104/examples/example.png -------------------------------------------------------------------------------- /examples/example_grad.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/botev/meta_diff/2499d7c5885f98324c3f8afe5cdede8c9b624104/examples/example_grad.png -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Meta Diff Docs 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/codegen/eigen.rs: -------------------------------------------------------------------------------- 1 | use std::io::{Write, Error}; 2 | use std::result::Result; 3 | use core::ComputeGraph; 4 | 5 | pub fn write_eigen(fmt: &mut Write, graph: & ComputeGraph) -> Result<(),Error>{ 6 | write!(fmt, "{}", graph.nodes.len()) 7 | } 8 | -------------------------------------------------------------------------------- /src/codegen/graphviz.rs: -------------------------------------------------------------------------------- 1 | use std::io::{Write, Error}; 2 | use std::result::Result; 3 | use core::*; 4 | 5 | static HEADING: &'static str = 6 | "digraph G{ 7 | bgcolor=\"transparent\"; 8 | ranksep=.75; 9 | node [shape=box, fontsize=16, style=filled]; 10 | subgraph cluster_0{ 11 | label=\"Forward Calculations\"; 12 | "; 13 | static MIDDLE: &'static str = 14 | " } 15 | subgraph cluster_1{ 16 | label=\"Gradient Calculations\"; 17 | "; 18 | static MIDDLE_2: &'static str = 19 | " } 20 | subgraph cluster_2{ 21 | label=\"Hessian Calculations\"; 22 | "; 23 | 24 | 25 | 26 | pub fn write_graphviz(fmt: &mut Write, graph: & ComputeGraph) -> Result<(),Error>{ 27 | try!(write!(fmt, "{}", HEADING)); 28 | let target = graph.outputs[0]; 29 | let outputs = graph.outputs.clone(); 30 | // Forward Calculation 31 | for option in graph.nodes.iter(){ 32 | match *option{ 33 | None => (), 34 | Some(ref value) => match { 35 | if value.grad_level != 0 { 36 | continue; 37 | } 38 | if outputs.contains(&value.id){ 39 | write_node(fmt, value, &value.name, "red", "ellipse") 40 | } 41 | else { 42 | match value.node_type { 43 | Type::Float(_) | Type::Integer(_) => write_node(fmt, value, &value.name, "yellow", "rectangle"), 44 | Type::ConstInput => write_node(fmt, value, &value.name, "orange", "rectangle"), 45 | Type::ConstDerived => write_node(fmt, value, &value.name, "orangered", "rectangle"), 46 | Type::Parameter => write_node(fmt, value, &value.name, "green", "rectangle"), 47 | Type::ParameterDerived => write_node(fmt, value, &value.name, "blue", "rectangle") 48 | } 49 | } 50 | } { 51 | Ok(()) => (), 52 | Err(msg) => return Err(msg) 53 | } 54 | } 55 | } 56 | try!(write!(fmt, "{}", MIDDLE)); 57 | // Backward Calculation 58 | for option in graph.nodes.iter(){ 59 | match *option{ 60 | None => (), 61 | Some(ref value) => match { 62 | if value.grad_level != 1 { 63 | continue; 64 | } 65 | let mut name = &format!("GradOf{:?}",value.grad_parents); 66 | if value.grad_parents.len() == 0 { 67 | name = &value.name; 68 | } 69 | if value.id == target { 70 | write_node(fmt, value, name, "green", "ellipse") 71 | } 72 | else if outputs.contains(&value.id){ 73 | write_node(fmt, value, name, "red", "ellipse") 74 | } 75 | else { 76 | match value.node_type { 77 | Type::Float(_) | Type::Integer(_) => write_node(fmt, value, name, "yellow", "rectangle"), 78 | Type::ConstInput => write_node(fmt, value, name, "orange", "rectangle"), 79 | Type::ConstDerived => write_node(fmt, value, name, "orangered", "rectangle"), 80 | Type::Parameter => write_node(fmt, value, name, "green", "rectangle"), 81 | Type::ParameterDerived => write_node(fmt, value, name, "blue", "rectangle") 82 | } 83 | } 84 | } { 85 | Ok(()) => (), 86 | Err(msg) => return Err(msg) 87 | } 88 | } 89 | } 90 | try!(write!(fmt, "{}", MIDDLE_2)); 91 | // Hessian order 92 | for option in graph.nodes.iter(){ 93 | match *option{ 94 | None => (), 95 | Some(ref value) => match { 96 | if value.grad_level != 2 { 97 | continue; 98 | } 99 | let mut name = &format!("GradOf{:?}",value.grad_parents); 100 | if value.grad_parents.len() == 0 { 101 | name = &value.name; 102 | } 103 | if value.id == target { 104 | write_node(fmt, value, name, "green", "ellipse") 105 | } 106 | else if outputs.contains(&value.id){ 107 | write_node(fmt, value, name, "red", "ellipse") 108 | } 109 | else { 110 | match value.node_type { 111 | Type::Float(_) | Type::Integer(_) => write_node(fmt, value, name, "yellow", "rectangle"), 112 | Type::ConstInput => write_node(fmt, value, name, "orange", "rectangle"), 113 | Type::ConstDerived => write_node(fmt, value, name, "orangered", "rectangle"), 114 | Type::Parameter => write_node(fmt, value, name, "green", "rectangle"), 115 | Type::ParameterDerived => write_node(fmt, value, name, "blue", "rectangle") 116 | } 117 | } 118 | } { 119 | Ok(()) => (), 120 | Err(msg) => return Err(msg) 121 | } 122 | } 123 | } 124 | try!(write!(fmt, "{}", "\t}\n")); 125 | // Write connections 126 | for option in graph.nodes.iter(){ 127 | match *option{ 128 | None => (), 129 | Some(ref value) => match { 130 | for child in value.children.iter(){ 131 | try!(write!(fmt, "\t{} -> {};\n", value.id, child)); 132 | } 133 | Ok(()) 134 | } { 135 | Ok(()) => (), 136 | Err(msg) => return Err(msg) 137 | } 138 | } 139 | } 140 | try!(write!(fmt, "{}", "}\n")); 141 | Ok(()) 142 | } 143 | 144 | #[inline(always)] 145 | fn write_node(fmt: &mut Write, node: &ComputeNode, name: &str, color:&str, shape: &str) -> Result<(),Error>{ 146 | write!(fmt,"\t\t{id}[label=\"{name}\\nId:{id}\\n{op}\"][fillcolor={color},shape={shape}];\n" 147 | , id=node.id, name=name,op=format!("{:?}",node.op.op_type), color=color, shape=shape) 148 | } 149 | -------------------------------------------------------------------------------- /src/codegen/matlab.rs: -------------------------------------------------------------------------------- 1 | use std::io::{Write, Error}; 2 | use std::result::Result; 3 | use core::ComputeGraph; 4 | 5 | pub fn write_matlab(fmt: &mut Write, graph: & ComputeGraph) -> Result<(),Error>{ 6 | write!(fmt, "{}", graph.nodes.len()) 7 | } 8 | -------------------------------------------------------------------------------- /src/codegen/mod.rs: -------------------------------------------------------------------------------- 1 | mod eigen; 2 | mod matlab; 3 | mod graphviz; 4 | 5 | pub use self::graphviz::write_graphviz; 6 | pub use self::matlab::write_matlab; 7 | pub use self::eigen::write_eigen; 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/core/grammar.rs: -------------------------------------------------------------------------------- 1 | use std::collections::{HashMap, HashSet}; 2 | use super::operator::*; 3 | use super::node::*; 4 | use super::graph::*; 5 | 6 | #[context] 7 | graph_res -> Result = {Ok(ComputeGraph::new())} 8 | #[context] 9 | variable_table -> HashMap = {HashMap::new()} 10 | 11 | // ================================================================== 12 | // PARSER RULES 13 | // 14 | 15 | #[pub] 16 | metaFile -> Result = functionDefinition {graph_res.clone()} 17 | 18 | /// Set the name of the graph add all outputs and set target to the first output 19 | functionDefinition = (eol / __)* FUNCTION __ outputs: functionReturn __? EQ __? main:ID __? mainParamList eol statementList END (eol / __)* { 20 | let mut result : Result<(),ParseError> = Ok(()); 21 | match *graph_res{ 22 | Ok(ref mut graph) => { 23 | graph.name = main; 24 | for output in outputs.iter(){ 25 | match variable_table.get(output){ 26 | Some(id) => { 27 | // println!("Target {} is {}", output, *id); 28 | graph.outputs.push(*id); 29 | }, 30 | None => { 31 | result = result_err!(input, state, 32 | format!("Output variable \'{}\' has not been defined", output)); 33 | // println!("{:?}", result); 34 | break; 35 | } 36 | } 37 | } 38 | }, 39 | Err(ref msg) => {result = Err(msg.clone());} 40 | } 41 | match result { 42 | Ok(_) => (), 43 | Err(msg) => {*graph_res = Err(msg);} 44 | } 45 | } 46 | 47 | /// Return all of the outputs names 48 | functionReturn -> Vec = LSBRACE __? ids: ID ++ (__? COMMA) __? RSBRACE {ids} 49 | 50 | /// Only match pattern 51 | mainParamList = LPAREN __? inputVar ++ (__? COMMA) __? RPAREN 52 | 53 | /// Add all of the inputs to the variable table and in to the graph 54 | inputVar = param: AT? name:ID { 55 | if ComputeGraph::is_function_name(&name) { 56 | *graph_res = result_err!(input, state, 57 | format!("Can not have a variable with name \'{}\' since it is a built in function", name)) 58 | } 59 | else{ 60 | match *graph_res{ 61 | Ok(ref mut graph) => match param { 62 | Some(_) => {variable_table.insert(name.clone(),graph.add_parameter(name));()}, 63 | None => {variable_table.insert(name.clone(),graph.add_const_input(name));()} 64 | }, 65 | Err(_) => (), 66 | } 67 | } 68 | } 69 | 70 | /// Only match pattern 71 | statementList = ((eol / comment/ __)* statement)* (eol / comment/ __)* 72 | 73 | /// Insert the variable on the left to represent the graph node of the expression on the right 74 | statement = name: ID __? EQ __? id:expression __? SEMI { 75 | let result = match *graph_res{ 76 | Ok(ref mut graph) => { 77 | if ComputeGraph::is_function_name(&name) { 78 | result_err!(input, state, 79 | format!("Can not have a variable with name \'{}\' since it is a built in function", name)) 80 | } 81 | else{ 82 | variable_table.insert(name,id); 83 | Ok(()) 84 | } 85 | }, 86 | Err(ref msg) => Err(msg.clone()) 87 | }; 88 | match result { 89 | Ok(var) => var, 90 | Err(msg) => {*graph_res = Err(msg);} 91 | } 92 | } 93 | 94 | /// Logical operators 95 | g1 -> OperatorType = 96 | GTE {OPERATOR_GTE} 97 | / GT {OPERATOR_GT} 98 | / LTE {OPERATOR_LTE} 99 | / LT {OPERATOR_LT} 100 | / NEQ {OPERATOR_NEQ} 101 | / DOUBLE_EQ {OPERATOR_EQ} 102 | 103 | /// Plus or Minus operators 104 | g2 -> bool 105 | = PLUS {true} 106 | / MINUS {false} 107 | 108 | /// Multiplication and division operators 109 | g3 -> bool 110 | = TIMES {true} 111 | / DIVISION {false} 112 | 113 | /// Currently the logical operators are not supported 114 | expression -> usize = first: e1 second:(__? op:g1 __? var:expression{(op,var)})? { 115 | let result = match *graph_res{ 116 | Ok(ref mut graph) => match second { 117 | Some(tuple) => match graph.add_operation(tuple.0, vec![first, tuple.1]) { 118 | Ok(var) => Ok(var), 119 | Err(err) => result_err!(input, state, format!("{}",err)) 120 | }, 121 | None => Ok(first) 122 | }, 123 | Err(ref msg) => Err(msg.clone()) 124 | }; 125 | match result { 126 | Ok(var) => var, 127 | Err(msg) => {*graph_res = Err(msg); 0} 128 | } 129 | } 130 | 131 | /// Addition or subtraction, however subtraction in the graph is represented as 132 | /// addition and unary negation 133 | e1 -> usize = first: e2 rest:( __? op:g2 __? var:e2 { 134 | let result = match *graph_res{ 135 | Ok(ref mut graph) => { 136 | if op { 137 | Ok(var) 138 | } else { 139 | match graph.add_operation(OPERATOR_NEG, vec![var]) { 140 | Ok(var) => Ok(var), 141 | Err(err) => result_err!(input, state, format!("{}",err)) 142 | } 143 | } 144 | }, 145 | Err(ref msg) => Err(msg.clone()) 146 | }; 147 | match result { 148 | Ok(var) => var, 149 | Err(msg) => {*graph_res = Err(msg); 0} 150 | } 151 | })* { 152 | let result = match *graph_res{ 153 | Ok(ref mut graph) => match rest.len() { 154 | 0 => Ok(first), 155 | _ => { 156 | let mut vars = vec![first]; 157 | vars.extend(rest); 158 | match graph.add_operation(OPERATOR_ADD, vars) { 159 | Ok(var) => Ok(var), 160 | Err(err) => result_err!(input, state, format!("{}",err)) 161 | } 162 | } 163 | }, 164 | Err(ref msg) => Err(msg.clone()) 165 | }; 166 | match result { 167 | Ok(var) => var, 168 | Err(msg) => {*graph_res = Err(msg); 0} 169 | } 170 | } 171 | 172 | /// Multiplication and division, however division in the graph is represented as 173 | /// multiplication and unary division 174 | e2 -> usize = first: e3 rest:( __? op:g3 __? var:e3 { 175 | let result = match *graph_res{ 176 | Ok(ref mut graph) => { 177 | if op { 178 | Ok(var) 179 | } else { 180 | match graph.add_operation(OPERATOR_DIV, vec![var]) { 181 | Ok(var) => Ok(var), 182 | Err(err) => result_err!(input, state, format!("{}",err)) 183 | } 184 | } 185 | }, 186 | Err(ref msg) => Err(msg.clone()) 187 | }; 188 | match result { 189 | Ok(var) => var, 190 | Err(msg) => {*graph_res = Err(msg); 0} 191 | } 192 | })* { 193 | let result = match *graph_res{ 194 | Ok(ref mut graph) => match rest.len() { 195 | 0 => Ok(first), 196 | _ => { 197 | let mut vars = vec![first]; 198 | vars.extend(rest); 199 | match graph.add_operation(OPERATOR_MUL, vars) { 200 | Ok(var) => Ok(var), 201 | Err(err) => result_err!(input, state, format!("{}",err)) 202 | } 203 | } 204 | }, 205 | Err(ref msg) => Err(msg.clone()) 206 | }; 207 | match result { 208 | Ok(var) => var, 209 | Err(msg) => {*graph_res = Err(msg); 0} 210 | } 211 | } 212 | 213 | /// Matrix multiplication - having higher precedence than normal 214 | e3 -> usize = vars: e4 ++ (__? DOT_PRODUCT __?) { 215 | let result = match *graph_res{ 216 | Ok(ref mut graph) => match vars.len() { 217 | 0 => unreachable!(), 218 | 1 => Ok(vars[0]), 219 | _ => match graph.add_operation(OPERATOR_DOT, vars) { 220 | Ok(var) => Ok(var), 221 | Err(err) => result_err!(input, state, format!("{}",err)) 222 | } 223 | }, 224 | Err(ref msg) => Err(msg.clone()) 225 | }; 226 | match result { 227 | Ok(var) => var, 228 | Err(msg) => {*graph_res = Err(msg); 0} 229 | } 230 | } 231 | 232 | /// Unary negation 233 | e4 -> usize = m:MINUS? __? var: e5 { 234 | let result = match *graph_res{ 235 | Ok(ref mut graph) => match m { 236 | Some(_) => match graph.add_operation(OPERATOR_NEG,vec![var]) { 237 | Ok(var) => Ok(var), 238 | Err(err) => result_err!(input, state, format!("{}",err)) 239 | }, 240 | None => Ok(var) 241 | }, 242 | Err(ref msg) => Err(msg.clone()) 243 | }; 244 | match result { 245 | Ok(var) => var, 246 | Err(msg) => {*graph_res = Err(msg); 0} 247 | } 248 | } 249 | 250 | /// Powering one value by another 251 | e5 -> usize = first: e6 second: (__? EXP __? var:e6 {var})? { 252 | let result = match *graph_res{ 253 | Ok(ref mut graph) => match second{ 254 | Some(id) => match graph.add_operation(OPERATOR_POW,vec![first,id]) { 255 | Ok(var) => Ok(var), 256 | Err(err) => result_err!(input, state, format!("{}",err)) 257 | }, 258 | None => Ok(first) 259 | }, 260 | Err(ref msg) => Err(msg.clone()) 261 | }; 262 | match result { 263 | Ok(var) => var, 264 | Err(msg) => {*graph_res = Err(msg); 0} 265 | } 266 | } 267 | 268 | /// Transpose 269 | e6 -> usize = var: unaryExpression tr: TRANSPOSE? { 270 | let mut result = match *graph_res{ 271 | Ok(ref mut graph) => match tr{ 272 | Some(_) => match graph.add_operation(OPERATOR_TRANSPOSE,vec![var]) { 273 | Ok(var) => Ok(var), 274 | Err(err) => result_err!(input, state, format!("{}",err)) 275 | }, 276 | None => Ok(var) 277 | }, 278 | Err(ref msg) => Err(msg.clone()) 279 | }; 280 | match result { 281 | Ok(var) => var, 282 | Err(msg) => {*graph_res = Err(msg); 0} 283 | } 284 | } 285 | 286 | /// Unary expression 287 | unaryExpression -> usize = baseExpression / (LPAREN __? e:expression __? RPAREN {e}) 288 | 289 | /// Only if this is an ID we have to check if it is in the variable table 290 | baseExpression -> usize = NUMBER / indexedVar / varDotFunc / funcCall / name:ID { 291 | let result = match *graph_res{ 292 | Ok(ref mut graph) => match variable_table.get(&name) { 293 | Some(id) => Ok(*id), 294 | None => result_err!(input, state, format!("Use of undefined variable \'{}\'", name)) 295 | }, 296 | Err(ref msg) => Err(msg.clone()) 297 | }; 298 | match result { 299 | Ok(var) => var, 300 | Err(msg) => {*graph_res = Err(msg); 0} 301 | } 302 | } 303 | 304 | /// Index a variable - var[arg1,arg2,arg3,arg4] 305 | indexedVar -> usize = name: ID LSBRACE __? arg1: expression __? COMMA __? arg2:expression __? COMMA __? 306 | arg3:expression __? COMMA __? arg4:expression __? RSBRACE { 307 | let result = match *graph_res{ 308 | Ok(ref mut graph) => match variable_table.get(&name) { 309 | Some(id) => match graph.add_operation( 310 | OPERATOR_SUBINDEX,vec![*id,arg1,arg2,arg3,arg4]) { 311 | Ok(var) => Ok(var), 312 | Err(err) => result_err!(input, state, format!("{}",err)) 313 | }, 314 | None => result_err!(input, state, format!("Use of undefined variable \'{}\'", name)) 315 | }, 316 | Err(ref msg) => Err(msg.clone()) 317 | }; 318 | match result { 319 | Ok(var) => var, 320 | Err(msg) => {*graph_res = Err(msg); 0} 321 | } 322 | } 323 | 324 | /// Call on a variable an unary function - var.func(args) 325 | varDotFunc -> usize = name:ID DOT func:ID args:paramList { 326 | let result = match *graph_res{ 327 | Ok(ref mut graph) => match variable_table.get(&name){ 328 | Some(id) => { 329 | let mut newargs = args.clone(); 330 | newargs.insert(0,*id); 331 | if ComputeGraph::is_function_name(&func) { 332 | match graph.string_to_operator(func, newargs) { 333 | Ok(var) => Ok(var), 334 | Err(err) => result_err!(input, state, format!("{}",err)) 335 | } 336 | } else { 337 | result_err!(input, state, format!("Use of undefined function \'{}\'", func)) 338 | } 339 | }, 340 | None => result_err!(input, state, format!("Use of undefined variable \'{}\'", name)) 341 | }, 342 | Err(ref msg) => Err(msg.clone()) 343 | }; 344 | match result { 345 | Ok(var) => var, 346 | Err(msg) => {*graph_res = Err(msg); 0} 347 | } 348 | } 349 | 350 | /// Function call 351 | funcCall -> usize = func:ID args:paramList { 352 | let result = match *graph_res{ 353 | Ok(ref mut graph) => { 354 | if ComputeGraph::is_function_name(&func) { 355 | match graph.string_to_operator(func, args) { 356 | Ok(var) => Ok(var), 357 | Err(err) => result_err!(input, state, format!("{}",err)) 358 | } 359 | } else { 360 | result_err!(input, state, format!("Use of undefined function \'{}\'", func)) 361 | } 362 | }, 363 | Err(ref msg) => Err(msg.clone()) 364 | }; 365 | match result { 366 | Ok(var) => var, 367 | Err(msg) => {*graph_res = Err(msg); 0} 368 | } 369 | } 370 | 371 | /// Parameter list 372 | paramList -> Vec = LPAREN __? vars: expression ** (__? COMMA __?) __? RPAREN{ 373 | vars 374 | } 375 | 376 | // ================================================================== 377 | // LEXER RULES 378 | // 379 | 380 | // 381 | // language keywords 382 | // 383 | 384 | // BREAK = "break"; 385 | // CASE = "case"; 386 | // CATCH = "catch"; 387 | // CONTINUE= "continue"; 388 | // ELSE = "else"; 389 | // ELSEIF = "elseif"; 390 | END = "end"; 391 | // FOR = "for"; 392 | FUNCTION= "function"; 393 | // GLOBAL = "global"; 394 | // IF = "if"; 395 | // OTHERWISE= "otherwise"; 396 | // PERSISTENT= "persistent"; 397 | // RETURNS = "return"; 398 | // SWITCH = "switch"; 399 | // TRY = "try"; 400 | // WHILE = "while"; 401 | // CLEAR = "clear"; 402 | // VARARGIN= "varargin"; 403 | // NARGIN= "nargin"; 404 | // VARARGOUT= "varargout"; 405 | // NARGOUT= "nargout"; 406 | // HOLDON = "hold on"; 407 | // PAUSE = "pause"; 408 | // PARAMS= "params"; 409 | 410 | // Operators and assignments 411 | // 412 | 413 | 414 | // // Binary - Not supported 415 | // BIN_OR = "|"; 416 | // BIN_AND = "&"; 417 | 418 | // Logical - Not supported 419 | // LOG_OR = "||"; 420 | // LOG_AND = "&&"; 421 | 422 | // Comparison - Not supported 423 | DOUBLE_EQ = "=="; 424 | NEQ = "~="; 425 | LTE = "<="; 426 | GTE = ">="; 427 | LT = "<"; 428 | GT = ">"; 429 | EQ = "="; 430 | 431 | // Standard arithmetic 432 | PLUS = "+"; 433 | MINUS = "-"; 434 | TIMES = "*"; 435 | DIVISION = "/"; 436 | EXP = "^"; 437 | TRANSPOSE = "\'"; 438 | DOT_PRODUCT = "dot"; 439 | 440 | // 441 | // Other useful language snippets 442 | // 443 | 444 | SEMI = ";"; 445 | LPAREN = "("; 446 | RPAREN = ")"; 447 | LBRACE = "{"; 448 | RBRACE = "}"; 449 | LSBRACE = "["; 450 | RSBRACE = "]"; 451 | AT = "@"; 452 | DOT = "."; 453 | COMMA = ","; 454 | 455 | 456 | // 457 | // Identifiers, numbers, strings, linecomennts and whitespace 458 | // 459 | 460 | ID -> String = [a-zA-Z] [a-zA-Z0-9_]* { match_str.to_string() } 461 | 462 | NUMBER -> usize = [0-9]+ ('.' [0-9]+)? { 463 | let result = match *graph_res{ 464 | Ok(ref mut graph) => match match_str.parse::(){ 465 | Ok(value) => Ok(graph.add_int(value)), 466 | Err(_) => match match_str.parse::(){ 467 | Ok(value) => Ok(graph.add_float(value)), 468 | Err(_) => unreachable!() 469 | } 470 | }, 471 | Err(ref msg) => Err(msg.clone()) 472 | }; 473 | match result { 474 | Ok(var) => var, 475 | Err(msg) => {*graph_res = Err(msg); 0} 476 | } 477 | } 478 | 479 | comment = "%" (!eolChar .)* 480 | 481 | /* Modeled after ECMA-262, 5th ed., 7.3. */ 482 | eol 483 | = "\n" 484 | / "\r\n" 485 | / "\r" 486 | / "\u{2028}" 487 | / "\u{2029}" 488 | 489 | eolChar 490 | = [\n\r\u2028\u2029] 491 | 492 | /* Modeled after ECMA-262, 5th ed., 7.2. - whitespace */ 493 | __ = [ \t\u{00A0}\u{FEFF}\u{1680}\u{180E}\u{2000}-\u{200A}\u{202F}\u{205F}\u{3000}] // \v\f removed 494 | 495 | 496 | // pub fn metaFile<'input>(input: &'input str) 497 | // -> ParseResult { 498 | // let mut state = ParseState::new(); 499 | // match parse_metaFile(input, &mut state, 0) { 500 | // Matched(pos, value) => { if pos == input.len() { return value } } 501 | // _ => { } 502 | // } 503 | // let (line, col) = pos_to_line(input, state.max_err_pos); 504 | // Err(ParseError{line: line, 505 | // column: col, 506 | // offset: state.max_err_pos, 507 | // expected: state.expected, 508 | // msg: None,}) 509 | // } 510 | // 511 | // 512 | // macro_rules! result_err { 513 | // ($input:ident , $state:ident , $msg:expr) => { 514 | // { 515 | // let (line, col) = pos_to_line($input, $state.max_err_pos); 516 | // Err(ParseError{line: line, column: col, offset: $state.max_err_pos, 517 | // expected: HashSet::new(), msg: Some($msg)}) 518 | // } 519 | // }; 520 | // } 521 | -------------------------------------------------------------------------------- /src/core/graph.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::{Display, Formatter, Error}; 2 | use std::string::ToString; 3 | use std::collections::HashMap; 4 | // use std::collections::vec_deque::VecDeque; 5 | use super::operator::*; 6 | use super::node::*; 7 | 8 | 9 | 10 | /// The core of this module - this structure contains the full compute graph 11 | #[derive(Clone, Debug, PartialEq)] 12 | pub struct ComputeGraph{ 13 | counter: usize, 14 | grad_level: u8, 15 | pub name: String, 16 | pub nodes: Vec>, 17 | pub ordering: Vec, 18 | pub outputs: Vec, 19 | // pub variable_table: HashMap, 20 | // symbolic_table: Vec, 21 | // symbloic_parents: Vec, 22 | // symbolic_vars: usize 23 | } 24 | 25 | impl Display for ComputeGraph{ 26 | fn fmt(&self, f : &mut Formatter) -> Result<(), Error> { 27 | try!(write!(f, concat!("============ Graph {} ============\n", 28 | "Number of nodes:{}\n", 29 | "Outputs:{:?}\n" , 30 | "============= Nodes =============\n"), 31 | self.name, self.counter, self.outputs)); 32 | for node_opt in self.nodes.iter(){ 33 | match *node_opt { 34 | Some(ref node) => try!(write!(f,"{}\n",node)), 35 | None => {} 36 | } 37 | } 38 | write!(f, "============ Graph End ============") 39 | } 40 | } 41 | 42 | impl ComputeGraph{ 43 | /// Returns the number of nodes in the graph 44 | pub fn len(&self) -> usize { 45 | self.nodes.iter().fold(0, |acc,x| if x.is_some() {acc + 1} else {acc}) 46 | } 47 | 48 | /// Inserts the node argument at the end of the grpah and of the ordering, also assigning it the correct id. 49 | fn insert_new(&mut self, mut node: ComputeNode) -> usize{ 50 | node.id = self.counter; 51 | self.nodes.push(Some(node)); 52 | self.ordering.push(self.counter); 53 | self.counter += 1; 54 | return self.counter-1 55 | } 56 | 57 | /// Removes the last element from the graph 58 | fn remove_last(&mut self) -> Result { 59 | let last_id = self.counter-1; 60 | let has_children = try!(self.get_node(last_id)).children.len() > 0; 61 | if !has_children { 62 | let order = self.ordering.iter().position(|&x| x == self.counter-1).unwrap(); 63 | self.counter -= 1; 64 | self.nodes.remove(self.counter); 65 | self.ordering.remove(order); 66 | Ok(order) 67 | } else { 68 | Err(GraphError::LastHasChildren) 69 | } 70 | 71 | } 72 | 73 | /// Create a new compute graph for a function with the input name 74 | pub fn new() -> Self{ 75 | return ComputeGraph{name: "main".to_string(), counter: 0, grad_level: 0, nodes: Vec::new(), ordering: Vec::new(), outputs: Vec::new()} 76 | } 77 | 78 | /// Creates a new `Parameter` variable with the given name, inserts it in the variable table and returns its id 79 | pub fn add_parameter(&mut self, name: String) -> usize { 80 | let mut node = ComputeNode::new(0, Type::Parameter, self.grad_level, 81 | Operator::new(From::from(ConstantOperatorType::None), vec![], vec![]).unwrap()); 82 | node.name = name; 83 | self.insert_new(node) 84 | } 85 | 86 | /// Creates a new `Float` variable and returns its id 87 | pub fn add_float(&mut self, value: f64) -> usize{ 88 | let node = ComputeNode::new(0, Type::Float(value), self.grad_level, 89 | Operator::new(From::from(ConstantOperatorType::None), vec![], vec![]).unwrap()); 90 | self.insert_new(node) 91 | } 92 | 93 | /// Creates a new `Integer` variable and returns its id 94 | pub fn add_int(&mut self, value: i64) -> usize{ 95 | let node = ComputeNode::new(0, Type::Integer(value), self.grad_level, 96 | Operator::new(From::from(ConstantOperatorType::None), vec![], vec![]).unwrap()); 97 | self.insert_new(node) 98 | } 99 | 100 | /// Creates a new `ConstInput` variable with the given name, inserts it in the variable table and returns its id 101 | pub fn add_const_input(&mut self, name: String) -> usize{ 102 | let mut node = ComputeNode::new(0, Type::ConstInput, self.grad_level, 103 | Operator::new(From::from(ConstantOperatorType::None), vec![], vec![]).unwrap()); 104 | node.name = name; 105 | self.insert_new(node) 106 | } 107 | 108 | /// Adds a variable coresponding to the input operation to the graph 109 | pub fn add_operation(&mut self, op_type: OperatorType, args: Vec) 110 | -> Result { 111 | let mut node_type = Type::ConstDerived; 112 | let id = self.counter; 113 | let mut op_p : Vec = Vec::new(); 114 | let mut op_args : Vec = Vec::new(); 115 | match op_type { 116 | OperatorType::Special(_) => { 117 | // First argument is the parent all others are the arguments 118 | if args.len() > 0 { 119 | op_p.push(args[0]); 120 | } 121 | if args.len() > 1 { 122 | op_args.extend(&args[1..]); 123 | } 124 | } 125 | OperatorType::Constant(_) => { 126 | // All arguments are the parents 127 | op_p = args; 128 | }, 129 | _ => { 130 | for i in args.iter(){ 131 | // All arguments are the paretns, check if some of them are parameter dependent 132 | match try!(self.get_mut_node(*i)).node_type { 133 | Type::Parameter | Type::ParameterDerived => node_type = Type::ParameterDerived, 134 | _ => () 135 | } 136 | } 137 | op_p = args; 138 | } 139 | }; 140 | // Create the new node 141 | let operator = try!(Operator::new(op_type,op_p,op_args)); 142 | // Insert the id as a child of all ancestros 143 | for i in operator.get_ancestors(){ 144 | try!(self.get_mut_node(*i)).children.push(id); 145 | } 146 | let node = ComputeNode::new(0, node_type, self.grad_level, operator); 147 | Ok(self.insert_new(node)) 148 | } 149 | 150 | /// Generates an ordering of computation 151 | pub fn generate_ordering(&mut self, mut targets: Vec) -> Result,GraphError> { 152 | // The spanning tree of the targets, e.g. all nodes required to compute them 153 | let mut spanning_tree = vec![false; self.counter]; 154 | // Use the targets vector as a stack 155 | while targets.len() > 0 { 156 | let node = targets.pop().unwrap(); 157 | // If we see this node for the first time add its parents to the stack 158 | if !spanning_tree[node] { 159 | for p in try!(self.get_node(node)).op.get_ancestors() { 160 | targets.push(*p); 161 | } 162 | } 163 | // Add this node to the spanning tree 164 | spanning_tree[node] = true; 165 | } 166 | Ok(self.ordering.iter().cloned().filter(|&x| spanning_tree[x]).collect::>()) 167 | } 168 | 169 | /// Applies gradient operator with the first of the outputs 170 | pub fn direct_gradient(&mut self) -> Result<(),GraphError> { 171 | let target = self.outputs[0]; 172 | self.gradient(target) 173 | } 174 | 175 | /// Applies a gradient operator to the graph given the target 176 | pub fn gradient(&mut self, target: usize) -> Result<(),GraphError>{ 177 | // Some sensible checks 178 | match self.nodes[target]{ 179 | Some(ref node) => match node.node_type { 180 | Type::Parameter | Type::ParameterDerived => (), 181 | _ => return Ok(()) 182 | }, 183 | None => return Err(GraphError::AccessNoneNode(target)) 184 | } 185 | self.grad_level += 1; 186 | // Keeps all gradient messages 187 | let mut messages : HashMap> = HashMap::new(); 188 | let ordering = try!(self.generate_ordering(vec![target])); 189 | messages.insert(target, vec![self.add_int(1)]); 190 | for i in ordering.iter().rev(){ 191 | // Get all gradient messages and process them 192 | let gradient = match messages.remove(&i) { 193 | Some(vec) => match vec.len() { 194 | 0 => return Err(GraphError::NoGradientMessages(*i)), 195 | 1 => vec[0], 196 | _ => try!(self.add_operation(OPERATOR_ADD, vec)) 197 | }, 198 | None => continue//return Err(format!("No incoming messages found for node {}", i)) 199 | }; 200 | // Connect the gradient info and the parent 201 | try!(self.get_mut_node(gradient)).grad_parents.push(*i); 202 | try!(self.get_mut_node(*i)).grad_child = Some(gradient); 203 | let gradient = 0; 204 | // Generate gradient messages and send them to parents 205 | let grad_msgs = try!(self.op_gradient(*i, gradient)); 206 | for (parent, msg) in grad_msgs{ 207 | let mut mine = messages.entry(parent).or_insert(Vec::new()); 208 | mine.push(msg); 209 | } 210 | } 211 | // let mut grad_outputs: Vec = Vec::new(); 212 | // // Add gradients of the parameters to outptus 213 | // for i in (0..self.counter) { 214 | // //let node : Result<&mut ComputeNode, String> = ; 215 | // match self.get_mut_node(i) { 216 | // Ok(ref node) => match node.node_type { 217 | // Type::Parameter => {grad_outputs.push(node.grad_child.unwrap()); ()}, 218 | // _ => () 219 | // }, 220 | // Err(_) => () 221 | // } 222 | // } 223 | // for val in grad_outputs { 224 | // self.outputs.push(val); 225 | // } 226 | Ok(()) 227 | } 228 | 229 | /// Generates gradient messages from the operator to all of its non constant parents. 230 | /// Returns a HashMap 231 | fn op_gradient(&mut self, child: usize, grad: usize) -> Result, GraphError>{ 232 | let mut gradients : HashMap = HashMap::new(); 233 | let op = try!(self.get_node(child)).op.clone(); 234 | if op.op_type == OperatorType::Constant(ConstantOperatorType::None) { 235 | return Ok(gradients) 236 | } 237 | match op.op_type{ 238 | OperatorType::Constant(_) => return Err(GraphError::GradientOfConstant(child)), 239 | OPERATOR_NEG => { 240 | let msg = try!(self.add_operation(OPERATOR_NEG,vec![grad])); 241 | gradients.insert(op.parents[0], msg); 242 | }, 243 | OPERATOR_DIV => { 244 | let mut msg = try!(self.add_operation(OPERATOR_SQUARE,op.parents.clone())); 245 | msg = try!(self.add_operation(OPERATOR_DIV,vec![msg])); 246 | msg = try!(self.add_operation(OPERATOR_NEG,vec![msg])); 247 | msg = try!(self.add_operation(OPERATOR_MUL,vec![msg,grad])); 248 | gradients.insert(op.parents[0], msg); 249 | }, 250 | OPERATOR_MINV => { 251 | let mut msg = try!(self.add_operation(OPERATOR_TRANSPOSE,vec![child])); 252 | msg = try!(self.add_operation(OPERATOR_DOT,vec![msg,grad,msg])); 253 | msg = try!(self.add_operation(OPERATOR_NEG,vec![msg])); 254 | gradients.insert(op.parents[0], msg); 255 | }, 256 | OPERATOR_TRANSPOSE => { 257 | let msg = try!(self.add_operation(OPERATOR_TRANSPOSE,vec![grad])); 258 | gradients.insert(op.parents[0], msg); 259 | }, 260 | OPERATOR_MDIAG => { 261 | let msg = try!(self.add_operation(OPERATOR_VDIAG,vec![grad])); 262 | gradients.insert(op.parents[0], msg); 263 | }, 264 | OPERATOR_VDIAG => { 265 | let msg = try!(self.add_operation(OPERATOR_MDIAG,vec![grad])); 266 | gradients.insert(op.parents[0], msg); 267 | }, 268 | OPERATOR_COS => { 269 | let mut msg = try!(self.add_operation(OPERATOR_SIN,op.parents.clone())); 270 | msg = try!(self.add_operation(OPERATOR_NEG,vec![msg])); 271 | msg = try!(self.add_operation(OPERATOR_MUL,vec![msg,grad])); 272 | gradients.insert(op.parents[0], msg); 273 | }, 274 | OPERATOR_SIN => { 275 | let mut msg = try!(self.add_operation(OPERATOR_COS,op.parents.clone())); 276 | msg = try!(self.add_operation(OPERATOR_MUL,vec![msg,grad])); 277 | gradients.insert(op.parents[0], msg); 278 | }, 279 | OPERATOR_TAN => { 280 | let mut msg = try!(self.add_operation(OPERATOR_COS,op.parents.clone())); 281 | msg = try!(self.add_operation(OPERATOR_SQUARE,vec![msg])); 282 | msg = try!(self.add_operation(OPERATOR_DIV,vec![msg])); 283 | msg = try!(self.add_operation(OPERATOR_MUL,vec![msg,grad])); 284 | gradients.insert(op.parents[0], msg); 285 | }, 286 | OPERATOR_COSH => { 287 | let mut msg = try!(self.add_operation(OPERATOR_SINH,op.parents.clone())); 288 | msg = try!(self.add_operation(OPERATOR_MUL,vec![msg,grad])); 289 | gradients.insert(op.parents[0], msg); 290 | }, 291 | OPERATOR_SINH => { 292 | let mut msg = try!(self.add_operation(OPERATOR_COSH,op.parents.clone())); 293 | msg = try!(self.add_operation(OPERATOR_MUL,vec![msg,grad])); 294 | gradients.insert(op.parents[0], msg); 295 | }, 296 | OPERATOR_TANH => { 297 | let mut msg = try!(self.add_operation(OPERATOR_SQUARE,vec![child])); 298 | msg = try!(self.add_operation(OPERATOR_NEG,vec![msg])); 299 | let const_1 = self.add_int(1); 300 | msg = try!(self.add_operation(OPERATOR_ADD,vec![msg,const_1])); 301 | msg = try!(self.add_operation(OPERATOR_MUL,vec![msg,grad])); 302 | gradients.insert(op.parents[0], msg); 303 | }, 304 | OPERATOR_ABS => { 305 | let mut msg = try!(self.add_operation(OPERATOR_SIGN,op.parents.clone())); 306 | msg = try!(self.add_operation(OPERATOR_MUL,vec![msg,grad])); 307 | gradients.insert(op.parents[0], msg); 308 | }, 309 | OPERATOR_LOG => { 310 | let mut msg = try!(self.add_operation(OPERATOR_DIV,op.parents.clone())); 311 | msg = try!(self.add_operation(OPERATOR_MUL,vec![msg,grad])); 312 | gradients.insert(op.parents[0], msg); 313 | }, 314 | OPERATOR_EXP => { 315 | let msg = try!(self.add_operation(OPERATOR_MUL,vec![child,grad])); 316 | gradients.insert(op.parents[0], msg); 317 | }, 318 | OPERATOR_SQRT => { 319 | let const_half = self.add_float(0.5); 320 | let mut msg = try!(self.add_operation(OPERATOR_DIV,vec![child])); 321 | msg = try!(self.add_operation(OPERATOR_MUL,vec![const_half,msg,grad])); 322 | gradients.insert(op.parents[0], msg); 323 | }, 324 | OPERATOR_SQUARE => { 325 | let const_2 = self.add_int(2); 326 | let msg = try!(self.add_operation( 327 | OPERATOR_MUL,vec![const_2,op.parents[0],grad])); 328 | gradients.insert(op.parents[0], msg); 329 | }, 330 | OPERATOR_SIGM => { 331 | let const_1 = self.add_int(1); 332 | let mut msg = try!(self.add_operation(OPERATOR_NEG,vec![child])); 333 | msg = try!(self.add_operation(OPERATOR_ADD,vec![const_1,msg])); 334 | msg = try!(self.add_operation(OPERATOR_MUL,vec![msg,child,grad])); 335 | gradients.insert(op.parents[0], msg); 336 | }, 337 | OPERATOR_RECT => { 338 | let const_0 = self.add_int(0); 339 | let mut msg = try!(self.add_operation( 340 | OPERATOR_GT,vec![op.parents[0],const_0])); 341 | msg = try!(self.add_operation(OPERATOR_MUL,vec![msg,grad])); 342 | gradients.insert(op.parents[0], msg); 343 | }, 344 | OPERATOR_SUM_1 => { 345 | let rows = try!(self.add_operation(OPERATOR_SIZE_1, vec![op.parents[0]])); 346 | let msg = try!(self.add_operation( 347 | OPERATOR_REPLICATEV,vec![grad,rows])); 348 | gradients.insert(op.parents[0], msg); 349 | }, 350 | OPERATOR_SUM_2 => { 351 | let cols = try!(self.add_operation(OPERATOR_SIZE_2, vec![op.parents[0]])); 352 | let msg = try!(self.add_operation( 353 | OPERATOR_REPLICATEH,vec![grad,cols])); 354 | gradients.insert(op.parents[0], msg); 355 | }, 356 | OPERATOR_SUM_ALL => { 357 | let rows = try!(self.add_operation(OPERATOR_SIZE_1, vec![op.parents[0]])); 358 | let cols = try!(self.add_operation(OPERATOR_SIZE_2, vec![op.parents[0]])); 359 | let mut msg = try!(self.add_operation( 360 | OPERATOR_REPLICATEV,vec![grad,rows])); 361 | msg = try!(self.add_operation( 362 | OPERATOR_REPLICATEH,vec![msg,cols])); 363 | gradients.insert(op.parents[0], msg); 364 | }, 365 | OPERATOR_L2_1 => { 366 | let const_2 = self.add_int(2); 367 | let rows = try!(self.add_operation(OPERATOR_SIZE_1, vec![op.parents[0]])); 368 | let mut msg = try!(self.add_operation( 369 | OPERATOR_REPLICATEV,vec![grad,rows])); 370 | msg = try!(self.add_operation( 371 | OPERATOR_MUL,vec![const_2, op.parents[0], msg])); 372 | gradients.insert(op.parents[0], msg); 373 | }, 374 | OPERATOR_L2_2 => { 375 | let const_2 = self.add_int(2); 376 | let cols = try!(self.add_operation(OPERATOR_SIZE_2, vec![op.parents[0]])); 377 | let mut msg = try!(self.add_operation( 378 | OPERATOR_REPLICATEH,vec![grad,cols])); 379 | msg = try!(self.add_operation( 380 | OPERATOR_MUL,vec![const_2, op.parents[0], msg])); 381 | gradients.insert(op.parents[0], msg); 382 | }, 383 | OPERATOR_L2_ALL => { 384 | let const_2 = self.add_int(2); 385 | let msg = try!(self.add_operation( 386 | OPERATOR_MUL,vec![const_2, op.parents[0], grad])); 387 | gradients.insert(op.parents[0], msg); 388 | }, 389 | OPERATOR_L1_1 => { 390 | let rows = try!(self.add_operation(OPERATOR_SIZE_1, vec![op.parents[0]])); 391 | let mut msg = try!(self.add_operation( 392 | OPERATOR_REPLICATEV,vec![grad,rows])); 393 | let msg_sign = try!(self.add_operation(OPERATOR_SIGN, vec![op.parents[0]])); 394 | msg = try!(self.add_operation( 395 | OPERATOR_MUL,vec![msg_sign, msg])); 396 | gradients.insert(op.parents[0], msg); 397 | }, 398 | OPERATOR_L1_2 => { 399 | let cols = try!(self.add_operation(OPERATOR_SIZE_2, vec![op.parents[0]])); 400 | let mut msg = try!(self.add_operation( 401 | OPERATOR_REPLICATEH,vec![grad,cols])); 402 | let msg_sign = try!(self.add_operation(OPERATOR_SIGN, vec![op.parents[0]])); 403 | msg = try!(self.add_operation( 404 | OPERATOR_MUL,vec![msg_sign, msg])); 405 | gradients.insert(op.parents[0], msg); 406 | }, 407 | OPERATOR_L1_ALL => { 408 | let msg = try!(self.add_operation(OPERATOR_SIGN, vec![op.parents[0]])); 409 | let msg = try!(self.add_operation( 410 | OPERATOR_MUL,vec![msg, grad])); 411 | gradients.insert(op.parents[0], msg); 412 | }, 413 | OPERATOR_MAX => { 414 | if try!(self.is_dependable(op.parents[0])){ 415 | let mut msg = try!(self.add_operation( 416 | OPERATOR_NEG,vec![op.parents[1]])); 417 | msg = try!(self.add_operation(OPERATOR_ADD,vec![op.parents[0],msg])); 418 | msg = try!(self.add_operation(OPERATOR_SIGN, vec![msg])); 419 | msg = try!(self.add_operation(OPERATOR_MUL,vec![msg, grad])); 420 | gradients.insert(op.parents[0], msg); 421 | } 422 | if try!(self.is_dependable(op.parents[1])){ 423 | let mut msg = try!(self.add_operation( 424 | OPERATOR_NEG,vec![op.parents[0]])); 425 | msg = try!(self.add_operation(OPERATOR_ADD,vec![op.parents[1],msg])); 426 | msg = try!(self.add_operation(OPERATOR_SIGN, vec![msg])); 427 | msg = try!(self.add_operation(OPERATOR_MUL,vec![msg, grad])); 428 | gradients.insert(op.parents[1], msg); 429 | } 430 | }, 431 | OPERATOR_MIN => { 432 | if try!(self.is_dependable(op.parents[0])){ 433 | let mut msg = try!(self.add_operation( 434 | OPERATOR_NEG,vec![op.parents[0]])); 435 | msg = try!(self.add_operation(OPERATOR_ADD,vec![op.parents[1],msg])); 436 | msg = try!(self.add_operation(OPERATOR_SIGN, vec![msg])); 437 | msg = try!(self.add_operation(OPERATOR_MUL,vec![msg, grad])); 438 | gradients.insert(op.parents[0], msg); 439 | } 440 | if try!(self.is_dependable(op.parents[1])){ 441 | let mut msg = try!(self.add_operation( 442 | OPERATOR_NEG,vec![op.parents[1]])); 443 | msg = try!(self.add_operation(OPERATOR_ADD,vec![op.parents[0],msg])); 444 | msg = try!(self.add_operation(OPERATOR_SIGN, vec![msg])); 445 | msg = try!(self.add_operation(OPERATOR_MUL,vec![msg, grad])); 446 | gradients.insert(op.parents[1], msg); 447 | } 448 | }, 449 | OPERATOR_POW => { 450 | if try!(self.is_dependable(op.parents[0])){ 451 | let mut msg = try!(self.add_operation( 452 | OPERATOR_DIV,vec![op.parents[0]])); 453 | msg = try!(self.add_operation( 454 | OPERATOR_MUL,vec![op.parents[1], child, msg, grad])); 455 | gradients.insert(op.parents[0], msg); 456 | } 457 | if try!(self.is_dependable(op.parents[1])){ 458 | let mut msg = try!(self.add_operation( 459 | OPERATOR_LOG,vec![op.parents[0]])); 460 | msg = try!(self.add_operation(OPERATOR_MUL,vec![child, msg, grad])); 461 | gradients.insert(op.parents[1], msg); 462 | } 463 | }, 464 | OPERATOR_QUAD => { 465 | if try!(self.is_dependable(op.parents[0])){ 466 | let ptr = try!(self.add_operation( 467 | OPERATOR_TRANSPOSE,vec![op.parents[1]])); 468 | let msg_1 = try!(self.add_operation( 469 | OPERATOR_DOT,vec![ptr, op.parents[0], grad])); 470 | let gradtr = try!(self.add_operation( 471 | OPERATOR_TRANSPOSE,vec![grad])); 472 | let msg_2 = try!(self.add_operation( 473 | OPERATOR_DOT,vec![op.parents[1], op.parents[0], gradtr])); 474 | let msg = try!(self.add_operation( 475 | OPERATOR_ADD,vec![msg_1, msg_2])); 476 | gradients.insert(op.parents[0], msg); 477 | } 478 | if try!(self.is_dependable(op.parents[1])){ 479 | let ptr = try!(self.add_operation( 480 | OPERATOR_TRANSPOSE,vec![op.parents[0]])); 481 | let msg = try!(self.add_operation( 482 | OPERATOR_DOT,vec![op.parents[0], grad, ptr])); 483 | gradients.insert(op.parents[1], msg); 484 | } 485 | }, 486 | OPERATOR_ADD => { 487 | for i in op.parents.iter(){ 488 | if try!(self.is_dependable(*i)){ 489 | gradients.insert(*i, grad); 490 | } 491 | } 492 | }, 493 | OPERATOR_MUL => { 494 | match op.parents.len(){ 495 | 0...1 => return Err(GraphError::Operator(OperatorError::InvalidNumberOfParents(OPERATOR_MUL, 2, op.parents.len()))), 496 | 2 => { 497 | let p1 = op.parents[0]; 498 | let p2 = op.parents[1]; 499 | if try!(self.is_dependable(p1)){ 500 | let msg = try!(self.add_operation(OPERATOR_MUL,vec![p2, grad])); 501 | gradients.insert(p1, msg); 502 | } 503 | if try!(self.is_dependable(p2)){ 504 | let msg = try!(self.add_operation(OPERATOR_MUL,vec![p1, grad])); 505 | gradients.insert(p2, msg); 506 | } 507 | }, 508 | _ => { 509 | for i in op.parents.iter(){ 510 | if try!(self.is_dependable(*i)){ 511 | let mut msg = try!(self.add_operation( 512 | OPERATOR_DIV,vec![*i])); 513 | msg = try!(self.add_operation( 514 | OPERATOR_MUL,vec![msg, child, grad])); 515 | gradients.insert(*i, msg); 516 | } 517 | } 518 | } 519 | } 520 | }, 521 | OPERATOR_DOT => { 522 | let n = op.parents.len(); 523 | match n { 524 | 0...1 => return Err(GraphError::Operator( 525 | OperatorError::InvalidNumberOfParents(op.op_type,op.parents.len(),2))), 526 | _ => { 527 | // Left most parent 528 | let p1 = op.parents[0]; 529 | if try!(self.is_dependable(p1)) { 530 | let right_msg = if n == 2 { 531 | try!(self.add_operation(OPERATOR_TRANSPOSE, vec![op.parents[1]])) 532 | } else { 533 | let right_parents = op.parents[1..].to_owned(); 534 | let msg = try!(self.add_operation(OPERATOR_DOT, right_parents)); 535 | try!(self.add_operation(OPERATOR_TRANSPOSE, vec![msg])) 536 | }; 537 | let msg = try!(self.add_operation(OPERATOR_DOT,vec![grad, right_msg])); 538 | gradients.insert(p1, msg); 539 | } 540 | // Right most parent 541 | let pend = op.parents[n-1]; 542 | if try!(self.is_dependable(pend)) { 543 | let left_msg = if n == 2 { 544 | try!(self.add_operation(OPERATOR_TRANSPOSE, vec![op.parents[0]])) 545 | } else { 546 | let left_parents = op.parents[..n-1].to_owned(); 547 | let msg = try!(self.add_operation(OPERATOR_DOT, left_parents)); 548 | try!(self.add_operation(OPERATOR_TRANSPOSE, vec![msg])) 549 | }; 550 | let msg = try!(self.add_operation(OPERATOR_DOT, vec![left_msg, grad])); 551 | gradients.insert(pend, msg); 552 | } 553 | if n > 2 { 554 | // Second from left to right 555 | let p = op.parents[1]; 556 | if try!(self.is_dependable(p)) { 557 | let left_msg = try!(self.add_operation(OPERATOR_TRANSPOSE, vec![op.parents[0]])); 558 | let right_msg = if n == 3 { 559 | try!(self.add_operation(OPERATOR_TRANSPOSE, vec![op.parents[2]])) 560 | } else { 561 | let right_parents = op.parents[2..].to_owned(); 562 | let msg = try!(self.add_operation(OPERATOR_DOT, right_parents)); 563 | try!(self.add_operation(OPERATOR_TRANSPOSE, vec![msg])) 564 | }; 565 | let msg = try!(self.add_operation(OPERATOR_DOT, vec![left_msg, grad, right_msg])); 566 | gradients.insert(p, msg); 567 | } 568 | } 569 | if n > 3 { 570 | // Second from right to left 571 | let p = op.parents[n-2]; 572 | if try!(self.is_dependable(p)) { 573 | let right_msg = try!(self.add_operation(OPERATOR_TRANSPOSE, vec![op.parents[n-1]])); 574 | let left_parents = op.parents[..n-3].to_owned(); 575 | let mut left_msg = try!(self.add_operation(OPERATOR_DOT, left_parents)); 576 | left_msg = try!(self.add_operation(OPERATOR_TRANSPOSE, vec![left_msg])); 577 | let msg = try!(self.add_operation(OPERATOR_DOT,vec![left_msg, grad, right_msg])); 578 | gradients.insert(p, msg); 579 | } 580 | } 581 | if n > 4 { 582 | // Rest 583 | for i in 2..n-3{ 584 | let p = op.parents[i]; 585 | if try!(self.is_dependable(p)) { 586 | let left_parents = op.parents[..i-1].to_owned(); 587 | let mut left_msg = try!(self.add_operation(OPERATOR_DOT, left_parents)); 588 | left_msg = try!(self.add_operation(OPERATOR_TRANSPOSE, vec![left_msg])); 589 | let right_parents = op.parents[i+1..].to_owned(); 590 | let mut right_msg = try!(self.add_operation(OPERATOR_DOT, right_parents)); 591 | right_msg = try!(self.add_operation(OPERATOR_TRANSPOSE, vec![right_msg])); 592 | let msg = try!(self.add_operation(OPERATOR_DOT, vec![left_msg, grad, right_msg])); 593 | gradients.insert(p, msg); 594 | } 595 | } 596 | } 597 | } 598 | } 599 | }, 600 | OPERATOR_HORZCAT => { 601 | let n = op.parents.len(); 602 | match n { 603 | 0...1 => return Err(GraphError::Operator( 604 | OperatorError::InvalidNumberOfParents(op.op_type,op.parents.len(),2))), 605 | _ => { 606 | let mut last : usize = n; 607 | for (i,p) in op.parents.iter().enumerate().rev(){ 608 | if try!(self.is_dependable(*p)) { 609 | last = i; 610 | break; 611 | } 612 | } 613 | if last < n { 614 | let const_0 = self.add_int(0); 615 | let rows = try!(self.add_operation(OPERATOR_SIZE_1, vec![child])); 616 | let mut accum = self.add_int(0); 617 | for p in op.parents.iter().take(last+1) { 618 | let cols = try!(self.add_operation(OPERATOR_SIZE_2, vec![*p])); 619 | if try!(self.is_dependable(*p)) { 620 | let msg = try!(self.add_operation(OPERATOR_SUBINDEX, vec![grad,const_0,rows, accum, cols])); 621 | gradients.insert(*p, msg); 622 | } 623 | accum = try!(self.add_operation(OPERATOR_ADD, vec![accum, cols])); 624 | } 625 | } 626 | } 627 | } 628 | }, 629 | OPERATOR_VERTCAT => { 630 | let n = op.parents.len(); 631 | match n{ 632 | 0...1 => return Err(GraphError::Operator( 633 | OperatorError::InvalidNumberOfParents(op.op_type,op.parents.len(),2))), 634 | _ => { 635 | let mut last : usize = n; 636 | for (i,p) in op.parents.iter().enumerate().rev(){ 637 | if try!(self.is_dependable(*p)) { 638 | last = i; 639 | break; 640 | } 641 | } 642 | if last < n { 643 | let const_0 = self.add_int(0); 644 | let cols = try!(self.add_operation(OPERATOR_SIZE_2, vec![child])); 645 | let mut accum = self.add_int(0); 646 | for p in op.parents.iter().take(last+1) { 647 | let rows = try!(self.add_operation(OPERATOR_SIZE_1, vec![*p])); 648 | if try!(self.is_dependable(*p)) { 649 | let msg = try!(self.add_operation(OPERATOR_SUBINDEX, vec![grad,accum,rows, const_0, cols])); 650 | gradients.insert(*p, msg); 651 | } 652 | accum = try!(self.add_operation(OPERATOR_ADD, vec![accum, rows])); 653 | } 654 | } 655 | } 656 | } 657 | }, 658 | OPERATOR_SUBINDEX => { 659 | let mut new_parents = vec![grad]; 660 | new_parents.extend(op.parents.iter().skip(1).cloned()); 661 | let msg = try!(self.add_operation( 662 | OPERATOR_SUBASSIGN,new_parents)); 663 | gradients.insert(op.parents[0], msg); 664 | }, 665 | OPERATOR_SUBASSIGN => { 666 | let mut new_parents = vec![grad]; 667 | new_parents.extend(op.parents.iter().skip(1).cloned()); 668 | let msg = try!(self.add_operation( 669 | OPERATOR_SUBINDEX,new_parents)); 670 | gradients.insert(op.parents[0], msg); 671 | }, 672 | OPERATOR_RESHAPE => { 673 | let rows = try!(self.add_operation( 674 | OPERATOR_SIZE_1, vec![op.parents[0]])); 675 | let cols = try!(self.add_operation( 676 | OPERATOR_SIZE_2, vec![op.parents[0]])); 677 | let msg = try!(self.add_operation( 678 | OPERATOR_RESHAPE,vec![grad, rows, cols])); 679 | gradients.insert(op.parents[0], msg); 680 | }, 681 | OPERATOR_REPLICATEH => { 682 | let msg = try!(self.add_operation( 683 | OPERATOR_SUM_2,vec![grad])); 684 | gradients.insert(op.parents[0], msg); 685 | }, 686 | OPERATOR_REPLICATEV => { 687 | let msg = try!(self.add_operation( 688 | OPERATOR_SUM_1,vec![grad])); 689 | gradients.insert(op.parents[0], msg); 690 | } 691 | } 692 | Ok(gradients) 693 | } 694 | 695 | // #[inline(always)] 696 | pub fn get_mut_node(&mut self, index: usize) -> Result<&mut ComputeNode, GraphError>{ 697 | let l = self.nodes.len(); 698 | try!(self.nodes.get_mut(index).ok_or_else( 699 | || GraphError::IndexOutOfBounds(index,l))) 700 | .as_mut().ok_or_else( 701 | || GraphError::AccessNoneNode(index)) 702 | } 703 | 704 | // #[inline(always)] 705 | pub fn get_node(&mut self, index: usize) -> Result<& ComputeNode, GraphError>{ 706 | try!(self.nodes.get(index).ok_or_else( 707 | || GraphError::IndexOutOfBounds(index,self.nodes.len()))) 708 | .as_ref().ok_or_else( 709 | || GraphError::AccessNoneNode(index)) 710 | } 711 | 712 | // #[inline(always)] 713 | pub fn pop_node(&mut self, index: usize) -> Result { 714 | self.nodes.push(None); 715 | self.nodes.swap_remove(index).ok_or_else(|| GraphError::AccessNoneNode(index)) 716 | } 717 | 718 | // #[inline(always)] 719 | pub fn insert_node(&mut self, index: usize, node: Option) -> Option { 720 | self.nodes.push(node); 721 | self.nodes.swap_remove(index) 722 | } 723 | 724 | // #[inline(always)] 725 | pub fn is_dependable(&mut self, index: usize) -> Result { 726 | match try!(self.get_node(index)).node_type.clone(){ 727 | Type::Parameter | Type::ParameterDerived => Ok(true), 728 | _ => Ok(false) 729 | } 730 | } 731 | 732 | pub fn swap_child_connections(&mut self, old_parent: usize, new_parent: usize) -> Result<(), GraphError> { 733 | if old_parent == new_parent { 734 | return Ok(()) 735 | } 736 | // Extract children 737 | let children = try!(self.get_node(old_parent)).children.clone(); 738 | for child in children.iter(){ 739 | try!(try!(self.get_mut_node(*child)).op.swap_parent_in_place(old_parent, new_parent)); 740 | } 741 | // Add all children to the new parent 742 | try!(self.get_mut_node(new_parent)).children.extend(children.iter().cloned()); 743 | Ok(()) 744 | } 745 | 746 | pub fn string_to_operator(&mut self , name: String, args: Vec) -> Result{ 747 | match &name[..]{ 748 | "const" => Ok(try!(self.add_operation(OPERATOR_CONST, args))), 749 | "eye" => Ok(try!(self.add_operation(OPERATOR_EYE, args))), 750 | "sign" => Ok(try!(self.add_operation(OPERATOR_SIGN, args))), 751 | "rows" => Ok(try!(self.add_operation(OPERATOR_SIZE_1, args))), 752 | "cols" => Ok(try!(self.add_operation(OPERATOR_SIZE_2, args))), 753 | "ones" => Ok(try!(self.add_operation(OPERATOR_ONES, args))), 754 | "zeros" => Ok(try!(self.add_operation(OPERATOR_ZEROS, args))), 755 | "lt" => Ok(try!(self.add_operation(OPERATOR_LT, args))), 756 | "lte" => Ok(try!(self.add_operation(OPERATOR_LTE, args))), 757 | "gt" => Ok(try!(self.add_operation(OPERATOR_GT, args))), 758 | "gte" => Ok(try!(self.add_operation(OPERATOR_GTE, args))), 759 | "eq" => Ok(try!(self.add_operation(OPERATOR_EQ, args))), 760 | "neq" => Ok(try!(self.add_operation(OPERATOR_NEQ, args))), 761 | "neg" => Ok(try!(self.add_operation(OPERATOR_NEG, args))), 762 | "div" => Ok(try!(self.add_operation(OPERATOR_DIV, args))), 763 | "minv" => Ok(try!(self.add_operation(OPERATOR_MINV, args))), 764 | "tr" => Ok(try!(self.add_operation(OPERATOR_TRANSPOSE, args))), 765 | "mdiag" => Ok(try!(self.add_operation(OPERATOR_MDIAG, args))), 766 | "vdiag" => Ok(try!(self.add_operation(OPERATOR_VDIAG, args))), 767 | "cos" => Ok(try!(self.add_operation(OPERATOR_COS, args))), 768 | "sin" => Ok(try!(self.add_operation(OPERATOR_SIN, args))), 769 | "tan" => Ok(try!(self.add_operation(OPERATOR_TAN, args))), 770 | "cosh" => Ok(try!(self.add_operation(OPERATOR_COSH, args))), 771 | "sinh" => Ok(try!(self.add_operation(OPERATOR_SINH, args))), 772 | "tanh" => Ok(try!(self.add_operation(OPERATOR_TANH, args))), 773 | "abs" => Ok(try!(self.add_operation(OPERATOR_ABS, args))), 774 | "log" => Ok(try!(self.add_operation(OPERATOR_LOG, args))), 775 | "exp" => Ok(try!(self.add_operation(OPERATOR_EXP, args))), 776 | "sqrt" => Ok(try!(self.add_operation(OPERATOR_SQRT, args))), 777 | "square" => Ok(try!(self.add_operation(OPERATOR_SQUARE, args))), 778 | "sigm" => Ok(try!(self.add_operation(OPERATOR_SIGM, args))), 779 | "rect" => Ok(try!(self.add_operation(OPERATOR_RECT, args))), 780 | "sum" => match args.len(){ 781 | 2 => match try!(self.get_node(args[1])).node_type { 782 | Type::Integer(x) => { 783 | match x { 784 | 0 => { 785 | try!(self.remove_last()); 786 | let result = try!(self.add_operation(OPERATOR_SUM_ALL, vec![args[0]])); 787 | Ok(result) 788 | }, 789 | 1 => { 790 | try!(self.remove_last()); 791 | let result = try!(self.add_operation( 792 | OPERATOR_SUM_1, vec![args[0]])); 793 | Ok(result) 794 | }, 795 | 2 => { 796 | try!(self.remove_last()); 797 | let result = try!(self.add_operation( 798 | OPERATOR_SUM_2, vec![args[0]])); 799 | Ok(result) 800 | }, 801 | _ => return Err(GraphError::Operator( 802 | OperatorError::InvalidDimensionArgument("SUM".to_string(),x as usize, vec![0,1,2]))) 803 | } 804 | }, 805 | _ => return Err(GraphError::Operator( 806 | OperatorError::InvalidDimensionArgument("SUM".to_string(),999, vec![0,1,2]))) 807 | }, 808 | _ => return Err(GraphError::Operator( 809 | OperatorError::InvalidNumberOfParents(OPERATOR_SUM_ALL, args.len()-1, 1))) 810 | }, 811 | "l2" => match args.len(){ 812 | 2 => match try!(self.get_node(args[1])).node_type { 813 | Type::Integer(x) => { 814 | match x { 815 | 0 => { 816 | try!(self.remove_last()); 817 | let result = try!(self.add_operation( 818 | OPERATOR_L2_ALL, vec![args[0]])); 819 | Ok(result) 820 | }, 821 | 1 => { 822 | try!(self.remove_last()); 823 | let result = try!(self.add_operation( 824 | OPERATOR_L2_1, vec![args[0]])); 825 | Ok(result) 826 | }, 827 | 2 => { 828 | try!(self.remove_last()); 829 | let result = try!(self.add_operation( 830 | OPERATOR_L2_2, vec![args[0]])); 831 | Ok(result) 832 | }, 833 | x => return Err(GraphError::Operator( 834 | OperatorError::InvalidDimensionArgument("L2".to_string(),x as usize, vec![0,1,2]))) 835 | } 836 | }, 837 | _ => return Err(GraphError::Operator( 838 | OperatorError::InvalidDimensionArgument("L2".to_string(), 999, vec![0,1,2]))) 839 | }, 840 | _ => return Err(GraphError::Operator( 841 | OperatorError::InvalidNumberOfParents(OPERATOR_L2_ALL, args.len()-1, 1))) 842 | }, 843 | "l1" => match args.len(){ 844 | 2 => match try!(self.get_node(args[1])).node_type { 845 | Type::Integer(x) => { 846 | match x { 847 | 0 => { 848 | try!(self.remove_last()); 849 | let result = try!(self.add_operation( 850 | OPERATOR_L1_ALL, vec![args[0]])); 851 | Ok(result) 852 | }, 853 | 1 => { 854 | try!(self.remove_last()); 855 | let result = try!(self.add_operation( 856 | OPERATOR_L1_1, vec![args[0]])); 857 | Ok(result) 858 | }, 859 | 2 => { 860 | try!(self.remove_last()); 861 | let result = try!(self.add_operation( 862 | OPERATOR_L1_2, vec![args[0]])); 863 | Ok(result) 864 | }, 865 | x => return Err(GraphError::Operator(OperatorError::InvalidDimensionArgument("L1".to_string(),x as usize, vec![0,1,2]))) 866 | } 867 | }, 868 | _ => return Err(GraphError::Operator( 869 | OperatorError::InvalidDimensionArgument("L1".to_string(),999 , vec![0,1,2]))) 870 | }, 871 | _ => return Err(GraphError::Operator( 872 | OperatorError::InvalidNumberOfParents(OPERATOR_L1_ALL, args.len()-1, 1))) 873 | }, 874 | "max" => Ok(try!(self.add_operation(OPERATOR_MAX, args))), 875 | "min" => Ok(try!(self.add_operation(OPERATOR_MIN, args))), 876 | "pow" => Ok(try!(self.add_operation(OPERATOR_POW, args))), 877 | "quad" => Ok(try!(self.add_operation(OPERATOR_QUAD, args))), 878 | "subind" => Ok(try!(self.add_operation(OPERATOR_SUBINDEX, args))), 879 | "subasign" => Ok(try!(self.add_operation(OPERATOR_SUBASSIGN, args))), 880 | "reshape" => Ok(try!(self.add_operation(OPERATOR_RESHAPE, args))), 881 | "replicateH" => Ok(try!(self.add_operation(OPERATOR_REPLICATEH, args))), 882 | "replicateV" => Ok(try!(self.add_operation(OPERATOR_REPLICATEV, args))), 883 | "add" => Ok(try!(self.add_operation(OPERATOR_ADD, args))), 884 | "mul" => Ok(try!(self.add_operation(OPERATOR_MUL, args))), 885 | "dot" => Ok(try!(self.add_operation(OPERATOR_DOT, args))), 886 | "horzcat" => Ok(try!(self.add_operation(OPERATOR_HORZCAT, args))), 887 | "vertcat" => Ok(try!(self.add_operation(OPERATOR_VERTCAT, args))), 888 | _ => Err(GraphError::UnknownFunction(name.clone())) 889 | } 890 | } 891 | pub fn is_function_name(name: &str) -> bool{ 892 | match name{ 893 | "const" | "eye" | "sign" | "rows" | "cols" | "ones" | "zeros" 894 | | "minv" | "mdiag" | "vdiag" | "cos" | "sin" | "tan" | "cosh" | "sinh" | "tanh" 895 | | "abs"| "log" | "exp" | "sqrt" | "square" | "sigm" | "rect" | "sum" | "l2" | "l1" 896 | | "max" | "min" | "pow" | "quad" | "reshape" | "replicateH"| "replicateV" 897 | | "horzcat" | "vertcat" | "dot" => true, 898 | _ => false 899 | } 900 | } 901 | 902 | pub fn get_params(&self) -> (Vec, Vec) { 903 | let mut names : Vec = Vec::new(); 904 | let mut grads : Vec = Vec::new(); 905 | for option in self.nodes.iter(){ 906 | match *option { 907 | Some(ref node) => { 908 | match node.node_type { 909 | Type::Parameter => { 910 | names.push(node.name.clone()); 911 | grads.push(node.grad_child.unwrap()); 912 | } 913 | _ => () 914 | } 915 | }, 916 | None => () 917 | } 918 | } 919 | (grads, names) 920 | } 921 | 922 | } 923 | 924 | #[derive(Clone, Debug)] 925 | pub enum GraphError { 926 | AccessNoneNode(usize), 927 | IndexOutOfBounds(usize,usize), 928 | UnknownFunction(String), 929 | LastHasChildren, 930 | GradientOfConstant(usize), 931 | NoGradientMessages(usize), 932 | Operator(OperatorError) 933 | } 934 | 935 | impl ::std::fmt::Display for GraphError { 936 | fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { 937 | match *self { 938 | GraphError::AccessNoneNode(x) => write!(f, "AccessNoneNode: Trying to access node {}, but its none", x), 939 | GraphError::IndexOutOfBounds(n,l) => write!(f, "IndexOutOfBounds: Trying to access node {}, but currently the counter is {}", n,l), 940 | GraphError::UnknownFunction(ref name) => write!(f, "UnknownFunction: {}", name), 941 | GraphError::LastHasChildren => write!(f, "Last node already has children"), 942 | GraphError::GradientOfConstant(n) => write!(f, "Can not take a gradient with respect to a cosntant node - {}", n), 943 | GraphError::NoGradientMessages(n) => write!(f, "No gradient messages found for node {}", n), 944 | GraphError::Operator(ref err) => write!(f, "OperatorError: {}", err), 945 | } 946 | } 947 | } 948 | 949 | impl ::std::error::Error for GraphError { 950 | fn description(&self) -> &str { 951 | match *self { 952 | GraphError::AccessNoneNode(_) => "Trying to access a None node", 953 | GraphError::IndexOutOfBounds(_,_) => "Accessing node index out of bounds", 954 | GraphError::UnknownFunction(_) => "Trying to use an unkown function", 955 | GraphError::LastHasChildren => "Last node already has children", 956 | GraphError::GradientOfConstant(_) => "Taking gradient with respect to a constant", 957 | GraphError::NoGradientMessages(_) => "No gradient messages were send for a required node", 958 | GraphError::Operator(ref err) => err.description(), 959 | } 960 | } 961 | 962 | fn cause(&self) -> Option<&::std::error::Error> { 963 | match *self { 964 | GraphError::Operator(ref err) => Some(err), 965 | _ => None 966 | } 967 | } 968 | } 969 | 970 | impl ::std::convert::From for GraphError { 971 | fn from(err: OperatorError) -> GraphError { 972 | GraphError::Operator(err) 973 | } 974 | } 975 | -------------------------------------------------------------------------------- /src/core/mod.rs: -------------------------------------------------------------------------------- 1 | mod operator; 2 | mod node; 3 | mod graph; 4 | mod parser; 5 | 6 | pub use self::parser::metaFile as parseMetaFile; 7 | pub use self::parser::ParseError; 8 | 9 | pub use self::operator::*; 10 | pub use self::node::*; 11 | pub use self::graph::*; 12 | -------------------------------------------------------------------------------- /src/core/node.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::{Display, Formatter, Error}; 2 | use super::operator::*; 3 | 4 | /// Represents the five types any `ComputeNode` 5 | #[derive(Clone, Copy, Debug, PartialEq)] 6 | pub enum Type{ 7 | /// Represents a single floating variable 8 | Float(f64), 9 | /// Represents a single integer variable 10 | Integer(i64), 11 | /// Represents a constant input, no gradients will be taken with respect to such node 12 | ConstInput, 13 | /// Represents a pramater, gradients will be taken with respect to such node 14 | Parameter, 15 | /// Represent a variable which depends only on `ConstInput`s, `Float`s or `Integer`s 16 | ConstDerived, 17 | /// Represent a variable which has some dependency on a `Parameter` 18 | ParameterDerived 19 | } 20 | 21 | 22 | 23 | /// The main data structure of the `ComputeGraph` 24 | #[derive(Clone, Debug, PartialEq)] 25 | pub struct ComputeNode{ 26 | /// The id is equivalent to the index in the nodes list of the `ComputeGraph` 27 | pub id: usize, 28 | /// The type of the node 29 | pub node_type: Type, 30 | /// A user given or automatically generated name 31 | pub name: String, 32 | /// All nodes dependable on this one 33 | pub children: Vec, 34 | /// Defines to what gradient level computation this node belongs 35 | pub grad_level: u8, 36 | /// Whether the node should be inlined by any of the source code generators 37 | pub inline: bool, 38 | // dims: Pair, 39 | /// Defines the node which represents `dL/dx` 40 | pub grad_child: Option, 41 | /// If this node has `grad_level` more than 0, it means it could represent for some node `dL/dx`, thus this contains a list of all such nodes 42 | pub grad_parents: Vec, 43 | /// What is the operator this node represents 44 | pub op: Operator 45 | } 46 | 47 | impl Display for ComputeNode{ 48 | fn fmt(&self, f : &mut Formatter) -> Result<(), Error> { 49 | match self.op.op_type { 50 | OperatorType::Constant(ConstantOperatorType::None) => 51 | write!(f, concat!("********{}[{}]********\n", 52 | "Type:{:?}\n", 53 | "Children:{:?}"), 54 | self.name, self.id, self.node_type, self.children), 55 | operator => write!(f, concat!("********{}[{}]********\n", 56 | "Type:{:?}\n", 57 | "Operator: {:?}\n", 58 | "Children:{:?}"), 59 | self.name, self.id, self.node_type, operator, self.children), 60 | } 61 | } 62 | } 63 | 64 | impl ComputeNode{ 65 | /// Creates a new empty `ComputeNode`, its name depends on the input type and gradient level 66 | pub fn new(id: usize, node_type: Type, grad_level: u8, op: Operator) -> Self{ 67 | let name = if grad_level > 0{ 68 | "AutoGrad".to_string() 69 | } 70 | else { 71 | format!("{:?}", node_type) 72 | }; 73 | ComputeNode{id: id, node_type: node_type, name: name, children: Vec::new(), 74 | grad_level: grad_level, inline: false, grad_child: None, grad_parents: Vec::new(), op:op} 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/core/operator.rs: -------------------------------------------------------------------------------- 1 | /// Represents all possible dimensionality arguments, used in the operators 2 | #[derive(Clone, Copy, Debug, PartialEq)] 3 | pub enum Dimension{ 4 | First, 5 | Second, 6 | All 7 | } 8 | 9 | impl ::std::convert::From for Dimension { 10 | fn from(err: usize) -> Dimension { 11 | match err { 12 | 1 => Dimension::First, 13 | 2 => Dimension::Second, 14 | _ => Dimension::All 15 | } 16 | } 17 | } 18 | 19 | /// An enum for operators which take a single parent node and produce a constant 20 | /// 21 | /// The operator should have a single parent and no argumetns 22 | #[derive(Clone, Copy, Debug, PartialEq)] 23 | pub enum ConstantUnaryOperatorType{ 24 | /// Transforms the parent node to a constant one, regardless if whether it is dependable on any parameters or not 25 | Const, 26 | /// Creates a new identity matrix with dimensions given by the parent node 27 | Eye, 28 | /// Represents elementwise sign(x) 29 | Sign, 30 | /// Returns the size of the node along the selected dimension. Should never be used with `Dimension::All`! 31 | Size(Dimension) 32 | } 33 | 34 | /// An enum for operators which take two parent nodes and produce a constant 35 | /// 36 | /// The operator should have two parents and no arguments 37 | #[derive(Clone, Copy, Debug, PartialEq)] 38 | pub enum ConstantBinaryOperatorType { 39 | /// Creates a new matrix of zeros with dimensions given by its parents 40 | Zeros, 41 | /// Creates a new matrix of ones with dimensions given by its parents 42 | Ones, 43 | /// Represents elemtwise x < y 44 | LessThan, 45 | /// Represents elemtwise x <= y 46 | LessThanOrEqual, 47 | /// Represents elemtwise x > y 48 | GreaterThan, 49 | /// Represents elemtwise x >= y 50 | GreaterThanOrEqual, 51 | /// Represents elementwise x == y 52 | Equals, 53 | /// Represents elementiwse x != y 54 | NotEquals 55 | } 56 | 57 | /// An enum for all operators which produce a constant 58 | /// 59 | /// The operator should have either one or two parents and no arguments 60 | #[derive(Clone, Copy, Debug, PartialEq)] 61 | pub enum ConstantOperatorType { 62 | /// A `ConstantUnaryOperatorType` 63 | Unary(ConstantUnaryOperatorType), 64 | /// A `ConstantBinaryOperatorType` 65 | Binary(ConstantBinaryOperatorType), 66 | /// An empty operator, used for inputs or parameters 67 | None 68 | } 69 | 70 | impl ::std::convert::From for ConstantOperatorType { 71 | fn from(err: ConstantUnaryOperatorType) -> ConstantOperatorType { 72 | ConstantOperatorType::Unary(err) 73 | } 74 | } 75 | 76 | impl ::std::convert::From for ConstantOperatorType { 77 | fn from(err: ConstantBinaryOperatorType) -> ConstantOperatorType { 78 | ConstantOperatorType::Binary(err) 79 | } 80 | } 81 | 82 | /// An enum for operators which take a single parent node. 83 | /// 84 | /// The operator should have one parent and no arguments 85 | #[derive(Clone, Copy, Debug, PartialEq)] 86 | pub enum UnaryOperatorType { 87 | /// Represents elemtwise -x 88 | Neg, 89 | /// Represents elemntwise x^-1 90 | Div, 91 | /// Represents matrix inversion M^-1 92 | MatrixInverse, 93 | /// Represents matrix transpose M^T 94 | Transpose, 95 | /// Takes the diagonal of a matrix as a column vector 96 | MatrixDiag, 97 | /// Takes a vector to a matrix, whose diagonal is equal to that vector 98 | VectorDiag, 99 | /// Represents elementwise cos(x) 100 | Cos, 101 | /// Represents elementwise sin(x) 102 | Sin, 103 | /// Represents elementwise tan(x) 104 | Tan, 105 | /// Represents elementwise cosh(x) 106 | CosH, 107 | /// Represents elementwise sinh(x) 108 | SinH, 109 | /// Represents elementwise tanh(x) 110 | TanH, 111 | /// Represents elementwise abs(x) 112 | Abs, 113 | /// Represents elementwise ln(x) 114 | Log, 115 | /// Represents elementwise e^x 116 | Exp, 117 | /// Represents elementwise sqrt(x) 118 | Sqrt, 119 | /// Represents elementwise x^2 120 | Square, 121 | /// Represents elementwise 1 / (1 + exp(-x)) 122 | Sigmoid, 123 | /// Repersents elementwise max(x,0) 124 | Rectifier, 125 | /// Takes the sum of the elements along the given dimension. 126 | Sum(Dimension), 127 | /// Takes the L2 squared norm along the given dimension. This is defuned as sum(x_i^2) 128 | L2(Dimension), 129 | /// Takes the L1 norm along the given dimension. This is defined as sum(abs(x_i)) 130 | L1(Dimension) 131 | } 132 | 133 | /// An enum for operators which take a two parent nodes 134 | /// 135 | /// The operator should have two parents and no arguments 136 | #[derive(Clone, Copy, Debug, PartialEq)] 137 | pub enum BinaryOperatorType { 138 | /// Represents elementwise max(x,y) 139 | Max, 140 | /// Represents elementwise min(x,y) 141 | Min, 142 | /// Represents elemntwise power x^y 143 | Pow, 144 | /// Represents the matrix quadratic form M_1^T M_2 M_1 145 | Quadratic 146 | } 147 | 148 | /// An enum for operators which are applied to several parent nodes 149 | /// 150 | /// The operator should have at least two parents and no arguments 151 | #[derive(Clone, Copy, Debug, PartialEq)] 152 | pub enum NaryOperatorType { 153 | /// Represents a + b + ... + z 154 | Add, 155 | /// Represents elementwise a * b * ... * z 156 | Mul, 157 | /// Represents the linear algebra matrix multiplication M_a M_b ... M_z 158 | Dot, 159 | /// Concatenates horizontally all of its arguments 160 | HorzCat, 161 | /// Concatenates vertically all of its arguments 162 | VertCat 163 | } 164 | 165 | /// An enum for special operators which take a single parent node. 166 | /// 167 | /// The operator should have one parent and several arguments 168 | #[derive(Clone, Copy, Debug, PartialEq)] 169 | pub enum SpecialUnaryOperatorType { 170 | /// Takes the sub block of the parent node described by the following 4 arguments. 171 | /// The operator has the following syntax: (parent, start_x, sizeOfBlockX, start_y, sizeOfBlockY) 172 | SubIndex, 173 | /// Represents subassignment. This will produce a matrix for which the sub block described by the 4 argument will be equal to the parent node. E.g. this means that the result is a matrix of zeros, whose subblock is equal to the parent. 174 | /// The operator has the following syntax: (parent, start_x, sizeOfBlockX, start_y, sizeOfBlockY) 175 | SubAssign, 176 | /// Represents reshaping the parent node to a size given by its arguments. 177 | /// The operator has the following syntax: (parent, dim_1, dim_2) 178 | Reshape, 179 | /// Represents the replication of the parent node horizontally. It is assumed that it is a scalar or column vector. 180 | /// The operator has the following syntax: (parent, times) 181 | ReplicateHorz, 182 | /// Represents the replication of the parent node vertically. It is assumed that it is a scalar or row vector. 183 | /// The operator has the following syntax: (parent, times) 184 | ReplicateVert 185 | } 186 | 187 | impl SpecialUnaryOperatorType{ 188 | /// Returns the number of required arguments for the operator 189 | pub fn required_num_of_args(&self) -> usize { 190 | match *self{ 191 | SpecialUnaryOperatorType::SubIndex => 4, 192 | SpecialUnaryOperatorType::SubAssign => 4, 193 | SpecialUnaryOperatorType::Reshape => 2, 194 | SpecialUnaryOperatorType::ReplicateHorz | SpecialUnaryOperatorType::ReplicateVert=> 1, 195 | } 196 | } 197 | } 198 | 199 | /// An enum that represents all supported mathematical operations 200 | #[derive(Clone, Copy, Debug, PartialEq)] 201 | pub enum OperatorType { 202 | /// A `ConstantOperatorType` 203 | Constant(ConstantOperatorType), 204 | /// A `UnaryOperatorType` 205 | Unary(UnaryOperatorType), 206 | /// A `BinaryOperatorType` 207 | Binary(BinaryOperatorType), 208 | /// A `NaryOperatorType` 209 | Nary(NaryOperatorType), 210 | /// A `SpecialUnaryOperatorType` 211 | Special(SpecialUnaryOperatorType) 212 | } 213 | 214 | impl ::std::fmt::Display for OperatorType { 215 | fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { 216 | match *self { 217 | OperatorType::Constant(ConstantOperatorType::None) => Ok(()), 218 | OperatorType::Constant(ConstantOperatorType::Unary(op)) => write!(f, "{:?}", op), 219 | OperatorType::Constant(ConstantOperatorType::Binary(op)) => write!(f, "{:?}", op), 220 | OperatorType::Unary(op) => write!(f, "{:?}", op), 221 | OperatorType::Binary(op) => write!(f, "{:?}", op), 222 | OperatorType::Nary(op) => write!(f, "{:?}", op), 223 | OperatorType::Special(op) => write!(f, "{:?}", op) 224 | } 225 | } 226 | } 227 | 228 | impl ::std::convert::From for OperatorType { 229 | fn from(op: ConstantOperatorType) -> OperatorType { 230 | OperatorType::Constant(op) 231 | } 232 | } 233 | 234 | impl ::std::convert::From for OperatorType { 235 | fn from(op: ConstantUnaryOperatorType) -> OperatorType { 236 | OperatorType::Constant(ConstantOperatorType::Unary(op)) 237 | } 238 | } 239 | 240 | impl ::std::convert::From for OperatorType { 241 | fn from(op: ConstantBinaryOperatorType) -> OperatorType { 242 | OperatorType::Constant(ConstantOperatorType::Binary(op)) 243 | } 244 | } 245 | 246 | impl ::std::convert::From for OperatorType { 247 | fn from(op: UnaryOperatorType) -> OperatorType { 248 | OperatorType::Unary(op) 249 | } 250 | } 251 | 252 | impl ::std::convert::From for OperatorType { 253 | fn from(op: SpecialUnaryOperatorType) -> OperatorType { 254 | OperatorType::Special(op) 255 | } 256 | } 257 | 258 | impl ::std::convert::From for OperatorType { 259 | fn from(err: BinaryOperatorType) -> OperatorType { 260 | OperatorType::Binary(err) 261 | } 262 | } 263 | 264 | impl ::std::convert::From for OperatorType { 265 | fn from(err: NaryOperatorType) -> OperatorType { 266 | OperatorType::Nary(err) 267 | } 268 | } 269 | 270 | /// A struct that captures all supported mathematical operations with their metadata 271 | #[derive(Clone, Debug, PartialEq)] 272 | pub struct Operator { 273 | /// The type of this operator 274 | pub op_type: OperatorType, 275 | /// List of parent nodes 276 | pub parents: Vec, 277 | /// List of argument nodes 278 | pub args: Vec, 279 | } 280 | 281 | impl ::std::fmt::Display for Operator { 282 | fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { 283 | match self.op_type{ 284 | OPERATOR_NONE => Ok(()), 285 | _ => { 286 | if self.parents.len() > 0 && self.args.len() > 0 { 287 | write!(f, "{}[{:?}|{:?}]", self.op_type, self.parents, self.args) 288 | } else if self.parents.len() > 0 { 289 | write!(f, "{}[{:?}]", self.op_type, self.parents) 290 | } else if self.args.len() > 0 { 291 | write!(f, "{}[{:?}]", self.op_type, self.args) 292 | } else { 293 | write!(f, "{}", self.op_type) 294 | } 295 | } 296 | } 297 | } 298 | } 299 | 300 | impl Operator { 301 | /// Creates a new `Operator` with the given ancestors 302 | /// Returns an error if the given ancestors do not match the type of operator 303 | pub fn new(op_type: OperatorType, parents: Vec, args: Vec ) -> Result { 304 | if super::super::VERIFICATION { 305 | match op_type { 306 | OperatorType::Constant(ConstantOperatorType::None) => { 307 | if parents.len() != 0 { 308 | return Err(OperatorError::InvalidNumberOfParents(op_type,parents.len(),0)) 309 | } 310 | if args.len() != 0 { 311 | return Err(OperatorError::InvaludNumberOfArguments(op_type,args.len(),0)) 312 | } 313 | }, 314 | OperatorType::Constant(ConstantOperatorType::Unary(_)) | OperatorType::Unary(_) => { 315 | if parents.len() != 1 { 316 | return Err(OperatorError::InvalidNumberOfParents(op_type,parents.len(),1)) 317 | } 318 | if args.len() != 0 { 319 | return Err(OperatorError::InvaludNumberOfArguments(op_type,args.len(),0)) 320 | } 321 | }, 322 | OperatorType::Constant(ConstantOperatorType::Binary(_)) | OperatorType::Binary(_) => { 323 | if parents.len() != 2 { 324 | return Err(OperatorError::InvalidNumberOfParents(op_type,parents.len(),2)) 325 | } 326 | if args.len() != 0 { 327 | return Err(OperatorError::InvaludNumberOfArguments(op_type,args.len(),0)) 328 | } 329 | }, 330 | OperatorType::Nary(_) => { 331 | if parents.len() < 2 { 332 | return Err(OperatorError::InvalidNumberOfParents(op_type,parents.len(),2)) 333 | } 334 | if args.len() != 0 { 335 | return Err(OperatorError::InvaludNumberOfArguments(op_type,args.len(),0)) 336 | } 337 | }, 338 | OperatorType::Special(ref sp) => { 339 | if parents.len() != 1 { 340 | return Err(OperatorError::InvalidNumberOfParents(op_type,parents.len(),1)) 341 | } 342 | if args.len() != sp.required_num_of_args() { 343 | return Err(OperatorError::InvaludNumberOfArguments(op_type, args.len(), sp.required_num_of_args())) 344 | } 345 | } 346 | } 347 | } 348 | Ok(Operator{op_type: op_type, parents: parents, args: args}) 349 | } 350 | 351 | pub fn get_ancestors(&self) -> ::std::iter::Chain<::std::slice::Iter, ::std::slice::Iter> { 352 | self.parents.iter().chain(self.args.iter()) 353 | } 354 | 355 | /// Swaps the given parents of the operator 356 | /// Returns an error if `old_parent` was not in the parents' list 357 | pub fn swap_parent(&self, old_parent: usize, new_parent: usize) -> Result { 358 | let position = self.parents.iter().position(|&x| x == old_parent); 359 | match position { 360 | Some(_) => { 361 | let new_parents = self.parents.iter().map( 362 | |&x| if x == old_parent {new_parent} else {x}).collect::>(); 363 | Ok(try!(Operator::new(self.op_type, new_parents, self.args.clone()))) 364 | } 365 | None => Err(OperatorError::ParentNotFound(self.op_type, old_parent, self.parents.clone())) 366 | } 367 | } 368 | 369 | /// Swaps the given the parents of the operator in place 370 | /// Returns an error if `old_parent` was not in the parents' list 371 | pub fn swap_parent_in_place(&mut self, old_parent: usize, new_parent: usize) -> Result<(), OperatorError> { 372 | let position = self.parents.iter().position(|&x| x == old_parent); 373 | match position { 374 | Some(p) => { 375 | self.parents.push(new_parent); 376 | let _ = self.parents.swap_remove(p); 377 | Ok(()) 378 | } 379 | None => Err(OperatorError::ParentNotFound(self.op_type, old_parent, self.parents.clone())) 380 | } 381 | } 382 | 383 | /// Swaps the given the arguments of the operator 384 | /// Returns an error if `old_arg` was not in the arguments' list 385 | pub fn swap_argument(&self, old_arg: usize, new_arg: usize) -> Result{ 386 | let position = self.args.iter().position(|&x| x == old_arg); 387 | match position { 388 | Some(_) => { 389 | let new_args = self.args.iter().map( 390 | |&x| if x == old_arg {new_arg} else {x}).collect::>(); 391 | Ok(try!(Operator::new(self.op_type, self.parents.clone(), new_args))) 392 | }, 393 | None => Err(OperatorError::ArgumentNotFound(self.op_type, old_arg, self.args.clone())) 394 | } 395 | } 396 | 397 | /// Swaps the given the arguments of the operator in place 398 | /// Returns an error if `old_arg` was not in the arguments' list 399 | pub fn swap_argument_in_place(&mut self, old_arg: usize, new_arg: usize) -> Result<(), OperatorError> { 400 | let position = self.args.iter().position(|&x| x == old_arg); 401 | match position { 402 | Some(p) => { 403 | self.args.push(new_arg); 404 | let _ = self.args.swap_remove(p); 405 | Ok(()) 406 | } 407 | None => Err(OperatorError::ArgumentNotFound(self.op_type, old_arg, self.args.clone())) 408 | } 409 | } 410 | 411 | /// Swaps the given the ancestors of the operator, in all occurences both in the parents' and arguments' list 412 | /// Returns an error if `old_anc` was not in the parents' or in the arguments' list 413 | pub fn swap_ancestor(&self, old_anc: usize, new_anc: usize) -> Result { 414 | let position_p = self.args.iter().position(|&x| x == old_anc); 415 | let position_a = self.args.iter().position(|&x| x == old_anc); 416 | match position_p { 417 | Some(_) => { 418 | let new_parents = self.parents.iter().map( 419 | |&x| if x == old_anc {new_anc} else {x}).collect::>(); 420 | match position_a { 421 | Some(_) => { 422 | let new_args = self.args.iter().map( 423 | |&x| if x == old_anc {new_anc} else {x}).collect::>(); 424 | Ok(try!(Operator::new(self.op_type, new_parents, new_args))) 425 | }, 426 | None => Ok(try!(Operator::new(self.op_type, new_parents, self.args.clone()))) 427 | } 428 | }, 429 | None => match position_a { 430 | Some(_) => { 431 | let new_args = self.args.iter().map( 432 | |&x| if x == old_anc {new_anc} else {x}).collect::>(); 433 | Ok(try!(Operator::new(self.op_type, self.parents.clone(), new_args))) 434 | }, 435 | None => Err(OperatorError::AncestorNotFound(self.op_type, old_anc, self.parents.clone(), self.args.clone())) 436 | } 437 | } 438 | } 439 | 440 | /// Swaps the given the ancestors of the operator in place, in all occurences both in the parents' and arguments' list 441 | /// Returns an error if `old_anc` was not in the parents' or in the arguments' list 442 | pub fn swap_ancestor_in_place(&mut self, old_anc: usize, new_anc: usize) -> Result<(), OperatorError> { 443 | let result_p = self.swap_parent_in_place(old_anc, new_anc); 444 | let result_a = self.swap_argument_in_place(old_anc, new_anc); 445 | if result_p.is_ok() || result_a.is_ok() { 446 | Ok(()) 447 | } else { 448 | Err(OperatorError::AncestorNotFound(self.op_type, old_anc, self.parents.clone(), self.args.clone())) 449 | } 450 | } 451 | 452 | /// Creates an operator of the same type, but with different parents and argumetns 453 | // #[inline(always)] 454 | pub fn recreate(&self, parents: Vec, args: Vec) -> Result { 455 | Operator::new(self.op_type, parents, args) 456 | } 457 | } 458 | 459 | /// A `OperatorType::Constant(ConstantOperatorType::None)` 460 | pub const OPERATOR_NONE: OperatorType = OperatorType::Constant(ConstantOperatorType::None); 461 | /// A `OperatorType::Constant(ConstantOperatorType::Unary(ConstantUnaryOperatorType::Const))` 462 | pub const OPERATOR_CONST: OperatorType = OperatorType::Constant(ConstantOperatorType::Unary(ConstantUnaryOperatorType::Const)); 463 | /// A `OperatorType::Constant(ConstantOperatorType::Unary(ConstantUnaryOperatorType::Eye))` 464 | pub const OPERATOR_EYE: OperatorType = OperatorType::Constant(ConstantOperatorType::Unary(ConstantUnaryOperatorType::Eye)); 465 | /// A `OperatorType::Constant(ConstantOperatorType::Unary(ConstantUnaryOperatorType::Sign))` 466 | pub const OPERATOR_SIGN: OperatorType = OperatorType::Constant(ConstantOperatorType::Unary(ConstantUnaryOperatorType::Sign)); 467 | /// A `OperatorType::Constant(ConstantOperatorType::Unary(ConstantUnaryOperatorType::Size(Dimension::First)))` 468 | pub const OPERATOR_SIZE_1: OperatorType = OperatorType::Constant(ConstantOperatorType::Unary(ConstantUnaryOperatorType::Size(Dimension::First))); 469 | /// A `OperatorType::Constant(ConstantOperatorType::Unary(ConstantUnaryOperatorType::Size(Dimension::Second)))` 470 | pub const OPERATOR_SIZE_2: OperatorType = OperatorType::Constant(ConstantOperatorType::Unary(ConstantUnaryOperatorType::Size(Dimension::Second))); 471 | /// A `OperatorType::Constant(ConstantOperatorType::Binary(ConstantBinaryOperatorType::Ones))` 472 | pub const OPERATOR_ONES: OperatorType = OperatorType::Constant(ConstantOperatorType::Binary(ConstantBinaryOperatorType::Ones)); 473 | /// A `OperatorType::Constant(ConstantOperatorType::Binary(ConstantBinaryOperatorType::Zeros))` 474 | pub const OPERATOR_ZEROS: OperatorType = OperatorType::Constant(ConstantOperatorType::Binary(ConstantBinaryOperatorType::Zeros)); 475 | /// A `OperatorType::Constant(ConstantOperatorType::Binary(ConstantBinaryOperatorType::LessThan))` 476 | pub const OPERATOR_LT: OperatorType = OperatorType::Constant(ConstantOperatorType::Binary(ConstantBinaryOperatorType::LessThan)); 477 | /// A `OperatorType::Constant(ConstantOperatorType::Binary(ConstantBinaryOperatorType::LessThanOrEqual))` 478 | pub const OPERATOR_LTE: OperatorType = OperatorType::Constant(ConstantOperatorType::Binary(ConstantBinaryOperatorType::LessThanOrEqual)); 479 | /// A `OperatorType::Constant(ConstantOperatorType::Binary(ConstantBinaryOperatorType::GreaterThan))` 480 | pub const OPERATOR_GT: OperatorType = OperatorType::Constant(ConstantOperatorType::Binary(ConstantBinaryOperatorType::GreaterThan)); 481 | /// A `OperatorType::Constant(ConstantOperatorType::Binary(ConstantBinaryOperatorType::GreaterThanOrEqual))` 482 | pub const OPERATOR_GTE: OperatorType = OperatorType::Constant(ConstantOperatorType::Binary(ConstantBinaryOperatorType::GreaterThanOrEqual)); 483 | /// A `OperatorType::Constant(ConstantOperatorType::Binary(ConstantBinaryOperatorType::Equals))` 484 | pub const OPERATOR_EQ: OperatorType = OperatorType::Constant(ConstantOperatorType::Binary(ConstantBinaryOperatorType::Equals)); 485 | /// A `OperatorType::Constant(ConstantOperatorType::Binary(ConstantBinaryOperatorType::NotEquals))` 486 | pub const OPERATOR_NEQ: OperatorType = OperatorType::Constant(ConstantOperatorType::Binary(ConstantBinaryOperatorType::NotEquals)); 487 | /// A `OperatorType = OperatorType::Unary(UnaryOperatorType::Neg)` 488 | pub const OPERATOR_NEG: OperatorType = OperatorType::Unary(UnaryOperatorType::Neg); 489 | /// A `OperatorType = OperatorType::Unary(UnaryOperatorType::Div)` 490 | pub const OPERATOR_DIV: OperatorType = OperatorType::Unary(UnaryOperatorType::Div); 491 | /// A `OperatorType = OperatorType::Unary(UnaryOperatorType::MatrixInverse)` 492 | pub const OPERATOR_MINV: OperatorType = OperatorType::Unary(UnaryOperatorType::MatrixInverse); 493 | /// A `OperatorType = OperatorType::Unary(UnaryOperatorType::Transpose)` 494 | pub const OPERATOR_TRANSPOSE: OperatorType = OperatorType::Unary(UnaryOperatorType::Transpose); 495 | /// A `OperatorType = OperatorType::Unary(UnaryOperatorType::MatrixDiag)` 496 | pub const OPERATOR_MDIAG: OperatorType = OperatorType::Unary(UnaryOperatorType::MatrixDiag); 497 | /// A `OperatorType = OperatorType::Unary(UnaryOperatorType::VectorDiag)` 498 | pub const OPERATOR_VDIAG: OperatorType = OperatorType::Unary(UnaryOperatorType::VectorDiag); 499 | /// A `OperatorType = OperatorType::Unary(UnaryOperatorType::Cos)` 500 | pub const OPERATOR_COS: OperatorType = OperatorType::Unary(UnaryOperatorType::Cos); 501 | /// A `OperatorType = OperatorType::Unary(UnaryOperatorType::Sin)` 502 | pub const OPERATOR_SIN: OperatorType = OperatorType::Unary(UnaryOperatorType::Sin); 503 | /// A `OperatorType = OperatorType::Unary(UnaryOperatorType::Tan)` 504 | pub const OPERATOR_TAN: OperatorType = OperatorType::Unary(UnaryOperatorType::Tan); 505 | /// A `OperatorType = OperatorType::Unary(UnaryOperatorType::CosH)` 506 | pub const OPERATOR_COSH: OperatorType = OperatorType::Unary(UnaryOperatorType::CosH); 507 | /// A `OperatorType = OperatorType::Unary(UnaryOperatorType::SinH)` 508 | pub const OPERATOR_SINH: OperatorType = OperatorType::Unary(UnaryOperatorType::SinH); 509 | /// A `OperatorType = OperatorType::Unary(UnaryOperatorType::TanH)` 510 | pub const OPERATOR_TANH: OperatorType = OperatorType::Unary(UnaryOperatorType::TanH); 511 | /// A `OperatorType = OperatorType::Unary(UnaryOperatorType::Abs)` 512 | pub const OPERATOR_ABS: OperatorType = OperatorType::Unary(UnaryOperatorType::Abs); 513 | /// A `OperatorType = OperatorType::Unary(UnaryOperatorType::Log)` 514 | pub const OPERATOR_LOG: OperatorType = OperatorType::Unary(UnaryOperatorType::Log); 515 | /// A `OperatorType = OperatorType::Unary(UnaryOperatorType::Exp)` 516 | pub const OPERATOR_EXP: OperatorType = OperatorType::Unary(UnaryOperatorType::Exp); 517 | /// A `OperatorType = OperatorType::Unary(UnaryOperatorType::Sqrt)` 518 | pub const OPERATOR_SQRT: OperatorType = OperatorType::Unary(UnaryOperatorType::Sqrt); 519 | /// A `OperatorType = OperatorType::Unary(UnaryOperatorType::Square)` 520 | pub const OPERATOR_SQUARE: OperatorType = OperatorType::Unary(UnaryOperatorType::Square); 521 | /// A `OperatorType = OperatorType::Unary(UnaryOperatorType::Sigmoid)` 522 | pub const OPERATOR_SIGM: OperatorType = OperatorType::Unary(UnaryOperatorType::Sigmoid); 523 | /// A `OperatorType = OperatorType::Unary(UnaryOperatorType::Rectifier)` 524 | pub const OPERATOR_RECT: OperatorType = OperatorType::Unary(UnaryOperatorType::Rectifier); 525 | /// A `OperatorType::Unary(UnaryOperatorType::Sum(Dimension::All))` 526 | pub const OPERATOR_SUM_ALL: OperatorType = OperatorType::Unary(UnaryOperatorType::Sum(Dimension::All)); 527 | /// A `OperatorType::Unary(UnaryOperatorType::Sum(Dimension::First))` 528 | pub const OPERATOR_SUM_1: OperatorType = OperatorType::Unary(UnaryOperatorType::Sum(Dimension::First)); 529 | /// A `OperatorType::Unary(UnaryOperatorType::Sum(Dimension::Second))` 530 | pub const OPERATOR_SUM_2: OperatorType = OperatorType::Unary(UnaryOperatorType::Sum(Dimension::Second)); 531 | /// A `OperatorType::Unary(UnaryOperatorType::L2(Dimension::All))` 532 | pub const OPERATOR_L2_ALL: OperatorType = OperatorType::Unary(UnaryOperatorType::L2(Dimension::All)); 533 | /// A `OperatorType::Unary(UnaryOperatorType::L2(Dimension::First))` 534 | pub const OPERATOR_L2_1: OperatorType = OperatorType::Unary(UnaryOperatorType::L2(Dimension::First)); 535 | /// A `OperatorType::Unary(UnaryOperatorType::L2(Dimension::Second))` 536 | pub const OPERATOR_L2_2: OperatorType = OperatorType::Unary(UnaryOperatorType::L2(Dimension::Second)); 537 | /// A `OperatorType::Unary(UnaryOperatorType::L1(Dimension::All))` 538 | pub const OPERATOR_L1_ALL: OperatorType = OperatorType::Unary(UnaryOperatorType::L1(Dimension::All)); 539 | /// A `OperatorType::Unary(UnaryOperatorType::L1(Dimension::First))` 540 | pub const OPERATOR_L1_1: OperatorType = OperatorType::Unary(UnaryOperatorType::L1(Dimension::First)); 541 | /// A `OperatorType::Unary(UnaryOperatorType::L1(Dimension::Second))` 542 | pub const OPERATOR_L1_2: OperatorType = OperatorType::Unary(UnaryOperatorType::L1(Dimension::Second)); 543 | /// A `OperatorType::Binary(BinaryOperatorType::Max))` 544 | pub const OPERATOR_MAX: OperatorType = OperatorType::Binary(BinaryOperatorType::Max); 545 | /// A `OperatorType::Binary(BinaryOperatorType::Min))` 546 | pub const OPERATOR_MIN: OperatorType = OperatorType::Binary(BinaryOperatorType::Min); 547 | /// A `OperatorType::Binary(BinaryOperatorType::Pow))` 548 | pub const OPERATOR_POW: OperatorType = OperatorType::Binary(BinaryOperatorType::Pow); 549 | /// A `OperatorType::Binary(BinaryOperatorType::Quadratic))` 550 | pub const OPERATOR_QUAD: OperatorType = OperatorType::Binary(BinaryOperatorType::Quadratic); 551 | /// A `OperatorType::Nary(NaryOperatorType::Add)` 552 | pub const OPERATOR_ADD: OperatorType = OperatorType::Nary(NaryOperatorType::Add); 553 | /// A `OperatorType::Nary(NaryOperatorType::Mul)` 554 | pub const OPERATOR_MUL: OperatorType = OperatorType::Nary(NaryOperatorType::Mul); 555 | /// A `OperatorType::Nary(NaryOperatorType::Dot)` 556 | pub const OPERATOR_DOT: OperatorType = OperatorType::Nary(NaryOperatorType::Dot); 557 | /// A `OperatorType::Nary(NaryOperatorType::HorzCat)` 558 | pub const OPERATOR_HORZCAT: OperatorType = OperatorType::Nary(NaryOperatorType::HorzCat); 559 | /// A `OperatorType::Nary(NaryOperatorType::VertCat)` 560 | pub const OPERATOR_VERTCAT: OperatorType = OperatorType::Nary(NaryOperatorType::VertCat); 561 | /// A `OperatorType::Special(SpecialUnaryOperatorType::SubIndex)` 562 | pub const OPERATOR_SUBINDEX: OperatorType = OperatorType::Special(SpecialUnaryOperatorType::SubIndex); 563 | /// A `OperatorType::Special(SpecialUnaryOperatorType::SubAssign)` 564 | pub const OPERATOR_SUBASSIGN: OperatorType = OperatorType::Special(SpecialUnaryOperatorType::SubAssign); 565 | /// A `OperatorType::Special(SpecialUnaryOperatorType::Reshape)` 566 | pub const OPERATOR_RESHAPE: OperatorType = OperatorType::Special(SpecialUnaryOperatorType::Reshape); 567 | /// A `OperatorType::Special(SpecialUnaryOperatorType::ReplicateHorz)` 568 | pub const OPERATOR_REPLICATEH: OperatorType = OperatorType::Special(SpecialUnaryOperatorType::ReplicateHorz); 569 | /// A `OperatorType::Special(SpecialUnaryOperatorType::ReplicateVert)` 570 | pub const OPERATOR_REPLICATEV: OperatorType = OperatorType::Special(SpecialUnaryOperatorType::ReplicateVert); 571 | 572 | 573 | 574 | // /// Represents the possible NotFoundErrorType 575 | // #[derive(Clone, Copy, Debug)] 576 | // pub enum NotFoundErrorType{ 577 | // /// The node is a parent 578 | // Parent, 579 | // /// The node is an argument 580 | // Argument, 581 | // /// The node is either a parent or an argument 582 | // Ancestor 583 | // } 584 | 585 | /// An error when trying to create or manipulate an operator in in consistent way 586 | #[derive(Clone, Debug)] 587 | pub enum OperatorError{ 588 | /// When trying to swap a prent which is not in the parents' list 589 | /// Fields are (operator, requested parent, parents' list) 590 | ParentNotFound(OperatorType,usize, Vec), 591 | /// When trying to swap an argument which is not in the parents' list 592 | /// Fields are (operator, requested argument, arguments' list) 593 | ArgumentNotFound(OperatorType,usize, Vec), 594 | /// When trying to swap an ancestor which is not in the parents' list 595 | /// Fields are (operator, requested ancestor, parents' list, arguments' list) 596 | AncestorNotFound(OperatorType,usize, Vec, Vec), 597 | /// When trying to create an operator with the wrong number of parents 598 | /// Fields are (operator, given number of parents, expected number of parents) 599 | InvalidNumberOfParents(OperatorType, usize, usize), 600 | /// When trying to create an operator with the wrong number of arguments 601 | /// Fields are (operator, given number of parents, expected number of parents) 602 | InvaludNumberOfArguments(OperatorType, usize, usize), 603 | /// When trying to create an operator with the wrong number of ancesotrs 604 | /// Fields are (operator, given number of parents, expected number of parents) 605 | InvalidNumberOfAncestors(OperatorType, usize, usize), 606 | /// When trying to create an operator with wrongly specified dimension. These are in in integer format where 0 is `Dimension::All` 607 | /// Fields are (operator name, dimension provided, possible dimensions) 608 | InvalidDimensionArgument(String, usize, Vec) 609 | } 610 | 611 | impl ::std::fmt::Display for OperatorError { 612 | fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { 613 | match *self { 614 | OperatorError::ParentNotFound(op,req,ref actual) => write!(f, "Requested parent {} for operator {} does not exist. Parents: {:?}", req, op, actual), 615 | OperatorError::ArgumentNotFound(op,req,ref actual) => write!(f, "Requested argument {} for operator {} does not exist. Arguments: {:?}", req, op, actual), 616 | OperatorError::AncestorNotFound(op,req,ref p_list,ref arg_list) => write!(f, "Requested ancestor {} for operator {} does not exist. Parents: {:?}, Arguments: {:?}", req, op, p_list, arg_list), 617 | OperatorError::InvalidNumberOfParents(op, given, expected) => write!(f, "Can not create an operator {} with {} parents, when {} are required", op, given, expected), 618 | OperatorError::InvaludNumberOfArguments(op, given, expected) => write!(f, "Can not create an operator {} with {} arguments, when {} are required", op, given, expected), 619 | OperatorError::InvalidNumberOfAncestors(op, given, expected) => write!(f, "Can not create an operator {} with {} ancesotrs, when {} are required", op, given, expected), 620 | OperatorError::InvalidDimensionArgument(ref name, given, ref expected) => write!(f, "Can not create an operator {} with dimension {}, when {:?} are possible", name, given, expected), 621 | } 622 | } 623 | } 624 | 625 | impl ::std::error::Error for OperatorError { 626 | fn description(&self) -> &str { 627 | match *self { 628 | OperatorError::ParentNotFound(_,_,_) => "Attempted swapping of a parent which is not present in the parents' list", 629 | OperatorError::ArgumentNotFound(_,_,_) => "Attempted swapping of an argument which is not present in the arguments' list", 630 | OperatorError::AncestorNotFound(_,_,_,_) => "Attempted swapping of an ancestor which is not present in either the parertns' or the arguments' list", 631 | OperatorError::InvalidNumberOfParents(_,_,_) => "Attempted to create an operator with wrong number of parents", 632 | OperatorError::InvaludNumberOfArguments(_,_,_) => "Attempted to create an operator with wrong number of arguments", 633 | OperatorError::InvalidNumberOfAncestors(_,_,_) => "Attempted to create an operator with wrong number of acnestors", 634 | OperatorError::InvalidDimensionArgument(_,_,_) => "Attempted to create an operator with wrong dimensionality argument" 635 | } 636 | } 637 | } 638 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![feature(dynamic_lib)] 2 | /// A flag for enabling certain form of verification inside the different modules. This is similar to a debugging flag, but will guarantee semantic checks in each module, where needed. 3 | /// 4 | /// Until the library has proven to be stable it is required it to always be set to `true` 5 | const VERIFICATION: bool = true; 6 | 7 | pub mod core; 8 | pub mod optimization; 9 | pub mod codegen; 10 | pub mod linking; 11 | 12 | use std::io::Write; 13 | pub fn print_graph(graph: &core::ComputeGraph, directory: &mut std::path::PathBuf, name: &String) -> Result<(), ProgramError>{ 14 | // Print cmd graph 15 | directory.push(name.clone() + ".txt"); 16 | let file = try!(std::fs::File::create(directory.as_path())); 17 | let mut writer = std::io::BufWriter::new(&file); 18 | try!(writer.write_fmt(format_args!("{}\n",graph))); 19 | directory.pop(); 20 | 21 | // Print graphviz 22 | directory.push(name.clone() + ".dot"); 23 | let file = try!(std::fs::File::create(directory.as_path())); 24 | let mut writer = std::io::BufWriter::new(&file); 25 | try!(codegen::write_graphviz(&mut writer as &mut std::io::Write, &graph)); 26 | directory.pop(); 27 | Ok(()) 28 | } 29 | 30 | #[derive(Debug)] 31 | pub enum ProgramError { 32 | Io(std::io::Error), 33 | Parse(core::ParseError), 34 | Graph(core::GraphError), 35 | Other(String) 36 | } 37 | 38 | impl From for ProgramError { 39 | fn from(err: std::io::Error) -> ProgramError { 40 | ProgramError::Io(err) 41 | } 42 | } 43 | 44 | impl From for ProgramError { 45 | fn from(err: core::ParseError) -> ProgramError { 46 | ProgramError::Parse(err) 47 | } 48 | } 49 | 50 | impl From for ProgramError { 51 | fn from(err: core::GraphError) -> ProgramError { 52 | ProgramError::Graph(err) 53 | } 54 | } 55 | 56 | 57 | impl From for ProgramError { 58 | fn from(err: String) -> ProgramError { 59 | ProgramError::Other(err) 60 | } 61 | } 62 | 63 | impl std::fmt::Display for ProgramError { 64 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 65 | match *self { 66 | ProgramError::Io(ref err) => err.fmt(f), 67 | ProgramError::Parse(ref err) => err.fmt(f), 68 | ProgramError::Graph(ref err) => err.fmt(f), 69 | ProgramError::Other(ref err) => err.fmt(f), 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/linking.rs: -------------------------------------------------------------------------------- 1 | use std::process::Command; 2 | use std::io::Write; 3 | use std::dynamic_lib::DynamicLibrary; 4 | use std::result::Result; 5 | 6 | /// An encapsulater object of a function loaded from a dynamic library. 7 | /// The object is required because the if the `DynamicLibrary` object is dropped the function pointer will no longer be valid 8 | pub struct DLFunction{ 9 | pub lib: DynamicLibrary, 10 | pub func: fn(P) -> R 11 | } 12 | 13 | impl DLFunction { 14 | /// Evaluates the function with the given parameters 15 | // #[inline(always)] 16 | pub fn eval(&self, args: P) -> R { 17 | (self.func)(args) 18 | } 19 | } 20 | 21 | /// The function performs several actions in sequence: 22 | /// 23 | /// * Creates a file `location/file_name.rs` 24 | /// * Writes the source code to the file 25 | /// * Compiles the source code using rustc to a dynamic library `location/file_name.so` 26 | /// * Opens the compiled dynamic library 27 | /// * Finds and links from the symbol table `func_name` 28 | /// * Returns a `DLFunction` object 29 | pub fn dynamical_linking_rust(source: &str, file_name: &str, location: &mut ::std::path::PathBuf, func_name: &str) 30 | -> Result,DynamicLinkingError>{ 31 | // Write source code to file 32 | let mut source_loc = location.clone(); 33 | source_loc.push(&file_name); 34 | source_loc.set_extension("rs"); 35 | let file = try!(::std::fs::File::create(source_loc.as_path())); 36 | { 37 | let mut writer = ::std::io::BufWriter::new(&file); 38 | let _ = try!(writer.write_fmt(format_args!("{}\n",source))); 39 | } 40 | // Compile the source code 41 | let mut target_loc = location.clone(); 42 | target_loc.push(&file_name); 43 | target_loc.set_extension("so"); 44 | let cmd = format!("rustc --crate-type dylib {} -o {}", 45 | source_loc.into_os_string().to_str().unwrap(), 46 | target_loc.clone().into_os_string().to_str().unwrap()); 47 | let output = Command::new("sh") 48 | .arg("-c") 49 | .arg(cmd) 50 | .output() 51 | .unwrap_or_else(|e| { panic!("failed to execute process: {}", e) }); 52 | // Check if compilation is ok 53 | if !output.status.success() { 54 | return Err(DynamicLinkingError::Compilation(String::from_utf8(output.stderr).unwrap())) 55 | } 56 | 57 | // Link the library 58 | let lib = match DynamicLibrary::open(Some(target_loc.as_path())){ 59 | Ok(lib) => lib, 60 | Err(err) => return Err(DynamicLinkingError::OpenLibrary(err)) 61 | }; 62 | let func: fn(P) -> R = unsafe { 63 | match lib.symbol(func_name) { 64 | Ok(func) => ::std::mem::transmute::<*mut u8,fn(P) -> R>(func), 65 | Err(err) => return Err(DynamicLinkingError::SymbolTable(err)) 66 | } 67 | }; 68 | Ok(DLFunction{lib: lib, func: func}) 69 | } 70 | 71 | #[derive(Debug)] 72 | pub enum DynamicLinkingError{ 73 | Io(::std::io::Error), 74 | Compilation(String), 75 | OpenLibrary(String), 76 | SymbolTable(String) 77 | } 78 | 79 | impl ::std::convert::From<::std::io::Error> for DynamicLinkingError { 80 | fn from(err: ::std::io::Error) -> DynamicLinkingError { 81 | DynamicLinkingError::Io(err) 82 | } 83 | } 84 | 85 | impl ::std::fmt::Display for DynamicLinkingError { 86 | fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { 87 | match *self { 88 | DynamicLinkingError::Io(ref err) => write!(f, "{}", err), 89 | DynamicLinkingError::Compilation(ref err) => write!(f, "{}", err), 90 | DynamicLinkingError::OpenLibrary(ref err) => write!(f, "{}", err), 91 | DynamicLinkingError::SymbolTable(ref err) => write!(f, "{}", err), 92 | } 93 | } 94 | } 95 | 96 | impl ::std::error::Error for DynamicLinkingError { 97 | fn description(&self) -> &str { 98 | match *self { 99 | DynamicLinkingError::Io(ref err) => err.description(), 100 | DynamicLinkingError::Compilation(_) => "Compilation of the source code failed", 101 | DynamicLinkingError::OpenLibrary(_) => "Opening the compiled library failed", 102 | DynamicLinkingError::SymbolTable(_) => "Finding the function in the symbol table failed", 103 | } 104 | } 105 | 106 | fn cause(&self) -> Option<&::std::error::Error> { 107 | match *self { 108 | DynamicLinkingError::Io(ref err) => Some(err), 109 | _ => None 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | extern crate meta_diff; 2 | extern crate rustc_serialize; 3 | extern crate docopt; 4 | 5 | static USAGE: &'static str = "Meta Diff 6 | 7 | Usage: 8 | meta_diff 9 | meta_diff --help 10 | meta_diff --version 11 | 12 | Options: 13 | -h --help Show this usage message. 14 | -v --version Show the version and exit. 15 | "; 16 | 17 | #[derive(RustcDecodable, Debug)] 18 | struct Args { 19 | arg_source: String, 20 | flag_version: bool 21 | } 22 | 23 | fn main() { 24 | let args: Args = docopt::Docopt::new(USAGE).and_then(|d| d.decode()).unwrap_or_else(|e| e.exit()); 25 | if args.flag_version{ 26 | println!("Meta Diff version {}.{}.{}",0,0,1); 27 | std::process::exit(0); 28 | } 29 | match main_proxy(args){ 30 | Ok(_) => (), 31 | Err(err) => { 32 | use std::io::Write; 33 | writeln!(&mut std::io::stderr(), "{}", err).unwrap(); 34 | std::process::exit(1); 35 | } 36 | } 37 | } 38 | 39 | use std::io::{Read,Write}; 40 | fn main_proxy(args: Args) -> Result<(), meta_diff::ProgramError> { 41 | // Read source file 42 | let mut source = String::new(); 43 | let path = std::path::Path::new(&args.arg_source); 44 | let mut file = try!(std::fs::File::open(&path)); 45 | try!(file.read_to_string(&mut source)); 46 | 47 | // Set up output directory 48 | let file_name = try!(path.file_name().ok_or(std::io::Error::new(std::io::ErrorKind::InvalidInput 49 | , "The file given does not exist or is a directory."))); 50 | let file_noextension = file_name.to_str().unwrap().split(".").nth(0).unwrap().to_string(); 51 | let mut directory = try!(std::env::current_dir()); 52 | directory.push(file_noextension.clone()); 53 | let _ = std::fs::create_dir(directory.as_path()); 54 | 55 | // Parse source file 56 | let mut graph = try!(meta_diff::core::parseMetaFile(&source)); 57 | // Print initial 58 | try!(meta_diff::print_graph(&graph, &mut directory, &file_noextension)); 59 | // Gradient 60 | try!(graph.direct_gradient()); 61 | try!(meta_diff::print_graph(&graph, &mut directory, &(file_noextension.clone() + "_grad"))); 62 | // Hessian-vector product 63 | let (ids, names) = graph.get_params(); 64 | let vs = ids.iter().zip(names.iter()).map(|(id, name)| { 65 | let v = graph.add_const_input(name.clone() + &"_v".to_string()); 66 | let op = meta_diff::core::OperatorType::Nary(meta_diff::core::NaryOperatorType::Mul); 67 | graph.add_operation(op,vec![*id, v]).unwrap() 68 | }).collect::>(); 69 | let target = try!(graph.add_operation( 70 | meta_diff::core::OperatorType::Nary(meta_diff::core::NaryOperatorType::Add),vs)); 71 | try!(graph.gradient(target)); 72 | try!(meta_diff::print_graph(&graph, &mut directory, &(file_noextension.clone() + "_hess"))); 73 | Ok(()) 74 | } 75 | -------------------------------------------------------------------------------- /src/optimization/constant_folding.rs: -------------------------------------------------------------------------------- 1 | use core::*; 2 | 3 | /// Performs constant folding on all nodes of the graph 4 | /// 5 | /// This means that all nodes which are of types `Int(x)` or `Float(x)` are combined where possible. 6 | /// Also nodes of the from `OPERATOR_CONST(x)` where `x` is by itself `ConstInput` or `ConstDerivde` are unfolded 7 | /// 8 | /// Returns true if the graph has been modified, false otherwise. 9 | /// An error if any of the operations brings up a `GraphError` 10 | pub fn constant_folding(graph: &mut ComputeGraph) -> Result { 11 | let mut outcome = false; 12 | let mut i = 0; 13 | loop { 14 | // Grab operator 15 | let node = match graph.nodes[i] { 16 | Some(_) => true, 17 | None => false 18 | }; 19 | let result = if node { 20 | try!(single_fold(graph, i)) 21 | } else { 22 | false 23 | }; 24 | outcome = outcome || result; 25 | i += 1; 26 | if i == graph.nodes.len(){ 27 | break; 28 | } 29 | } 30 | Ok(outcome) 31 | } 32 | 33 | fn single_fold(graph: &mut ComputeGraph, old: usize) -> Result{ 34 | let op = try!(graph.get_node(old)).op.clone(); 35 | let mut created_nodes : Vec = Vec::new(); 36 | let mut new_node : Option = None; 37 | let mut parents : Vec = Vec::new(); 38 | match op.op_type{ 39 | OPERATOR_CONST => { 40 | let parent = try!(graph.get_node(op.parents[0])); 41 | match parent.node_type { 42 | Type::Integer(_) | Type::Float(_) | 43 | Type::ConstInput | Type::ConstDerived => { 44 | // Remove const(x) where x is itself a constant 45 | if parent.grad_parents.len() > 0 || parent.grad_child.is_some() { 46 | return Err(GraphError::GradientOfConstant(op.parents[0])) 47 | } 48 | else { 49 | new_node = Some(op.parents[0]); 50 | parents.push(op.parents[0]); 51 | } 52 | }, 53 | _ => () 54 | } 55 | }, 56 | OPERATOR_TRANSPOSE | OPERATOR_MDIAG | OPERATOR_VDIAG 57 | | OPERATOR_SUM_ALL | OPERATOR_SUM_1 | OPERATOR_SUM_2 => { 58 | 59 | match try!(graph.get_node(op.parents[0])).node_type { 60 | Type::Integer(_) | Type::Float(_) => { 61 | new_node = Some(op.parents[0]); 62 | parents.push(op.parents[0]); 63 | } 64 | _ => () 65 | } 66 | }, 67 | OPERATOR_SIZE_1 | OPERATOR_SIZE_2 => { 68 | match try!(graph.get_node(op.parents[0])).node_type{ 69 | Type::Float(_) | Type::Integer(_) => { 70 | let node = graph.add_int(1); 71 | created_nodes.push(node); 72 | new_node = Some(node); 73 | parents.push(op.parents[0]); 74 | }, 75 | _ => () 76 | } 77 | }, 78 | OPERATOR_SIGN =>{ 79 | match try!(graph.get_node(op.parents[0])).node_type { 80 | Type::Float(x) => { 81 | let node = if x == 0.0 { 82 | graph.add_int(0) 83 | } else if x < 0.0 { 84 | graph.add_int(-1) 85 | } else { 86 | graph.add_int(1) 87 | }; 88 | created_nodes.push(node); 89 | new_node = Some(node); 90 | parents.push(op.parents[0]); 91 | }, 92 | Type::Integer(x) => { 93 | let node = if x == 0 { 94 | graph.add_int(0) 95 | } else if x < 0 { 96 | graph.add_int(-1) 97 | } else { 98 | graph.add_int(1) 99 | }; 100 | created_nodes.push(node); 101 | new_node = Some(node); 102 | parents.push(op.parents[0]); 103 | }, 104 | _ => () 105 | } 106 | }, 107 | OPERATOR_NEG => { 108 | match try!(graph.get_node(op.parents[0])).node_type { 109 | Type::Float(x) => { 110 | let node = graph.add_float(-x); 111 | created_nodes.push(node); 112 | new_node = Some(node); 113 | parents.push(op.parents[0]); 114 | }, 115 | Type::Integer(x) => { 116 | let node = graph.add_int(-x); 117 | created_nodes.push(node); 118 | new_node = Some(node); 119 | parents.push(op.parents[0]); 120 | }, 121 | _ => () 122 | } 123 | }, 124 | OPERATOR_DIV | OPERATOR_MINV => { 125 | match try!(graph.get_node(op.parents[0])).node_type { 126 | Type::Float(x) => { 127 | let node = graph.add_float(1.0/x); 128 | created_nodes.push(node); 129 | new_node = Some(node); 130 | parents.push(op.parents[0]); 131 | }, 132 | Type::Integer(x) => { 133 | let node = graph.add_float(1.0/(x as f64)); 134 | created_nodes.push(node); 135 | new_node = Some(node); 136 | parents.push(op.parents[0]); 137 | }, 138 | _ => () 139 | } 140 | }, 141 | OPERATOR_COS => { 142 | match try!(graph.get_node(op.parents[0])).node_type { 143 | Type::Float(x) => { 144 | let node = graph.add_float(x.cos()); 145 | created_nodes.push(node); 146 | new_node = Some(node); 147 | parents.push(op.parents[0]); 148 | }, 149 | Type::Integer(x) => { 150 | let node = graph.add_float((x as f64).cos()); 151 | created_nodes.push(node); 152 | new_node = Some(node); 153 | parents.push(op.parents[0]); 154 | }, 155 | _ => () 156 | } 157 | }, 158 | OPERATOR_SIN => { 159 | match try!(graph.get_node(op.parents[0])).node_type { 160 | Type::Float(x) => { 161 | let node = graph.add_float(x.sin()); 162 | created_nodes.push(node); 163 | new_node = Some(node); 164 | parents.push(op.parents[0]); 165 | }, 166 | Type::Integer(x) => { 167 | let node = graph.add_float((x as f64).sin()); 168 | created_nodes.push(node); 169 | new_node = Some(node); 170 | parents.push(op.parents[0]); 171 | }, 172 | _ => () 173 | } 174 | }, 175 | OPERATOR_TAN => { 176 | match try!(graph.get_node(op.parents[0])).node_type { 177 | Type::Float(x) => { 178 | let node = graph.add_float(x.tan()); 179 | created_nodes.push(node); 180 | new_node = Some(node); 181 | parents.push(op.parents[0]); 182 | }, 183 | Type::Integer(x) => { 184 | let node = graph.add_float((x as f64).tan()); 185 | created_nodes.push(node); 186 | new_node = Some(node); 187 | parents.push(op.parents[0]); 188 | }, 189 | _ => () 190 | } 191 | }, 192 | OPERATOR_COSH => { 193 | match try!(graph.get_node(op.parents[0])).node_type { 194 | Type::Float(x) => { 195 | let node = graph.add_float(x.cosh()); 196 | created_nodes.push(node); 197 | new_node = Some(node); 198 | parents.push(op.parents[0]); 199 | }, 200 | Type::Integer(x) => { 201 | let node = graph.add_float((x as f64).cosh()); 202 | created_nodes.push(node); 203 | new_node = Some(node); 204 | parents.push(op.parents[0]); 205 | }, 206 | _ => () 207 | } 208 | }, 209 | OPERATOR_SINH => { 210 | match try!(graph.get_node(op.parents[0])).node_type { 211 | Type::Float(x) => { 212 | let node = graph.add_float(x.sinh()); 213 | created_nodes.push(node); 214 | new_node = Some(node); 215 | parents.push(op.parents[0]); 216 | }, 217 | Type::Integer(x) => { 218 | let node = graph.add_float((x as f64).sinh()); 219 | created_nodes.push(node); 220 | new_node = Some(node); 221 | parents.push(op.parents[0]); 222 | }, 223 | _ => () 224 | } 225 | }, 226 | OPERATOR_TANH => { 227 | match try!(graph.get_node(op.parents[0])).node_type { 228 | Type::Float(x) => { 229 | let node = graph.add_float(x.tanh()); 230 | created_nodes.push(node); 231 | new_node = Some(node); 232 | parents.push(op.parents[0]); 233 | }, 234 | Type::Integer(x) => { 235 | let node = graph.add_float((x as f64).tanh()); 236 | created_nodes.push(node); 237 | new_node = Some(node); 238 | parents.push(op.parents[0]); 239 | }, 240 | _ => () 241 | } 242 | }, 243 | OPERATOR_ABS | OPERATOR_L1_ALL | OPERATOR_L1_1 | OPERATOR_L1_2 => { 244 | match try!(graph.get_node(op.parents[0])).node_type { 245 | Type::Float(x) => { 246 | if x > 0.0{ 247 | new_node = Some(op.parents[0]); 248 | parents.push(op.parents[0]); 249 | } else { 250 | let node = graph.add_float(-x); 251 | created_nodes.push(node); 252 | new_node = Some(node); 253 | parents.push(op.parents[0]); 254 | } 255 | }, 256 | Type::Integer(x) => { 257 | if x > 0{ 258 | new_node = Some(op.parents[0]); 259 | parents.push(op.parents[0]); 260 | } else { 261 | let node = graph.add_int(-x); 262 | created_nodes.push(node); 263 | new_node = Some(node); 264 | parents.push(op.parents[0]); 265 | } 266 | }, 267 | _ => () 268 | } 269 | }, 270 | OPERATOR_L2_ALL | OPERATOR_L2_1 | OPERATOR_L2_2 => { 271 | match try!(graph.get_node(op.parents[0])).node_type { 272 | Type::Float(x) => { 273 | let node = graph.add_float(x*x); 274 | created_nodes.push(node); 275 | new_node = Some(node); 276 | parents.push(op.parents[0]); 277 | }, 278 | Type::Integer(x) => { 279 | let node = graph.add_int(x*x); 280 | created_nodes.push(node); 281 | new_node = Some(node); 282 | parents.push(op.parents[0]); 283 | }, 284 | _ => () 285 | } 286 | }, 287 | OPERATOR_LOG => { 288 | match try!(graph.get_node(op.parents[0])).node_type { 289 | Type::Float(x) => { 290 | let node = graph.add_float(x.ln()); 291 | created_nodes.push(node); 292 | new_node = Some(node); 293 | parents.push(op.parents[0]); 294 | }, 295 | Type::Integer(x) => { 296 | let node = graph.add_float((x as f64).ln()); 297 | created_nodes.push(node); 298 | new_node = Some(node); 299 | parents.push(op.parents[0]); 300 | }, 301 | _ => () 302 | } 303 | }, 304 | OPERATOR_EXP => { 305 | match try!(graph.get_node(op.parents[0])).node_type { 306 | Type::Float(x) => { 307 | let node = graph.add_float(x.exp()); 308 | created_nodes.push(node); 309 | new_node = Some(node); 310 | parents.push(op.parents[0]); 311 | }, 312 | Type::Integer(x) => { 313 | let node = graph.add_float((x as f64).exp()); 314 | created_nodes.push(node); 315 | new_node = Some(node); 316 | parents.push(op.parents[0]); 317 | }, 318 | _ => () 319 | } 320 | }, 321 | OPERATOR_SQRT => { 322 | match try!(graph.get_node(op.parents[0])).node_type { 323 | Type::Float(x) => { 324 | let node = graph.add_float(x.sqrt()); 325 | created_nodes.push(node); 326 | new_node = Some(node); 327 | parents.push(op.parents[0]); 328 | }, 329 | Type::Integer(x) => { 330 | let node = graph.add_float((x as f64).sqrt()); 331 | created_nodes.push(node); 332 | new_node = Some(node); 333 | parents.push(op.parents[0]); 334 | }, 335 | _ => () 336 | } 337 | }, 338 | OPERATOR_SQUARE => { 339 | match try!(graph.get_node(op.parents[0])).node_type { 340 | Type::Float(x) => { 341 | let node = graph.add_float(x*x); 342 | created_nodes.push(node); 343 | new_node = Some(node); 344 | parents.push(op.parents[0]); 345 | }, 346 | Type::Integer(x) => { 347 | let node = graph.add_int(x*x); 348 | created_nodes.push(node); 349 | new_node = Some(node); 350 | parents.push(op.parents[0]); 351 | }, 352 | _ => () 353 | } 354 | }, 355 | OPERATOR_SIGM => { 356 | match try!(graph.get_node(op.parents[0])).node_type { 357 | Type::Float(x) => { 358 | let node = graph.add_float(1.0 / (1.0 + (-x).exp())); 359 | created_nodes.push(node); 360 | new_node = Some(node); 361 | parents.push(op.parents[0]); 362 | }, 363 | Type::Integer(x) => { 364 | let node = graph.add_float(1.0 / (1.0 + (-x as f64).exp())); 365 | created_nodes.push(node); 366 | new_node = Some(node); 367 | parents.push(op.parents[0]); 368 | }, 369 | _ => () 370 | } 371 | }, 372 | OPERATOR_LT => { 373 | let (_, values) = try!(extract_values(graph, &op.parents)); 374 | match values.len() { 375 | 0...1 => (), 376 | 2 => { 377 | let val = if values[0] < values[1] {1} else {0}; 378 | let node = graph.add_int(val); 379 | created_nodes.push(node); 380 | new_node = Some(node); 381 | parents.extend(op.parents.iter()); 382 | }, 383 | _ => unreachable!() 384 | } 385 | }, 386 | OPERATOR_LTE => { 387 | let (_, values) = try!(extract_values(graph, &op.parents)); 388 | match values.len() { 389 | 0...1 => (), 390 | 2 => { 391 | let val = if values[0] <= values[1] {1} else {0}; 392 | let node = graph.add_int(val); 393 | created_nodes.push(node); 394 | new_node = Some(node); 395 | parents.extend(op.parents.iter()); 396 | }, 397 | _ => unreachable!() 398 | } 399 | }, 400 | OPERATOR_GT => { 401 | let (_, values) = try!(extract_values(graph, &op.parents)); 402 | match values.len() { 403 | 0...1 => (), 404 | 2 => { 405 | let val = if values[0] > values[1] {1} else {0}; 406 | let node = graph.add_int(val); 407 | created_nodes.push(node); 408 | new_node = Some(node); 409 | parents.extend(op.parents.iter()); 410 | }, 411 | _ => unreachable!() 412 | } 413 | }, 414 | OPERATOR_GTE => { 415 | let (_, values) = try!(extract_values(graph, &op.parents)); 416 | match values.len() { 417 | 0...1 => (), 418 | 2 => { 419 | let val = if values[0] >= values[1] {1} else {0}; 420 | let node = graph.add_int(val); 421 | created_nodes.push(node); 422 | new_node = Some(node); 423 | parents.extend(op.parents.iter()); 424 | }, 425 | _ => unreachable!() 426 | } 427 | }, 428 | OPERATOR_MAX => { 429 | let (_, values) = try!(extract_values(graph, &op.parents)); 430 | match values.len() { 431 | 0...1 => (), 432 | 2 => { 433 | let val = if values[0] > values[1] {values[0]} else {values[1]}; 434 | let node = if val.floor() == val { 435 | graph.add_int(val as i64) 436 | } else { 437 | graph.add_float(val) 438 | }; 439 | created_nodes.push(node); 440 | new_node = Some(node); 441 | parents.extend(op.parents.iter()); 442 | }, 443 | _ => unreachable!() 444 | } 445 | }, 446 | OPERATOR_MIN => { 447 | let (_, values) = try!(extract_values(graph, &op.parents)); 448 | match values.len() { 449 | 0...1 => (), 450 | 2 => { 451 | let val = if values[0] < values[1] {values[0]} else {values[1]}; 452 | let node = if val.floor() == val { 453 | graph.add_int(val as i64) 454 | } else { 455 | graph.add_float(val) 456 | }; 457 | created_nodes.push(node); 458 | new_node = Some(node); 459 | parents.extend(op.parents.iter()); 460 | }, 461 | _ => unreachable!() 462 | } 463 | }, 464 | OPERATOR_POW => { 465 | let (indexes, values) = try!(extract_values(graph, &op.parents)); 466 | match values.len() { 467 | 0 => (), 468 | 1 => { 469 | match indexes[0] { 470 | 0 => match values[0] { 471 | 0.0 => { 472 | let node = graph.add_int(0); 473 | created_nodes.push(node); 474 | new_node = Some(node); 475 | parents.extend(op.parents.iter()); 476 | }, 477 | 1.0 => { 478 | let node = graph.add_int(1); 479 | created_nodes.push(node); 480 | new_node = Some(node); 481 | parents.extend(op.parents.iter()); 482 | }, 483 | _ => () 484 | }, 485 | 1 => match values[0]{ 486 | 0.0 => { 487 | let node = graph.add_int(1); 488 | created_nodes.push(node); 489 | new_node = Some(node); 490 | parents.extend(op.parents.iter()); 491 | }, 492 | 1.0 => { 493 | new_node = Some(op.parents[0]); 494 | parents.extend(op.parents.iter()); 495 | }, 496 | 2.0 => { 497 | let node = try!(graph.add_operation( 498 | OperatorType::Unary(UnaryOperatorType::Square), vec![op.parents[0]])); 499 | created_nodes.push(node); 500 | new_node = Some(node); 501 | parents.extend(op.parents.iter()); 502 | }, 503 | _ => () 504 | }, 505 | _ => unreachable!() 506 | } 507 | }, 508 | 2 => { 509 | let val = values[0].powf(values[1]); 510 | let node = if val.floor() == val { 511 | graph.add_int(val as i64) 512 | } else { 513 | graph.add_float(val) 514 | }; 515 | created_nodes.push(node); 516 | new_node = Some(node); 517 | parents.extend(op.parents.iter()); 518 | }, 519 | _ => unreachable!() 520 | } 521 | }, 522 | OPERATOR_QUAD => { 523 | let po = try!(graph.get_node(op.parents[0])).op.clone(); 524 | // Check first operand for Zeros and Eye 525 | match po.op_type { 526 | OperatorType::Constant(ConstantOperatorType::Binary(ConstantBinaryOperatorType::Zeros)) => { 527 | let node = graph.add_int(0); 528 | created_nodes.push(node); 529 | new_node = Some(node); 530 | parents.extend(op.parents.iter()); 531 | }, 532 | OperatorType::Constant(ConstantOperatorType::Unary(ConstantUnaryOperatorType::Eye)) => { 533 | new_node = Some(op.parents[1]); 534 | parents.extend(op.parents.iter()); 535 | }, 536 | _ => () 537 | } 538 | if new_node == None { 539 | // Check second operand for Zeros and Eye 540 | let po = try!(graph.get_node(op.parents[1])).op.clone(); 541 | match po.op_type { 542 | OperatorType::Constant(ConstantOperatorType::Binary(ConstantBinaryOperatorType::Zeros)) => { 543 | let node = graph.add_int(0); 544 | created_nodes.push(node); 545 | new_node = Some(node); 546 | parents.extend(op.parents.iter()); 547 | }, 548 | OperatorType::Constant(ConstantOperatorType::Unary(ConstantUnaryOperatorType::Eye)) => { 549 | let node = try!(graph.add_operation( 550 | OperatorType::Nary(NaryOperatorType::Dot), vec![op.parents[0], op.parents[0]])); 551 | created_nodes.push(node); 552 | new_node = Some(node); 553 | parents.extend(op.parents.iter()); 554 | }, 555 | _ => () 556 | } 557 | } 558 | if new_node == None{ 559 | let (_, values) = try!(extract_values(graph, &op.parents)); 560 | match values.len() { 561 | 0...1 => (), 562 | 2 => { 563 | let val = if values[0] < values[1] {values[0]} else {values[1]}; 564 | let node = if val.floor() == val { 565 | graph.add_int(val as i64) 566 | } else { 567 | graph.add_float(val) 568 | }; 569 | created_nodes.push(node); 570 | new_node = Some(node); 571 | parents.extend(op.parents.iter()); 572 | }, 573 | _ => unreachable!() 574 | } 575 | } 576 | }, 577 | OPERATOR_REPLICATEH | OPERATOR_REPLICATEV => { 578 | match try!(graph.get_node(op.args[0])).node_type { 579 | Type::Integer(x) => match x{ 580 | 0 => { 581 | // TODO 582 | // return Err(OperatorError::Invalid 583 | // ::std::convert::From::from( 584 | // InvalidOperatorError::new(op.op_type, 1, 1, 0, 0))), 585 | }, 586 | 1 => { 587 | new_node = Some(op.parents[0]); 588 | parents.push(op.parents[0]); 589 | parents.push(op.args[0]); 590 | }, 591 | _ => () 592 | }, 593 | _ => () 594 | } 595 | }, 596 | _ => () 597 | } 598 | match new_node{ 599 | Some(node) => { 600 | // Swap connection of the children to point to the new node 601 | try!(graph.swap_child_connections(old, node)); 602 | // Delete the node from the parent's children 603 | for i in parents { 604 | let children : &mut Vec = &mut try!(graph.get_mut_node(i)).children; 605 | children.iter().position(|&x| x == old).map(|x| children.remove(x)); 606 | } 607 | // Remove node from the graph 608 | graph.insert_node(old, None); 609 | graph.outputs.iter().position(|&x| x == old).map(|x| {graph.outputs.push(node); graph.outputs.swap_remove(x);}); 610 | // Remove node from the ordering and put all created nodes 611 | let order:usize = graph.ordering.iter().position(|&x| x == old).unwrap(); 612 | println!("Ordering: {:?}",graph.ordering); 613 | println!("Removing {} from position {}",old,order); 614 | let _ = graph.ordering.remove(order); 615 | for _ in created_nodes.iter(){ 616 | let i = graph.ordering.pop().unwrap(); 617 | graph.ordering.insert(order, i); 618 | } 619 | Ok(true) 620 | }, 621 | None => Ok(false) 622 | } 623 | } 624 | 625 | fn extract_values(graph: &mut ComputeGraph, nodes: &Vec) 626 | -> Result<(Vec, Vec), GraphError> { 627 | let mut values : Vec = Vec::new(); 628 | let mut indexes : Vec = Vec::new(); 629 | for (index, node) in nodes.iter().enumerate(){ 630 | match try!(graph.get_node(*node)).node_type{ 631 | Type::Float(x) => { 632 | values.push(x); 633 | indexes.push(index); 634 | }, 635 | Type::Integer(x) => { 636 | indexes.push(index); 637 | values.push(x as f64); 638 | }, 639 | _ => () 640 | } 641 | } 642 | Ok((indexes, values)) 643 | } 644 | -------------------------------------------------------------------------------- /src/optimization/mod.rs: -------------------------------------------------------------------------------- 1 | mod constant_folding; 2 | pub use self::constant_folding::constant_folding; 3 | -------------------------------------------------------------------------------- /tests/codegen/mod.rs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/botev/meta_diff/2499d7c5885f98324c3f8afe5cdede8c9b624104/tests/codegen/mod.rs -------------------------------------------------------------------------------- /tests/core/gradient.rs: -------------------------------------------------------------------------------- 1 | extern crate meta_diff; 2 | 3 | fn grad_ok(nodes_before: usize, nodes_after: usize, source: &str){ 4 | let result = meta_diff::core::parseMetaFile(source); 5 | let mut graph = match result { 6 | Ok(g) => g, 7 | Err(msg) => {return assert!(false, "{}", msg);} 8 | }; 9 | assert!(graph.len() == nodes_before, "Number of the initial graph nodes expected: {}, was: {}", nodes_before, graph.len()); 10 | 11 | match graph.direct_gradient(){ 12 | Ok(_) => { 13 | if graph.len() == nodes_after { 14 | assert!(true); 15 | } else { 16 | match meta_diff::codegen::write_graphviz(&mut ::std::io::stdout() , &graph){ 17 | Ok(_) => (), 18 | Err(msg) => assert!(false, "{}", msg) 19 | } 20 | println!("{}",graph); 21 | assert!(false, "Number of the nodes after gradient - expected: {}, was: {}", nodes_after, graph.len()); 22 | } 23 | }, 24 | Err(msg) => assert!(false, "{}", msg) 25 | } 26 | } 27 | 28 | // fn grad_fail(fail_msg: &str, source: &str){ 29 | // let result = meta_diff::core::parseMetaFile(source); 30 | // match result { 31 | // Ok(_) => { 32 | // assert!(false, "Fail parsed, but should have failed."); 33 | // } 34 | // Err(msg) => { 35 | // assert!(format!("{}",msg) == fail_msg,format!("Parser failed message expected: {}, was: {}", fail_msg, msg)); 36 | // } 37 | // } 38 | // } 39 | 40 | parametarise_test!(grad_ok,{ 41 | 8,8, 42 | "function [d] = mat(a,b) 43 | c = a + b * a'; 44 | d = l2(c,0) * l1(c,0); 45 | end" 46 | },{ 47 | 14,37, 48 | "function [L] = mat(@w,x,y) 49 | h = tanh(w*vertcat(x,1)); 50 | h = tanh(w*vertcat(h,1)); 51 | L = l2(h-y,0); 52 | end" 53 | },{ 54 | 14,23, 55 | "function [L] = mat(@w,x,y) 56 | h = tanh(w*vertcat(x,1)); 57 | s = sinh(w*horzcat(h,1)); 58 | L = l1(h-y,0); 59 | end" 60 | },{ 61 | 10,18, 62 | "function [L] = mat(@w,x,y,@z) 63 | h = w + x dot y * z; 64 | L = sum(h^2,0); 65 | end" 66 | },{ 67 | 14,19, 68 | "function [L] = mat(@w,x,y) 69 | h = const(w*vertcat(x,1)); 70 | s = vdiag(w*horzcat(h,1)); 71 | L = l1(s-h,0); 72 | end" 73 | }); 74 | 75 | // parametarise_test!(grad_fail, 76 | // ["Error at 2:7: Use of undefined variable \'d\'", 77 | // "function [d] = mat(a,b) 78 | // c = d + b * a'; 79 | // d = l2(c,0) * l1(c,0); 80 | // end" ], 81 | // ["Error at 3:28: Can not have a variable with name \'sin\' since it is a built in function", 82 | // "function [L] = mat(@w,x,y) 83 | // h = tanh(w*vertcat(x,1)); 84 | // sin = tanh(w*vertcat(h,1)); 85 | // L = l2(h-y,0); 86 | // end"], 87 | // ["Error at 4:13: Comparison operators not supported!", 88 | // "function [L] = mat(@w,x,y) 89 | // h = tanh(w*vertcat(x,1)); 90 | // s = sinh(w*horzcat(h,1)); 91 | // L = l1(h>=y,0); 92 | // end"], 93 | // ["Error at 4:5: Output variable \'k\' has not been defined", 94 | // "function [L,k] = mat(@w,x,y,@z) 95 | // h = w + x dot y * z; 96 | // L = sum(h^2,0); 97 | // end"], 98 | // ["Error at 2:29: HorzCat takes at least two arguments", 99 | // "function [L] = mat(@w,x,y) 100 | // h = horzcat(w*-vertcat(x,1)); 101 | // s = diagV(w*horzcat(h,1)); 102 | // L = l1(s-h,0); 103 | // end"] 104 | // ); 105 | -------------------------------------------------------------------------------- /tests/core/mod.rs: -------------------------------------------------------------------------------- 1 | mod parser; 2 | mod gradient; 3 | -------------------------------------------------------------------------------- /tests/core/parser.rs: -------------------------------------------------------------------------------- 1 | extern crate meta_diff; 2 | 3 | fn parse_ok(nodes: usize, source: &str){ 4 | let result = meta_diff::core::parseMetaFile(source); 5 | match result { 6 | Ok(graph) => { 7 | if graph.len() == nodes { 8 | assert!(true); 9 | } else { 10 | match meta_diff::codegen::write_graphviz(&mut ::std::io::stdout() , &graph){ 11 | Ok(_) => (), 12 | Err(msg) => assert!(false, "{}", msg) 13 | } 14 | println!("{}",graph); 15 | assert!(false, "Number of nodes expected: {}, was: {}", nodes, graph.nodes.len()); 16 | } 17 | } 18 | Err(msg) => { 19 | assert!(false, "{}", msg); 20 | } 21 | } 22 | } 23 | 24 | fn parse_fail(fail_msg: &str, source: &str){ 25 | let result = meta_diff::core::parseMetaFile(source); 26 | match result { 27 | Ok(_) => { 28 | assert!(false, "Fail parsed, but should have failed."); 29 | } 30 | Err(msg) => { 31 | assert!(format!("{}",msg) == fail_msg,format!("Parser failed message expected: {}, was: {}", fail_msg, msg)); 32 | } 33 | } 34 | } 35 | 36 | parametarise_test!(parse_ok,{ 37 | 8, 38 | "function [d] = mat(a,b) 39 | c = a + b * a'; 40 | d = l2(c,0) * l1(c,0); 41 | end" 42 | },{ 43 | 14, 44 | "function [L] = mat(@w,x,y) 45 | h = tanh(w*vertcat(x,1)); 46 | h = tanh(w*vertcat(h,1)); 47 | L = l2(h-y,0); 48 | end" 49 | },{ 50 | 14, 51 | "function [L] = mat(@w,x,y) 52 | h = tanh(w*vertcat(x,1)); 53 | s = sinh(w*horzcat(h,1)); 54 | L = l1(h-y,0); 55 | end" 56 | },{ 57 | 10, 58 | "function [L] = mat(@w,x,y,@z) 59 | h = w + x dot y * z; 60 | L = sum(h^2,0); 61 | end" 62 | },{ 63 | 15, 64 | "function [L] = mat(@w,x,y) 65 | h = const(w*-vertcat(x,1)); 66 | s = vdiag(w*horzcat(h,1)); 67 | L = l1(s-h,0); 68 | end" 69 | }); 70 | 71 | parametarise_test!(parse_fail,{ 72 | "Error at 2:7: Use of undefined variable \'d\'", 73 | "function [d] = mat(a,b) 74 | c = d + b * a'; 75 | d = l2(c,0) * l1(c,0); 76 | end" 77 | },{ 78 | "Error at 3:28: Can not have a variable with name \'sin\' since it is a built in function", 79 | "function [L] = mat(@w,x,y) 80 | h = tanh(w*vertcat(x,1)); 81 | sin = tanh(w*vertcat(h,1)); 82 | L = l2(h-y,0); 83 | end" 84 | },{ 85 | "Error at 4:14: OperatorError: Can not create an operator L1 with dimension 3, when [0, 1, 2] are possible", 86 | "function [L] = mat(@w,x,y) 87 | h = tanh(w*vertcat(x,1)); 88 | s = sinh(w*horzcat(h,1)); 89 | L = l1(h>y,3); 90 | end" 91 | },{ 92 | "Error at 4:5: Output variable \'k\' has not been defined", 93 | "function [L,k] = mat(@w,x,y,@z) 94 | h = w + x dot y * z; 95 | L = sum(h^2,0); 96 | end" 97 | },{ 98 | "Error at 2:29: OperatorError: Can not create an operator HorzCat with 1 parents, when 2 are required", 99 | "function [L] = mat(@w,x,y) 100 | h = horzcat(w*-vertcat(x,1)); 101 | s = diagV(w*horzcat(h,1)); 102 | L = l1(s-h,0); 103 | end" 104 | }); 105 | -------------------------------------------------------------------------------- /tests/linking/linking_rust.rs: -------------------------------------------------------------------------------- 1 | extern crate meta_diff; 2 | extern crate tempdir; 3 | 4 | use self::meta_diff::linking::*; 5 | 6 | pub fn dynamic_linking_ok(args: Vec, out: Vec,source: &str) { 7 | let file_name = "test_dl"; 8 | let func_name = "test"; 9 | let mut location = tempdir::TempDir::new("rust_test").unwrap().into_path(); 10 | let dl_func: DLFunction = dynamical_linking_rust( 11 | source, file_name, &mut location, func_name).unwrap(); 12 | 13 | for (i,arg) in args.iter().enumerate(){ 14 | let res = dl_func.eval(*arg); 15 | if out[i].is_nan(){ 16 | assert!(res.is_nan(), 17 | format!("Incorrect result for argument {}, expected {}, was {} ",arg, out[i], res)) 18 | } else { 19 | let diff = (res - out[i]).abs(); 20 | assert!(diff < 1e-15, 21 | format!("Incorrect result for argument {}, expected {}, was {} ",arg, out[i], res)) 22 | } 23 | } 24 | } 25 | 26 | pub fn dynamic_linking_fail(error: &DynamicLinkingError, source: &str) { 27 | let file_name = "test_dl"; 28 | let func_name = "test"; 29 | let mut location = tempdir::TempDir::new("rust_test").unwrap().into_path(); 30 | let res : Result, DynamicLinkingError> = dynamical_linking_rust( 31 | source, file_name, &mut location, func_name); 32 | match res { 33 | Ok(_) => assert!(false, "Dynamic linking should have failed, but didn't"), 34 | Err(err) => { 35 | match err { 36 | DynamicLinkingError::Io(_) => match *error { 37 | DynamicLinkingError::Io(_) => assert!(true), 38 | _=> assert!(false, "Incorrect error, expected: {}, was {}|", *error, err) 39 | }, 40 | DynamicLinkingError::Compilation(ref s1) => match *error { 41 | DynamicLinkingError::Compilation(ref s2) => assert!(s1.contains(s2), "Incorrect error, expected: {}, was {}|", error, err), 42 | _=> assert!(false, "Incorrect error, expected: {}, was {}|", *error, err) 43 | }, 44 | DynamicLinkingError::OpenLibrary(ref s1) => match *error { 45 | DynamicLinkingError::OpenLibrary(ref s2) => assert!(s1.contains(s2), "Incorrect error, expected: {}, was {}|", error, err), 46 | _=> assert!(false, "Incorrect error, expected: {}, was {}|", *error, err) 47 | }, 48 | DynamicLinkingError::SymbolTable(ref s1) => match *error { 49 | DynamicLinkingError::SymbolTable(ref s2) => assert!(s1.contains(s2), "Incorrect error, expected: {}, was {}|", error, err), 50 | _=> assert!(false, "Incorrect error, expected: {}, was {}|", *error, err) 51 | }, 52 | } 53 | 54 | } 55 | } 56 | } 57 | 58 | parametarise_test!(dynamic_linking_ok,{ 59 | vec![-1.0,-0.75,-0.5,-0.25,0.0,0.25,0.5,0.75,1.0], 60 | vec![0.26894142136999510395, 0.32082130082460702525, 0.37754066879814540680, 0.43782349911420193056, 0.50000000000000000000, 0.56217650088579806944, 0.62245933120185459320, 0.67917869917539297475, 0.73105857863000489605], 61 | "// test_dl.rs 62 | #[no_mangle] 63 | pub fn test(x: f64) -> f64 { 64 | 1.0 / (1.0 + (-x).exp()) 65 | } " 66 | },{ 67 | vec![-1.0,-0.75,-0.5,-0.25,0.0,0.25,0.5,0.75,1.0], 68 | vec![-1.10908117742402323458, -0.86005775604188627881, -0.58780478976890193632, -0.29844720425183085544, 0.00000000000000000000, 0.29844720425183085544, 0.58780478976890193632, 0.86005775604188627881, 1.10908117742402323458], 69 | "// test_dl.rs 70 | #[no_mangle] 71 | pub fn test(x: f64) -> f64 { 72 | 2.4 * (x/2.0).tanh() 73 | } " 74 | },{ 75 | vec![-1.0,-0.75,-0.5,-0.25,0.0,0.25,0.5,0.75,1.0], 76 | vec![4.73515900796232269698, 4.87731706945529364106, 5.04531083492266496648, 5.24142471325712833163, 5.46731322773325167930, 5.72381678975859031766, 6.01085793007176949487, 6.32744388086401787774, 6.67177643695004984892], 77 | "// test_dl.rs 78 | #[no_mangle] 79 | pub fn test(x: f64) -> f64 { 80 | let y = (x+2.0).exp() + 8.0; 81 | (y*y + x).ln() 82 | } " 83 | },{ 84 | vec![-1.0,-0.75,-0.5,-0.25,0.0,0.25,0.5,0.75,1.0], 85 | vec![::std::f64::NAN, 0.15674646902621844347, 0.55585313969623040276, 0.81252007721352959013, 1.00000000000000000000, 1.12063988508324130500, 1.17255289492536807217, 1.15542379613608758859, 1.07267867039314279687], 86 | "// test_dl.rs 87 | #[no_mangle] 88 | pub fn test(x: f64) -> f64 { 89 | let y = (x+2.0).sin() + 1.0; 90 | let z = y.abs().ln(); 91 | (x*y*z + 1.0).sqrt() 92 | } " 93 | },{ 94 | vec![2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0], 95 | vec![9.0, 25.0, 64.0, 169.0, 441.0, 1156.0, 3025.0, 7921.0, 20736.0, 54289.0], 96 | "// test_dl.rs 97 | #[no_mangle] 98 | pub fn test(x: f64) -> f64 { 99 | let mut x_0 = 1.0; 100 | let mut x_1 = 1.0; 101 | let n = x.round() as i64; 102 | for _ in 0..n { 103 | let x_n = x_0 + x_1; 104 | x_0 = x_1; 105 | x_1 = x_n; 106 | } 107 | x_1*x_1 108 | } " 109 | }); 110 | 111 | parametarise_test!(dynamic_linking_fail,{ 112 | &meta_diff::linking::DynamicLinkingError::Compilation("`core::ops::Div` is not implemented for the type `_`".to_string()), 113 | "// test_dl.rs 114 | #[no_mangle] 115 | pub fn test(x: f64) -> f64 { 116 | 1 / (1.0 + (-x).exp()) 117 | } " 118 | },{ 119 | &meta_diff::linking::DynamicLinkingError::Compilation("re-assignment of immutable variable `a`".to_string()), 120 | "// test_dl.rs 121 | #[no_mangle] 122 | pub fn test(x: f64) -> f64 { 123 | let a = 1.0 / (1.0 + (-x).exp()); 124 | a = x + a*a; 125 | a 126 | } " 127 | },{ 128 | &meta_diff::linking::DynamicLinkingError::Compilation("re-assignment of immutable variable `a`".to_string()), 129 | "// test_dl.rs 130 | #[no_mangle] 131 | pub fn test12(x: f64) -> f64 { 132 | let a = 1.0 / (1.0 + (-x).exp()); 133 | a = x + a*a; 134 | a 135 | } " 136 | },{ 137 | &meta_diff::linking::DynamicLinkingError::SymbolTable("undefined symbol: test".to_string()), 138 | "// test_dl.rs 139 | #[no_mangle] 140 | pub fn test12(x: f64) -> f64 { 141 | 1.0 / (1.0 + (-x).exp()) 142 | } " 143 | },{ 144 | &meta_diff::linking::DynamicLinkingError::SymbolTable("undefined symbol: test".to_string()), 145 | "// test_dl.rs 146 | #[no_mangle] 147 | pub fn test23(x: f64) -> f64 { 148 | let mut a = 1.0 / (1.0 + (-x).exp()); 149 | a = x + a*a; 150 | a 151 | } " 152 | }); 153 | -------------------------------------------------------------------------------- /tests/linking/mod.rs: -------------------------------------------------------------------------------- 1 | mod linking_rust; 2 | -------------------------------------------------------------------------------- /tests/macros.rs: -------------------------------------------------------------------------------- 1 | #[macro_export] 2 | macro_rules! parametarise_test { 3 | ($func: ident, {$($args0: expr),*}) => { 4 | mod $func{ 5 | extern crate meta_diff; 6 | #[test] 7 | fn test_0 (){super::$func($($args0),*);} 8 | } 9 | }; 10 | ($func: ident, {$($args0: expr),*}, {$($args1: expr),*}) => { 11 | mod $func{ 12 | extern crate meta_diff; 13 | #[test] 14 | fn test_0 (){super::$func($($args0),*);} 15 | #[test] 16 | fn test_1 (){super::$func($($args1),*);} 17 | } 18 | }; 19 | ($func: ident, {$($args0: expr),*}, {$($args1: expr),*}, {$($args2: expr),*}) => { 20 | mod $func{ 21 | extern crate meta_diff; 22 | #[test] 23 | fn test_0 (){super::$func($($args0),*);} 24 | #[test] 25 | fn test_1 (){super::$func($($args1),*);} 26 | #[test] 27 | fn test_2 (){super::$func($($args2),*);} 28 | } 29 | }; 30 | ($func: ident, {$($args0: expr),*}, {$($args1: expr),*}, {$($args2: expr),*}, {$($args3: expr),*}) => { 31 | extern crate meta_diff; 32 | mod $func{ 33 | #[test] 34 | fn test_0 (){super::$func($($args0),*);} 35 | #[test] 36 | fn test_1 (){super::$func($($args1),*);} 37 | #[test] 38 | fn test_2 (){super::$func($($args2),*);} 39 | #[test] 40 | fn test_3 (){super::$func($($args3),*);} 41 | } 42 | }; 43 | ($func: ident, {$($args0: expr),*}, {$($args1: expr),*}, {$($args2: expr),*}, {$($args3: expr),*}, {$($args4: expr),*}) => { 44 | mod $func{ 45 | extern crate meta_diff; 46 | #[test] 47 | fn test_0 (){super::$func($($args0),*);} 48 | #[test] 49 | fn test_1 (){super::$func($($args1),*);} 50 | #[test] 51 | fn test_2 (){super::$func($($args2),*);} 52 | #[test] 53 | fn test_3 (){super::$func($($args3),*);} 54 | #[test] 55 | fn test_4 (){super::$func($($args4),*);} 56 | } 57 | }; 58 | ($func: ident, {$($args0: expr),*}, {$($args1: expr),*}, {$($args2: expr),*}, {$($args3: expr),*}, {$($args4: expr),*}, {$($args5: expr),*}) => { 59 | mod $func{ 60 | extern crate meta_diff; 61 | #[test] 62 | fn test_0 (){super::$func($($args0),*);} 63 | #[test] 64 | fn test_1 (){super::$func($($args1),*);} 65 | #[test] 66 | fn test_2 (){super::$func($($args2),*);} 67 | #[test] 68 | fn test_3 (){super::$func($($args3),*);} 69 | #[test] 70 | fn test_4 (){super::$func($($args4),*);} 71 | #[test] 72 | fn test_5 (){super::$func($($args5),*);} 73 | } 74 | }; 75 | ($func: ident, {$($args0: expr),*}, {$($args1: expr),*}, {$($args2: expr),*}, {$($args3: expr),*}, {$($args4: expr),*}, {$($args5: expr),*}, 76 | {$($args6: expr),*}) => { 77 | mod $func{ 78 | extern crate meta_diff; 79 | #[test] 80 | fn test_0 (){super::$func($($args0),*);} 81 | #[test] 82 | fn test_1 (){super::$func($($args1),*);} 83 | #[test] 84 | fn test_2 (){super::$func($($args2),*);} 85 | #[test] 86 | fn test_3 (){super::$func($($args3),*);} 87 | #[test] 88 | fn test_4 (){super::$func($($args4),*);} 89 | #[test] 90 | fn test_5 (){super::$func($($args5),*);} 91 | #[test] 92 | fn test_6 (){super::$func($($args5),*);} 93 | } 94 | }; 95 | ($func: ident, {$($args0: expr),*}, {$($args1: expr),*}, {$($args2: expr),*}, {$($args3: expr),*}, {$($args4: expr),*}, {$($args5: expr),*}, 96 | {$($args6: expr),*}) => { 97 | mod $func{ 98 | extern crate meta_diff; 99 | #[test] 100 | fn test_0 (){super::$func($($args0),*);} 101 | #[test] 102 | fn test_1 (){super::$func($($args1),*);} 103 | #[test] 104 | fn test_2 (){super::$func($($args2),*);} 105 | #[test] 106 | fn test_3 (){super::$func($($args3),*);} 107 | #[test] 108 | fn test_4 (){super::$func($($args4),*);} 109 | #[test] 110 | fn test_5 (){super::$func($($args5),*);} 111 | #[test] 112 | fn test_6 (){super::$func($($args6),*);} 113 | } 114 | }; 115 | ($func: ident, {$($args0: expr),*}, {$($args1: expr),*}, {$($args2: expr),*}, {$($args3: expr),*}, {$($args4: expr),*}, {$($args5: expr),*}, 116 | {$($args6: expr),*}, {$($args7: expr),*}) => { 117 | mod $func{ 118 | extern crate meta_diff; 119 | #[test] 120 | fn test_0 (){super::$func($($args0),*);} 121 | #[test] 122 | fn test_1 (){super::$func($($args1),*);} 123 | #[test] 124 | fn test_2 (){super::$func($($args2),*);} 125 | #[test] 126 | fn test_3 (){super::$func($($args3),*);} 127 | #[test] 128 | fn test_4 (){super::$func($($args4),*);} 129 | #[test] 130 | fn test_5 (){super::$func($($args5),*);} 131 | #[test] 132 | fn test_6 (){super::$func($($args6),*);} 133 | #[test] 134 | fn test_7 (){super::$func($($args7),*);} 135 | } 136 | }; 137 | ($func: ident, {$($args0: expr),*}, {$($args1: expr),*}, {$($args2: expr),*}, {$($args3: expr),*}, {$($args4: expr),*}, {$($args5: expr),*}, 138 | {$($args6: expr),*}, {$($args7: expr),*}, , {$($args8: expr),*}) => { 139 | mod $func{ 140 | extern crate meta_diff; 141 | #[test] 142 | fn test_0 (){super::$func($($args0),*);} 143 | #[test] 144 | fn test_1 (){super::$func($($args1),*);} 145 | #[test] 146 | fn test_2 (){super::$func($($args2),*);} 147 | #[test] 148 | fn test_3 (){super::$func($($args3),*);} 149 | #[test] 150 | fn test_4 (){super::$func($($args4),*);} 151 | #[test] 152 | fn test_5 (){super::$func($($args5),*);} 153 | #[test] 154 | fn test_6 (){super::$func($($args6),*);} 155 | #[test] 156 | fn test_7 (){super::$func($($args7),*);} 157 | #[test] 158 | fn test_8 (){super::$func($($args8),*);} 159 | } 160 | }; 161 | ($func: ident, {$($args0: expr),*}, {$($args1: expr),*}, {$($args2: expr),*}, {$($args3: expr),*}, {$($args4: expr),*}, {$($args5: expr),*}, 162 | {$($args6: expr),*}, {$($args7: expr),*}, , {$($args8: expr),*}, {$($args9: expr),*}) => { 163 | mod $func{ 164 | extern crate meta_diff; 165 | #[test] 166 | fn test_0 (){super::$func($($args0),*);} 167 | #[test] 168 | fn test_1 (){super::$func($($args1),*);} 169 | #[test] 170 | fn test_2 (){super::$func($($args2),*);} 171 | #[test] 172 | fn test_3 (){super::$func($($args3),*);} 173 | #[test] 174 | fn test_4 (){super::$func($($args4),*);} 175 | #[test] 176 | fn test_5 (){super::$func($($args5),*);} 177 | #[test] 178 | fn test_6 (){super::$func($($args6),*);} 179 | #[test] 180 | fn test_7 (){super::$func($($args7),*);} 181 | #[test] 182 | fn test_8 (){super::$func($($args8),*);} 183 | #[test] 184 | fn test_9 (){super::$func($($args9),*);} 185 | } 186 | }; 187 | } 188 | -------------------------------------------------------------------------------- /tests/mod.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | mod macros; 3 | mod core; 4 | mod optimization; 5 | mod linking; 6 | // use tempdir::*; 7 | // use std::process::Command; 8 | // use std::io::Write; 9 | // use std::dynamic_lib::DynamicLibrary; 10 | 11 | // #[test] 12 | // pub fn dynamic_linking_test() { 13 | // let name = "dylib"; 14 | // let source = " 15 | // // dylib.rs 16 | // #[no_mangle] 17 | // pub fn minicall(x: f64) -> f64 { 18 | // 1.0 / (1.0 + (-x).exp()) 19 | // } "; 20 | // 21 | // let dir = std::env::current_dir().unwrap(); 22 | // // TempDir::new("rust_test").unwrap().into_path(); 23 | // let mut source_loc = dir.clone(); 24 | // source_loc.push(&name); 25 | // source_loc.set_extension("rs"); 26 | // let file = std::fs::File::create(source_loc.as_path()).unwrap(); 27 | // { 28 | // let mut writer = std::io::BufWriter::new(&file); 29 | // let _ = writer.write_fmt(format_args!("{}\n",source)).unwrap(); 30 | // } 31 | // let mut target_loc = dir.clone(); 32 | // target_loc.push(&name); 33 | // target_loc.set_extension("so"); 34 | // println!("Generated source"); 35 | // 36 | // let cmd = format!("rustc --crate-type {} {} -o {}" ,name, 37 | // source_loc.into_os_string().to_str().unwrap(), 38 | // target_loc.clone().into_os_string().to_str().unwrap()); 39 | // println!("Calling command: {}", cmd); 40 | // let _ = Command::new("sh") 41 | // .arg("-c") 42 | // .arg(cmd) 43 | // .output() 44 | // .unwrap_or_else(|e| { panic!("failed to execute process: {}", e) }); 45 | // let output = Command::new("sh") 46 | // .arg("-c") 47 | // .arg(format!("ls {}", dir.into_os_string().to_str().unwrap())) 48 | // .output() 49 | // .unwrap_or_else(|e| { panic!("failed to execute process: {}", e) }); 50 | // println!("ls:\n {}",String::from_utf8(output.stdout).unwrap()); 51 | // 52 | // let (lib,func) = match DynamicLibrary::open(Some(target_loc.as_path())){ 53 | // Err(err) => panic!("DL Error: {}", err), 54 | // Ok(lib) => { 55 | // println!("Unsafe block!"); 56 | // let func: fn(f64) -> f64 = unsafe { 57 | // match lib.symbol("minicall") { 58 | // Err(err) => {panic!("ERROR: {}", err);} 59 | // // And then cast that pointer a function 60 | // Ok(f) => {::std::mem::transmute::<*mut f64, fn(f64) -> f64>(f)}, 61 | // } 62 | // }; 63 | // (lib, func) 64 | // // let values = vec![-1.0,-0.75,-0.5,-0.25,0.0,0.25,0.5,0.75,1.0]; 65 | // // for i in values.iter(){ 66 | // // println!("sigm({})={}",i,func(*i)); 67 | // // } 68 | // // (func.clone() 69 | // } 70 | // }; 71 | // let values = vec![-1.0,-0.75,-0.5,-0.25,0.0,0.25,0.5,0.75,1.0]; 72 | // for i in values.iter(){ 73 | // println!("sigm({})={}",i,func(*i)); 74 | // } 75 | // 76 | // assert!(false); 77 | // } 78 | -------------------------------------------------------------------------------- /tests/optimization/constant_folding.rs: -------------------------------------------------------------------------------- 1 | extern crate meta_diff; 2 | 3 | fn constant_folding_some(nodes_before: usize, nodes_after: usize, source: &str){ 4 | let result = meta_diff::core::parseMetaFile(source); 5 | let mut graph = match result { 6 | Ok(g) => g, 7 | Err(msg) => {return assert!(false, "{}", msg);} 8 | }; 9 | assert!(graph.len() == nodes_before, "Number of the initial graph nodes expected: {}, was: {}", nodes_before, graph.len()); 10 | //println!("Initial: {:?}",graph.ordering); 11 | match meta_diff::optimization::constant_folding(&mut graph) { 12 | Ok(b) => { 13 | assert!(b, "Did not return true for folding"); 14 | if graph.len() == nodes_after { 15 | assert!(true); 16 | } else { 17 | match meta_diff::codegen::write_graphviz(&mut ::std::io::stdout() , &graph){ 18 | Ok(_) => (), 19 | Err(msg) => assert!(false, "{}", msg) 20 | } 21 | //println!("{:?}",graph.ordering); 22 | println!("{}",graph); 23 | assert!(false, "Number of the optimized graph nodes expected: {}, was: {}", nodes_after, graph.len()); 24 | } 25 | }, 26 | Err(msg) => assert!(false, "{}", msg) 27 | } 28 | } 29 | 30 | fn constant_folding_none(nodes: usize, source: &str){ 31 | let result = meta_diff::core::parseMetaFile(source); 32 | let mut graph = match result { 33 | Ok(g) => g, 34 | Err(msg) => {return assert!(false, "{}", msg);} 35 | }; 36 | assert!(graph.len() == nodes, "Number of the initial graph nodes expected: {}, was: {}", nodes, graph.len()); 37 | 38 | match meta_diff::optimization::constant_folding(&mut graph) { 39 | Ok(b) => { 40 | assert!(!b, "Did not return true for folding"); 41 | if graph.len() == nodes { 42 | assert!(true); 43 | } else { 44 | match meta_diff::codegen::write_graphviz(&mut ::std::io::stdout() , &graph){ 45 | Ok(_) => (), 46 | Err(msg) => assert!(false, "{}", msg) 47 | } 48 | println!("{}",graph); 49 | assert!(false, "Number of the optimized graph nodes expected: {}, was: {}", nodes, graph.len()); 50 | } 51 | }, 52 | Err(msg) => assert!(false, "{}", msg) 53 | } 54 | } 55 | 56 | parametarise_test!(constant_folding_some,{ 57 | 11, 10, 58 | "function [d] = mat(a,b) 59 | c = 1 + 2 * 3'; 60 | d = l2(c,0) * l1(c,0); 61 | end" 62 | },{ 63 | 17, 16, 64 | "function [L] = mat(@w,x,y) 65 | h = tanh(w*const(vertcat(x,1))); 66 | h = tanh(w*const(vertcat(h,1))); 67 | L = quad(const(h),eye(3)); 68 | end" 69 | },{ 70 | 18, 16, 71 | "function [L] = mat(@w,x,y) 72 | h = tanh(w*const(vertcat(x,1))); 73 | s = sinh(w*horzcat(h,1)); 74 | L = quad(eye(3),l1(h-y,0)); 75 | end" 76 | },{ 77 | 14, 13, 78 | "function [L] = mat(@w,x,y,@z) 79 | h = replicateH(w,1) + x dot y * sin(2); 80 | L = sum(h^2,0); 81 | end" 82 | },{ 83 | 16, 16, 84 | "function [L] = mat(@w,x,y) 85 | h = const(w*-vertcat(x,cols(5))); 86 | s = vdiag(w*horzcat(h,1)); 87 | L = l1(s-h,0); 88 | end" 89 | }); 90 | 91 | parametarise_test!(constant_folding_none,{ 92 | 8, 93 | "function [d] = mat(a,b) 94 | c = a + b * a'; 95 | d = l2(c,0) * l1(c,0); 96 | end" 97 | },{ 98 | 14, 99 | "function [L] = mat(@w,x,y) 100 | h = tanh(w*vertcat(x,1)); 101 | h = tanh(w*vertcat(h,1)); 102 | L = l2(h-y,0); 103 | end" 104 | },{ 105 | 14, 106 | "function [L] = mat(@w,x,y) 107 | h = tanh(w*vertcat(x,1)); 108 | s = sinh(w*horzcat(h,1)); 109 | L = l1(h-y,0); 110 | end" 111 | },{ 112 | 10, 113 | "function [L] = mat(@w,x,y,@z) 114 | h = w + x dot y * z; 115 | L = sum(h^3,0); 116 | end" 117 | },{ 118 | 15, 119 | "function [L] = mat(@w,x,y) 120 | h = const(w*-vertcat(x,1)); 121 | s = vdiag(w*horzcat(h,1)); 122 | L = l1(s-h,0); 123 | end" 124 | }); 125 | -------------------------------------------------------------------------------- /tests/optimization/mod.rs: -------------------------------------------------------------------------------- 1 | mod constant_folding; 2 | --------------------------------------------------------------------------------