merge c_frontend with graphing_aby EXPERIMENTAL

This commit is contained in:
Edward Chen
2022-03-24 17:36:55 +00:00
24 changed files with 10565 additions and 286 deletions

228
Cargo.lock generated
View File

@@ -4,9 +4,9 @@ version = 3
[[package]]
name = "addr2line"
version = "0.16.0"
version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e61f2b7f93d2c7d2b08263acaa4a363b3e276806c68af6134c44f523bf1aacd"
checksum = "b9ecd88a8c8378ca913a680cd98f0f13ac67383d35993f86c90a70e3f137816b"
dependencies = [
"gimli",
]
@@ -39,18 +39,18 @@ dependencies = [
[[package]]
name = "ansi_term"
version = "0.11.0"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b"
checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2"
dependencies = [
"winapi",
]
[[package]]
name = "approx"
version = "0.5.0"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "072df7202e63b127ab55acfe16ce97013d5b97bf160489336d3f1840fd78e99e"
checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6"
dependencies = [
"num-traits",
]
@@ -80,21 +80,21 @@ dependencies = [
[[package]]
name = "autocfg"
version = "1.0.1"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]]
name = "az"
version = "1.1.2"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d6dff4a1892b54d70af377bf7a17064192e822865791d812957f21e3108c325"
checksum = "f771a5d1f5503f7f4279a30f3643d3421ba149848b89ecaaec0ea2acf04a5ac4"
[[package]]
name = "backtrace"
version = "0.3.61"
version = "0.3.64"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a905d892734eea339e896738c14b9afce22b5318f64b951e70bf3844419b01"
checksum = "5e121dee8023ce33ab248d9ce1493df03c3b38a659b240096fcbd7048ff9c31f"
dependencies = [
"addr2line",
"cc",
@@ -209,9 +209,9 @@ checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"
[[package]]
name = "cc"
version = "1.0.71"
version = "1.0.73"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "79c2681d6594606957bbb8631c4b90a7fcaaa72cdb714743a437b156d6a7eedd"
checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11"
[[package]]
name = "cfg-if"
@@ -259,9 +259,9 @@ dependencies = [
[[package]]
name = "clap"
version = "2.33.3"
version = "2.34.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37e58ac78573c40708d45522f0d80fa2f01cc4f9b4e2bf749807255454312002"
checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c"
dependencies = [
"ansi_term",
"atty",
@@ -296,9 +296,9 @@ checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc"
[[package]]
name = "crossbeam-channel"
version = "0.5.1"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06ed27e177f16d65f0f0c22a213e17c696ace5dd64b14258b52f9417ccb52db4"
checksum = "e54ea8bc3fb1ee042f5aace6e3c6e025d3874866da222930f70ce62aceba0bfa"
dependencies = [
"cfg-if",
"crossbeam-utils",
@@ -317,9 +317,9 @@ dependencies = [
[[package]]
name = "crossbeam-epoch"
version = "0.9.5"
version = "0.9.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ec02e091aa634e2c3ada4a392989e7c3116673ef0ac5b72232439094d73b7fd"
checksum = "c00d6d2ea26e8b151d99093005cb442fb9a37aeaca582a03ec70946f49ab5ed9"
dependencies = [
"cfg-if",
"crossbeam-utils",
@@ -330,9 +330,9 @@ dependencies = [
[[package]]
name = "crossbeam-utils"
version = "0.8.5"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d82cfc11ce7f2c3faef78d8a684447b40d503d9681acebed6cb728d45940c4db"
checksum = "b5e5bed1f1c269533fa816a0a5492b3545209a205ca1a54842be180eb63a16a6"
dependencies = [
"cfg-if",
"lazy_static",
@@ -392,9 +392,9 @@ version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa4da3c766cd7a0db8242e326e9e4e081edd567072893ed320008189715366a4"
dependencies = [
"proc-macro2 1.0.30",
"quote 1.0.10",
"syn 1.0.80",
"proc-macro2 1.0.36",
"quote 1.0.15",
"syn 1.0.86",
"synstructure",
]
@@ -404,6 +404,15 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed"
[[package]]
name = "fastrand"
version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3fcf0cee53519c866c09b5de1f6c56ff9d647101f81c1964fa632e148896cdf"
dependencies = [
"instant",
]
[[package]]
name = "ff"
version = "0.11.0"
@@ -417,9 +426,9 @@ dependencies = [
[[package]]
name = "fixedbitset"
version = "0.4.0"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "398ea4fabe40b9b0d885340a2a991a44c8a645624075ad966d21f88688e2b69e"
checksum = "279fb028e20b3c4c320317955b77c5e0c9701f05a1d309905d6fc702cdc5053e"
[[package]]
name = "fnv"
@@ -463,9 +472,9 @@ dependencies = [
[[package]]
name = "getrandom"
version = "0.2.3"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fcd999463524c52659517fe2cea98493cfe485d10565e7b0fb07dbba7ad2753"
checksum = "d39cd93900197114fa1fcb7ae84ca742095eed9442088988ae74fa744e930e77"
dependencies = [
"cfg-if",
"libc",
@@ -474,9 +483,9 @@ dependencies = [
[[package]]
name = "gimli"
version = "0.25.0"
version = "0.26.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0a01e0497841a3b2db4f8afa483cce65f7e96a3498bd6c541734792aeac8fe7"
checksum = "78cc372d058dcf6d5ecd98510e7fbc9e5aec4d21de70f65fea8fecebcd881bd4"
[[package]]
name = "gmp-mpfr-sys"
@@ -490,9 +499,9 @@ dependencies = [
[[package]]
name = "good_lp"
version = "1.2.0"
version = "1.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c8fba2696c6b6fce795aa113be95338541a1e08e7a80fc06ceded3e152a9c3f"
checksum = "c6e4f4cb8fac5e7a7862d8647529e3cc0cd478817c28efc7031d144ac259a718"
dependencies = [
"coin_cbc",
"fnv",
@@ -561,14 +570,23 @@ checksum = "9007da9cacbd3e6343da136e98b0d2df013f553d35bdec8b518f07bea768e19c"
[[package]]
name = "indexmap"
version = "1.7.0"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc633605454125dec4b66843673f01c7df2b89479b32e0ed634e43a91cff62a5"
checksum = "282a6247722caba404c065016bbfa522806e51714c34f5dfc3e4a3a46fcb4223"
dependencies = [
"autocfg",
"hashbrown",
]
[[package]]
name = "instant"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"
dependencies = [
"cfg-if",
]
[[package]]
name = "itertools"
version = "0.7.11"
@@ -589,9 +607,9 @@ dependencies = [
[[package]]
name = "itoa"
version = "0.4.8"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4"
checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35"
[[package]]
name = "lang-c"
@@ -607,9 +625,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
version = "0.2.104"
version = "0.2.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b2f96d100e1cf1929e7719b7edb3b90ab5298072638fccd77be9ce942ecdfce"
checksum = "1bf2e165bb3457c8e098ea76f3e3bc9db55f87aa90d52d0e6be741470916aaa4"
[[package]]
name = "log"
@@ -637,10 +655,10 @@ checksum = "56a7d287fd2ac3f75b11f19a1c8a874a7d55744bd91f7a1b3e7cf87d4343c36d"
dependencies = [
"beef",
"fnv",
"proc-macro2 1.0.30",
"quote 1.0.10",
"proc-macro2 1.0.36",
"quote 1.0.15",
"regex-syntax",
"syn 1.0.80",
"syn 1.0.86",
"utf8-ranges",
]
@@ -677,9 +695,9 @@ checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a"
[[package]]
name = "memoffset"
version = "0.6.4"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59accc507f1338036a0477ef61afdae33cde60840f4dfe481319ce3ad116ddf9"
checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce"
dependencies = [
"autocfg",
]
@@ -705,9 +723,9 @@ dependencies = [
[[package]]
name = "num_cpus"
version = "1.13.0"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05499f3756671c15885fee9034446956fff3f243d6077b91e5767df161f766b3"
checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1"
dependencies = [
"hermit-abi",
"libc",
@@ -715,9 +733,9 @@ dependencies = [
[[package]]
name = "object"
version = "0.26.2"
version = "0.27.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39f37e50073ccad23b6d09bcb5b263f4e76d3bb6038e4a3c08e52162ffa8abc2"
checksum = "67ac1d3f9a1d3616fd9a60c8d74296f22406a238b6a72f5cc1e6f314df4ffbf9"
dependencies = [
"memchr",
]
@@ -783,9 +801,9 @@ checksum = "99b8db626e31e5b81787b9783425769681b347011cc59471e33ea46d2ea0cf55"
dependencies = [
"pest",
"pest_meta",
"proc-macro2 1.0.30",
"quote 1.0.10",
"syn 1.0.80",
"proc-macro2 1.0.36",
"quote 1.0.15",
"syn 1.0.86",
]
[[package]]
@@ -811,9 +829,9 @@ dependencies = [
[[package]]
name = "ppv-lite86"
version = "0.2.14"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3ca011bd0129ff4ae15cd04c4eef202cadf6c51c21e47aba319b4e0501db741"
checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872"
[[package]]
name = "proc-macro-error"
@@ -822,9 +840,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"
dependencies = [
"proc-macro-error-attr",
"proc-macro2 1.0.30",
"quote 1.0.10",
"syn 1.0.80",
"proc-macro2 1.0.36",
"quote 1.0.15",
"syn 1.0.86",
"version_check",
]
@@ -834,8 +852,8 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"
dependencies = [
"proc-macro2 1.0.30",
"quote 1.0.10",
"proc-macro2 1.0.36",
"quote 1.0.15",
"version_check",
]
@@ -850,9 +868,9 @@ dependencies = [
[[package]]
name = "proc-macro2"
version = "1.0.30"
version = "1.0.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edc3358ebc67bc8b7fa0c007f945b0b18226f78437d61bec735a9eb96b61ee70"
checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029"
dependencies = [
"unicode-xid 0.2.2",
]
@@ -874,9 +892,9 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b22a693222d716a9587786f37ac3f6b4faedb5b80c23914e7303ff5a1d8016e9"
dependencies = [
"proc-macro2 1.0.30",
"quote 1.0.10",
"syn 1.0.80",
"proc-macro2 1.0.36",
"quote 1.0.15",
"syn 1.0.86",
]
[[package]]
@@ -890,11 +908,11 @@ dependencies = [
[[package]]
name = "quote"
version = "1.0.10"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38bc8cc6a5f2e3655e0899c1b848643b2562f853f114bfec7be120678e3ace05"
checksum = "864d3e96a899863136fc6e99f3d7cae289dafe43bf2c5ac19b70df7210c0a145"
dependencies = [
"proc-macro2 1.0.30",
"proc-macro2 1.0.36",
]
[[package]]
@@ -905,14 +923,13 @@ checksum = "643f8f41a8ebc4c5dc4515c82bb8abd397b527fc20fd681b7c011c2aee5d44fb"
[[package]]
name = "rand"
version = "0.8.4"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e7573632e6454cf6b99d7aac4ccca54be06da05aca2ef7423d22d27d4d4bcd8"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
"rand_hc",
]
[[package]]
@@ -934,15 +951,6 @@ dependencies = [
"getrandom",
]
[[package]]
name = "rand_hc"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d51e9f596de227fda2ea6c84607f5558e196eeaf43c986b724ba4fb8fdf497e7"
dependencies = [
"rand_core",
]
[[package]]
name = "rayon"
version = "1.5.1"
@@ -1014,9 +1022,9 @@ dependencies = [
[[package]]
name = "rug"
version = "1.13.0"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee0c6e98de59509e62e09f3456b23cebb75dad21928882016f169bb628843459"
checksum = "6ac804305677221f4c82469fd7eb8bfe00dd01420aa191197cb87d738520feef"
dependencies = [
"az",
"gmp-mpfr-sys",
@@ -1031,9 +1039,9 @@ checksum = "7ef03e0a2b150c7a90d01faf6254c9c48a41e95fb2a8c2ac1c6f0d2b9aefc342"
[[package]]
name = "ryu"
version = "1.0.5"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e"
checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f"
[[package]]
name = "scopeguard"
@@ -1043,15 +1051,15 @@ checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
[[package]]
name = "serde"
version = "1.0.130"
version = "1.0.136"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f12d06de37cf59146fbdecab66aa99f9fe4f78722e3607577a5375d66bd0c913"
checksum = "ce31e24b01e1e524df96f1c2fdd054405f8d7376249a5110886fb4b658484789"
[[package]]
name = "serde_json"
version = "1.0.68"
version = "1.0.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f690853975602e1bfe1ccbf50504d67174e3bcf340f23b5ea9992e0587a52d8"
checksum = "8e8d9fa5c3b304765ce1fd9c4c8a3de2c8db365a5b91be52f186efc675681d95"
dependencies = [
"itoa",
"ryu",
@@ -1087,9 +1095,9 @@ checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"
[[package]]
name = "structopt"
version = "0.3.25"
version = "0.3.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40b9788f4202aa75c240ecc9c15c65185e6a39ccdeb0fd5d008b98825464c87c"
checksum = "0c6b5c64445ba8094a6ab0c3cd2ad323e07171012d9c98b0b15651daf1787a10"
dependencies = [
"clap",
"lazy_static",
@@ -1104,9 +1112,9 @@ checksum = "dcb5ae327f9cc13b68763b5749770cb9e048a99bd9dfdfa58d0cf05d5f64afe0"
dependencies = [
"heck",
"proc-macro-error",
"proc-macro2 1.0.30",
"quote 1.0.10",
"syn 1.0.80",
"proc-macro2 1.0.36",
"quote 1.0.15",
"syn 1.0.86",
]
[[package]]
@@ -1128,12 +1136,12 @@ dependencies = [
[[package]]
name = "syn"
version = "1.0.80"
version = "1.0.86"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d010a1623fbd906d51d650a9916aaefc05ffa0e4053ff7fe601167f3e715d194"
checksum = "8a65b3f4ffa0092e9887669db0eae07941f023991ab58ea44da8fe8e2d511c6b"
dependencies = [
"proc-macro2 1.0.30",
"quote 1.0.10",
"proc-macro2 1.0.36",
"quote 1.0.15",
"unicode-xid 0.2.2",
]
@@ -1143,9 +1151,9 @@ version = "0.12.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f"
dependencies = [
"proc-macro2 1.0.30",
"quote 1.0.10",
"syn 1.0.80",
"proc-macro2 1.0.36",
"quote 1.0.15",
"syn 1.0.86",
"unicode-xid 0.2.2",
]
@@ -1157,13 +1165,13 @@ checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]]
name = "tempfile"
version = "3.2.0"
version = "3.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dac1c663cfc93810f88aed9b8941d48cabf856a1b111c29a40439018d870eb22"
checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4"
dependencies = [
"cfg-if",
"fastrand",
"libc",
"rand",
"redox_syscall",
"remove_dir_all",
"winapi",
@@ -1202,9 +1210,9 @@ version = "1.0.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa32fd3f627f367fe16f893e2597ae3c05020f8bba2666a4e6ea73d377e5714b"
dependencies = [
"proc-macro2 1.0.30",
"quote 1.0.10",
"syn 1.0.80",
"proc-macro2 1.0.36",
"quote 1.0.15",
"syn 1.0.86",
]
[[package]]
@@ -1215,9 +1223,9 @@ checksum = "0685c84d5d54d1c26f7d3eb96cd41550adb97baed141a761cf335d3d33bcd0ae"
[[package]]
name = "typenum"
version = "1.14.0"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63708a265f51345575b27fe43f9500ad611579e764c79edbc2037b1121959ec"
checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987"
[[package]]
name = "ucd-trie"
@@ -1227,9 +1235,9 @@ checksum = "56dee185309b50d1f11bfedef0fe6d036842e3fb77413abef29f8f8d1c5d4c1c"
[[package]]
name = "unicode-segmentation"
version = "1.8.0"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8895849a949e7845e06bd6dc1aa51731a103c42707010a5b591c0038fb73385b"
checksum = "7e8820f5d777f6224dc4be3632222971ac30164d4a258d595640799554ebfd99"
[[package]]
name = "unicode-width"
@@ -1263,9 +1271,9 @@ checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
[[package]]
name = "version_check"
version = "0.9.3"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "void"

42
Makefile Normal file
View File

@@ -0,0 +1,42 @@
all: test
build:
cargo build --release --examples
cargo build --examples
build_deps:
./scripts/build_aby.zsh
build_aby_zokrates: build
./scripts/build_mpc_zokrates_test.zsh
build_aby_c: build
./scripts/build_mpc_c_test.zsh
test: build build_aby_zokrates build_aby_c
cargo test
./scripts/zokrates_test.zsh
python3 ./scripts/aby_tests/zokrates_test_aby.py
python3 ./scripts/aby_tests/c_test_aby.py
./scripts/test_zok_to_ilp.zsh
./scripts/test_zok_to_ilp_pf.zsh
./scripts/test_datalog.zsh
c_aby: build_aby_c
python3 ./scripts/aby_tests/c_test_aby.py
z_aby: build_aby_zokrates
python3 ./scripts/aby_tests/zokrates_test_aby.py
clean:
# remove all generated files
rm -rf scripts/aby_tests/tests/*.txt
rm -rf scripts/aby_tests/__pycache__
rm -rf ./third_party/ABY/src/examples/*.graph
rm -rf P V pi perf.data perf.data.old flamegraph.svg
format:
cargo fmt --all
lint:
cargo clippy

View File

@@ -1,38 +1,44 @@
int main(
__attribute__((private(0))) int db[1024],
__attribute__((private(1))) int sample[4])
#define N 256
#define K 4 // currently fixed, do not change
#define INNER 64
#define OUTER (N/64)
int match_fix(int x1, int x2,int x3, int x4, int y1, int y2, int y3, int y4) {
int r = 0;
int i;
int t1 = (x1-y1);
int t2 = (x2-y2);
int t3 = (x3-y3);
int t4 = (x4-y4);
r = t1*t1 + t2*t2 + t3*t3 + t4*t4;
return r;
}
int min(int *data, int len) {
int best = data[0];
for (int i = 0; i < len; i++){
if (data[i] < best){
best = data[i];
}
}
return best;
}
void match_decomposed(int *db, int *OUTPUT_matches, int len, int *sample) {
for(int i = 0; i < len; i++) {
OUTPUT_matches[i] = match_fix(db[i*K], db[i*K+1], db[i*K+2], db[i*K+3], sample[0], sample[1], sample[2], sample[3]);
}
}
int main( __attribute__((private(0))) int db[1024], __attribute__((private(1))) int sample[4])
{
int N = 256;
int K = 4;
//int matches[4];
int matches[N];
// Compute distances
for (int i = 0; i < N; i++)
{
int db_inner[K];
for (int j = 0; j < K; j++)
{
db_inner[j] = db[i * K + j];
}
int r = 0;
for (int k = 0; k < K; k++)
{
int t = (db_inner[k] - sample[k]);
r += t * t;
}
matches[i] = r;
}
match_decomposed(db, matches, N, sample);
// Compute minimum
int best_match = matches[0];
for (int l = 1; l < N; l++)
{
if (matches[l] < best_match)
{
best_match = matches[l];
}
}
int best_match = min(matches, N);
return best_match;
}

View File

@@ -0,0 +1,202 @@
int main(__attribute__((private(0))) int a[200], __attribute__((private(1))) int b[200])
{
int D = 2;
int NA = 100;
int NB = 100;
int NC = 5;
int PRECISION = 4;
int LEN = NA + NB;
int LEN_OUTER = 10;
int LEN_INNER = LEN / LEN_OUTER;
// init data
int data[LEN * D];
for (int i_0 = 0; i_0 < D * NA; i_0++)
{
data[i_0] = a[i_0];
}
int offset = D * NA;
for (int i_1 = 0; i_1 < D * NB; i_1++)
{
data[i_1 + offset] = b[i_1];
}
int output[D * NC];
// ======================= kmeans
int cluster[D * NC];
// Assign random start cluster from data
for (int i_2 = 0; i_2 < NC; i_2++)
{
cluster[i_2 * D] = data[((i_2 + 3) % LEN) * D];
cluster[i_2 * D + 1] = data[((i_2 + 3) % LEN) * D + 1];
}
for (int i_3 = 0; i_3 < PRECISION; i_3++)
{
int new_cluster[D * NC];
// ======================= iteration_unrolled_outer
int count[NC];
// Set Outer result
for (int i_4 = 0; i_4 < NC; i_4++)
{
new_cluster[i_4 * D] = 0;
new_cluster[i_4 * D + 1] = 0;
count[i_4] = 0;
}
int loop_clusterD1[NC * LEN_OUTER];
int loop_clusterD2[NC * LEN_OUTER];
int loop_count[NC * LEN_OUTER];
// Compute decomposition
for (int i_5 = 0; i_5 < LEN_OUTER; i_5++)
{
// Copy data, fasthack for scalability
int data_offset = i_5 * LEN_INNER * D;
int data_inner[LEN_INNER * D];
// memcpy(data_inner, data+data_offset, LEN_INNER*D*sizeof(coord_t));
for (int i_6 = 0; i_6 < LEN_INNER * D; i_6++)
{
data_inner[i_6] = data[i_6 + data_offset];
}
int cluster_inner[NC * D];
int count_inner[NC];
// ======================= iteration_unrolled_inner_depth(data_inner, cluster, cluster_inner, count_inner, LEN_INNER, NC);
int dist[NC];
int pos[NC];
int bestMap_inner[LEN_INNER];
for (int i_7 = 0; i_7 < NC; i_7++)
{
cluster_inner[i_7 * D] = 0;
cluster_inner[i_7 * D + 1] = 0;
count_inner[i_7] = 0;
}
// Compute nearest clusters for Data item i
for (int i_8 = 0; i_8 < LEN_INNER; i_8++)
{
int dx = data_inner[i_8 * D];
int dy = data_inner[i_8 * D + 1];
for (int i_9 = 0; i_9 < NC; i_9++)
{
pos[i_9] = i_9;
int x1 = cluster[D * i_9];
int y1 = cluster[D * i_9 + 1];
int x2 = dx;
int y2 = dy;
dist[i_9] = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
}
// hardcoded NC = 5;
// stride = 1
// stride = 2
// stride = 4
int stride = 1;
for (int i_10 = 0; i_10 < NC - stride; i_10 += 2)
{
if (dist[i_10 + stride] < dist[i_10])
{
dist[i_10] = dist[i_10 + stride];
pos[i_10] = pos[i_10 + stride];
}
}
stride = 2;
for (int i_11 = 0; i_11 < NC - stride; i_11 += 4)
{
if (dist[i_11 + stride] < dist[i_11])
{
dist[i_11] = dist[i_11 + stride];
pos[i_11] = pos[i_11 + stride];
}
}
stride = 4;
for (int i_12 = 0; i_12 < NC - stride; i_12 += 8)
{
if (dist[i_12 + stride] < dist[i_12])
{
dist[i_12] = dist[i_12 + stride];
pos[i_12] = pos[i_12 + stride];
}
}
bestMap_inner[i_8] = pos[0];
int cc = bestMap_inner[i_8];
cluster_inner[cc * D] += data_inner[i_8 * D];
cluster_inner[cc * D + 1] += data_inner[i_8 * D + 1];
count_inner[cc] += 1;
}
// // ======================= iteration_unrolled_inner_depth(data_inner, cluster, cluster_inner, count_inner, LEN_INNER, NC);
for (int i_13 = 0; i_13 < NC; i_13++)
{
loop_clusterD1[i_13 * LEN_OUTER + i_5] = cluster_inner[i_13 * D];
loop_clusterD2[i_13 * LEN_OUTER + i_5] = cluster_inner[i_13 * D + 1];
loop_count[i_13 * LEN_OUTER + i_5] = count_inner[i_13];
}
}
for (int i_14 = 0; i_14 < NC; i_14++)
{
new_cluster[i_14 * D] =
loop_clusterD1[i_14 * LEN_OUTER + 0] + loop_clusterD1[i_14 * LEN_OUTER + 1] +
loop_clusterD1[i_14 * LEN_OUTER + 2] + loop_clusterD1[i_14 * LEN_OUTER + 3] +
loop_clusterD1[i_14 * LEN_OUTER + 4] + loop_clusterD1[i_14 * LEN_OUTER + 5] +
loop_clusterD1[i_14 * LEN_OUTER + 6] + loop_clusterD1[i_14 * LEN_OUTER + 7] +
loop_clusterD1[i_14 * LEN_OUTER + 8] + loop_clusterD1[i_14 * LEN_OUTER + 9];
new_cluster[i_14 * D + 1] =
loop_clusterD2[i_14 * LEN_OUTER + 0] + loop_clusterD2[i_14 * LEN_OUTER + 1] +
loop_clusterD2[i_14 * LEN_OUTER + 2] + loop_clusterD2[i_14 * LEN_OUTER + 3] +
loop_clusterD2[i_14 * LEN_OUTER + 4] + loop_clusterD2[i_14 * LEN_OUTER + 5] +
loop_clusterD2[i_14 * LEN_OUTER + 6] + loop_clusterD2[i_14 * LEN_OUTER + 7] +
loop_clusterD2[i_14 * LEN_OUTER + 8] + loop_clusterD2[i_14 * LEN_OUTER + 9];
count[i_14] =
loop_count[i_14 * LEN_OUTER + 0] + loop_count[i_14 * LEN_OUTER + 1] +
loop_count[i_14 * LEN_OUTER + 2] + loop_count[i_14 * LEN_OUTER + 3] +
loop_count[i_14 * LEN_OUTER + 4] + loop_count[i_14 * LEN_OUTER + 5] +
loop_count[i_14 * LEN_OUTER + 6] + loop_count[i_14 * LEN_OUTER + 7] +
loop_count[i_14 * LEN_OUTER + 8] + loop_count[i_14 * LEN_OUTER + 9];
}
// Recompute cluster Pos
// Compute mean
for (int i_15 = 0; i_15 < NC; i_15++)
{
if (count[i_15] > 0)
{
new_cluster[i_15 * D] /= count[i_15];
new_cluster[i_15 * D + 1] /= count[i_15];
}
}
// ======================= iteration_unrolled_outer
// We need to copy inputs to outputs
for (int i_16 = 0; i_16 < NC * D; i_16++)
{
cluster[i_16] = new_cluster[i_16];
}
}
for (int i_17 = 0; i_17 < NC; i_17++)
{
output[i_17 * D] = cluster[i_17 * D];
output[i_17 * D + 1] = cluster[i_17 * D + 1];
}
// ======================= kmeans
// return output[0];
int sum = 0;
for (int i_18 = 0; i_18 < D * NC; i_18++)
{
sum += output[i_18];
}
return sum;
}

View File

@@ -36,6 +36,7 @@ use std::io::Write;
use std::path::{Path, PathBuf};
use structopt::clap::arg_enum;
use structopt::StructOpt;
use std::time::Instant;
#[derive(Debug, StructOpt)]
#[structopt(name = "circ", about = "CirC: the circuit compiler")]
@@ -99,6 +100,10 @@ enum Backend {
Mpc {
#[structopt(long, default_value = "hycc", name = "cost_model")]
cost_model: String,
#[structopt(long, default_value = "ilp", name = "assign_mode")]
assign_mode: String,
#[structopt(long, default_value = "3000", name = "part_size")]
part_size: usize,
},
}
@@ -165,6 +170,7 @@ fn determine_language(l: &Language, input_path: &Path) -> DeterminedLanguage {
}
fn main() {
let before_comp = Instant::now();
env_logger::Builder::from_default_env()
.format_level(false)
.format_timestamp(None)
@@ -266,6 +272,7 @@ fn main() {
};
println!("Done with IR optimization");
let after_comp = Instant::now();
match options.backend {
#[cfg(feature = "r1cs")]
Backend::R1cs {
@@ -318,7 +325,7 @@ fn main() {
Backend::R1cs { .. } => {
panic!("Missing feature: r1cs");
}
Backend::Mpc { cost_model } => {
Backend::Mpc { cost_model, assign_mode, part_size} => {
println!("Converting to ABY");
let lang_str = match language {
DeterminedLanguage::C => "c".to_string(),
@@ -326,7 +333,8 @@ fn main() {
_ => panic!("Language isn't supported by MPC backend: {:#?}", language),
};
println!("Cost model: {}", cost_model);
to_aby(cs, &path_buf, &lang_str, &cost_model);
to_aby(cs, &path_buf, &lang_str, &cost_model, &assign_mode, &part_size);
println!("Compile cost: {:?}", after_comp.duration_since(before_comp));
}
#[cfg(feature = "lp")]
Backend::Ilp { .. } => {

View File

@@ -30,6 +30,8 @@ fn main() {
metadata: ComputationMetadata::default(),
values: None,
};
let _assignment = ilp::assign(&cs, "hycc");
let cg = cs.to_subgraph();
let _assignment = ilp::assign(&cg, "opa");
//dbg!(&assignment);
}

View File

@@ -4,33 +4,26 @@ from util import run_tests
from test_suite import *
if __name__ == "__main__":
tests = arithmetic_tests + \
mod_tests + \
arithmetic_boolean_tests + \
nary_arithmetic_tests + \
bitwise_tests + \
boolean_tests + \
nary_boolean_tests + \
const_arith_tests + \
const_bool_tests + \
ite_tests + \
div_tests + \
array_tests + \
struct_tests + \
matrix_tests + \
ptr_tests + \
c_array_tests + \
c_misc_tests + \
biomatch_tests + \
kmeans_tests + \
kmeans_tests_2
# tests = arithmetic_tests + \
# mod_tests + \
# arithmetic_boolean_tests + \
# nary_arithmetic_tests + \
# bitwise_tests + \
# boolean_tests + \
# nary_boolean_tests + \
# const_arith_tests + \
# const_bool_tests + \
# ite_tests + \
# div_tests + \
# array_tests + \
# c_array_tests + \
# misc_tests + \
# biomatch_tests + \
# kmeans_tests
# shift_tests
tests = biomatch_tests
# tests = new_tests
# tests = kmeans_tests_2
# tests = struct_tests
# tests = matrix_tests
# TODO: add support for return value - int promotion
# unsigned_arithmetic_tests + \

View File

@@ -0,0 +1,3 @@
db 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
sample 0 1 2 3
res 4

View File

@@ -0,0 +1,3 @@
db 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
sample 0 1 2 3
res 324

View File

@@ -0,0 +1,8 @@
// server
a 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
// client
b 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
// result
499

View File

@@ -6,7 +6,7 @@
# ],
# ]
new_tests = [
biomatch_tests = [
# [
# "Structs",
# "2pc_structs",
@@ -573,6 +573,11 @@ kmeans_tests = [
"2pc_kmeans",
"./scripts/aby_tests/test_inputs/kmeans.txt",
],
[
"kmeans2",
"2pc_kmeans2",
"./scripts/aby_tests/test_inputs/kmeans2.txt",
],
]

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -9,9 +9,12 @@ def rename_test(name: str, lang: str) -> str:
return f"{name}_{lang}"
def build_cmd(name:str, test_file: str, role: int) -> List[str]:
print(name)
print(role)
print(test_file)
bytecode = f"./scripts/aby_tests/tests/{name}_bytecode.txt"
share_map = f"./scripts/aby_tests/tests/{name}_share_map.txt"
return [os.getenv("ABY_SOURCE") + "/build/bin/aby_interpreter", "-M", "mpc", "-R", str(role), "-b", bytecode, "-t", test_file, "-s", share_map]
return [os.getenv("ABY_SOURCE", "../ABY") + "/build/bin/aby_interpreter", "-M", "mpc", "-R", str(role), "-b", bytecode, "-t", test_file, "-s", share_map]
def get_result(file_path):
if os.path.exists(file_path):

114
scripts/aby_tests/utils.py Normal file
View File

@@ -0,0 +1,114 @@
import os
from subprocess import Popen, PIPE
import sys
from typing import List
def init_progress_bar(toolbar_width=40):
""" Initialize progress bar """
sys.stdout.write("[%s]" % ("." * toolbar_width))
sys.stdout.flush()
sys.stdout.write("\b" * (toolbar_width+1))
def update_progress_bar():
""" Increment progress bar """
sys.stdout.write("#")
sys.stdout.flush()
def end_progress_bar():
""" Close progress bar """
sys.stdout.write("]\n") # this ends the progress bar
def rename_test(name: str, lang: str) -> str:
"""Append path with language type"""
return f"{name}_{lang}"
def build_cmd(name:str, test_file: str, role: int) -> List[str]:
bytecode = f"./scripts/aby_tests/tests/{name}_bytecode.txt"
share_map = f"./scripts/aby_tests/tests/{name}_share_map.txt"
param_map= f"./scripts/aby_tests/tests/{name}_param_map.txt"
return [os.getenv("ABY_SOURCE", "../ABY") + "/build/bin/aby_interpreter", "-M", "mpc", "-R", str(role), "-b", bytecode, "-t", test_file, "-s", share_map, "-p", param_map]
def get_result(file_path):
if os.path.exists(file_path):
with open(file_path) as f:
lines = f.read().splitlines()
res_flag = False
res = []
for l in lines:
l = l.strip()
if not l: continue
if res_flag:
res.append(l)
if l.startswith("//") and "result" in l:
res_flag = True
elif l.startswith("//"):
res_flag = False
return "\n".join(res)
else:
raise RuntimeError("Unable to open file: "+file_path)
def run_test(expected: str, server_cmd: List[str], client_cmd: List[str]) -> bool:
assert server_cmd[0] == client_cmd[0], "server and client do not have the same cmd: " + server_cmd[0] + ", " + client_cmd[0]
try:
server_proc = Popen(" ".join(server_cmd), shell=True, stdout=PIPE, stderr=PIPE)
client_proc = Popen(" ".join(client_cmd), shell=True, stdout=PIPE, stderr=PIPE)
server_out, server_err = server_proc.communicate(timeout=30)
client_out, client_err = client_proc.communicate(timeout=30)
if server_err:
raise RuntimeError("Server error: "+server_err.decode("utf-8").strip())
if client_err:
raise RuntimeError("Client error: "+client_err.decode("utf-8").strip())
server_out = server_out.decode("utf-8").strip()
client_out = client_out.decode("utf-8").strip()
assert server_out == client_out, "server out != client out\nserver_out: "+server_out+"\nclient_out: "+client_out
assert server_out == expected, "server_out: "+server_out+"\nexpected: "+expected
return True, ""
except Exception as e:
# print("Exception: ", e)
return False, e
def run_tests(lang: str, tests: List[dict]):
"""
tests will be a list of all tests to run. each element in the list will be
1. description of test case: str
2. test name: str
4. test file path: str
"""
print(f"Running ABY tests for {lang} frontend")
failed_test_descs = []
num_retries = 2
progress_inc = 5
init_progress_bar(len(tests) // progress_inc + 1)
for t, test in enumerate(tests):
assert len(test) == 3, "test configurations are wrong for test: "+test[0]
desc = test[0]
name = test[1]
rename = rename_test(name, lang)
server_cmd = build_cmd(rename, test[2], 0)
client_cmd = build_cmd(rename, test[2], 1)
expected = get_result(test[2])
test_results = []
for _ in range(num_retries):
test_results.append(run_test(expected, server_cmd, client_cmd))
if all([not r[0] for r in test_results]):
failed_test_descs += [(desc, e[1], " ".join(server_cmd)) for e in test_results]
if t % progress_inc == 0:
update_progress_bar()
end_progress_bar()
if len(failed_test_descs) == 0:
print("All tests passed ✅")
failed_test_descs = [f"{r}:\n{e}\n{cmd}" for r, e, cmd in failed_test_descs]
assert len(failed_test_descs) == 0, "there were failed test cases:\n======\n" + "\n\n".join(failed_test_descs)

View File

@@ -21,99 +21,89 @@ esac
function mpc_test {
parties=$1
cpath=$2
RUST_BACKTRACE=1 measure_time $BIN --parties $parties $cpath mpc --cost-model "hycc"
RUST_BACKTRACE=1 measure_time $BIN --parties $parties $cpath mpc --cost-model "hycc" --assign-mode "ilp_mut" --part-size 3000
}
# build mpc arithmetic tests
mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_add.c
mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_sub.c
mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_mult.c
mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_mult_add_pub.c
mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_mod.c
# mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_add_unsigned.c
mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_int_equals.c
mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_int_greater_than.c
mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_int_greater_equals.c
mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_int_less_than.c
mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_int_less_equals.c
# # build nary arithmetic tests
mpc_test 2 ./examples/C/mpc/unit_tests/nary_arithmetic_tests/2pc_nary_arithmetic_add.c
# # build bitwise tests
mpc_test 2 ./examples/C/mpc/unit_tests/bitwise_tests/2pc_bitwise_and.c
mpc_test 2 ./examples/C/mpc/unit_tests/bitwise_tests/2pc_bitwise_or.c
mpc_test 2 ./examples/C/mpc/unit_tests/bitwise_tests/2pc_bitwise_xor.c
# # build boolean tests
mpc_test 2 ./examples/C/mpc/unit_tests/boolean_tests/2pc_boolean_and.c
mpc_test 2 ./examples/C/mpc/unit_tests/boolean_tests/2pc_boolean_or.c
mpc_test 2 ./examples/C/mpc/unit_tests/boolean_tests/2pc_boolean_equals.c
# # build nary boolean tests
mpc_test 2 ./examples/C/mpc/unit_tests/nary_boolean_tests/2pc_nary_boolean_and.c
# # build const tests
mpc_test 2 ./examples/C/mpc/unit_tests/const_tests/2pc_const_arith.c
mpc_test 2 ./examples/C/mpc/unit_tests/const_tests/2pc_const_bool.c
# build if statement tests
mpc_test 2 ./examples/C/mpc/unit_tests/ite_tests/2pc_ite_ret_bool.c
mpc_test 2 ./examples/C/mpc/unit_tests/ite_tests/2pc_ite_ret_int.c
mpc_test 2 ./examples/C/mpc/unit_tests/ite_tests/2pc_ite_only_if.c
# build div tests
mpc_test 2 ./examples/C/mpc/unit_tests/div_tests/2pc_div.c
# build array tests
mpc_test 2 ./examples/C/mpc/unit_tests/array_tests/2pc_array_sum.c
mpc_test 2 ./examples/C/mpc/unit_tests/array_tests/2pc_array_index.c
mpc_test 2 ./examples/C/mpc/unit_tests/array_tests/2pc_array_index_2.c
# build circ/compiler array tests
mpc_test 2 ./examples/C/mpc/unit_tests/c_array_tests/2pc_array.c
mpc_test 2 ./examples/C/mpc/unit_tests/c_array_tests/2pc_array_1.c
mpc_test 2 ./examples/C/mpc/unit_tests/c_array_tests/2pc_array_2.c
mpc_test 2 ./examples/C/mpc/unit_tests/c_array_tests/2pc_array_3.c
mpc_test 2 ./examples/C/mpc/unit_tests/c_array_tests/2pc_array_sum_c.c
# build function tests
mpc_test 2 ./examples/C/mpc/unit_tests/function_tests/2pc_function_add.c
# build struct tests
mpc_test 2 ./examples/C/mpc/unit_tests/struct_tests/2pc_struct_add.c
mpc_test 2 ./examples/C/mpc/unit_tests/struct_tests/2pc_struct_array_add.c
# build matrix tests
mpc_test 2 ./examples/C/mpc/unit_tests/matrix_tests/2pc_matrix_add.c
mpc_test 2 ./examples/C/mpc/unit_tests/matrix_tests/2pc_matrix_assign_add.c
mpc_test 2 ./examples/C/mpc/unit_tests/matrix_tests/2pc_matrix_ptr_add.c
# build ptr tests
mpc_test 2 ./examples/C/mpc/unit_tests/ptr_tests/2pc_ptr_add.c
# build misc tests
mpc_test 2 ./examples/C/mpc/unit_tests/misc_tests/2pc_millionaires.c
mpc_test 2 ./examples/C/mpc/unit_tests/misc_tests/2pc_multi_var.c
# build hycc benchmarks
# mpc_test 2 ./examples/C/mpc/benchmarks/2pc_kmeans.c
# mpc_test 2 ./examples/C/mpc/benchmarks/2pc_kmeans_og.c
mpc_test 2 ./examples/C/mpc/benchmarks/2pc_biomatch.c
mpc_test 2 ./examples/C/mpc/benchmarks/2pc_kmeans.c
mpc_test 2 ./examples/C/mpc/benchmarks/2pc_kmeans_og.c
# # # build shift tests
# # mpc_test 2 ./examples/C/mpc/unit_tests/shift_tests/2pc_lhs.c
# # mpc_test 2 ./examples/C/mpc/unit_tests/shift_tests/2pc_rhs.c
# # ilp benchmarks
# # mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench_1.c
# # mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench_2.c
# # mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench_3.c
# # mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench_4.c
# # mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench_5.c
# # mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench_6.c
# # mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench_7.c
# # mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench_8.c
# # mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench_9.c
# # mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench.c
# # build arithmetic tests
# mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_add.c
# mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_sub.c
# mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_mult.c
# mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_mult_add_pub.c
# mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_mod.c
# # mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_add_unsigned.c
# mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_int_equals.c
# mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_int_greater_than.c
# mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_int_greater_equals.c
# mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_int_less_than.c
# mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_int_less_equals.c
# # # build nary arithmetic tests
# mpc_test 2 ./examples/C/mpc/unit_tests/nary_arithmetic_tests/2pc_nary_arithmetic_add.c
# # # build bitwise tests
# mpc_test 2 ./examples/C/mpc/unit_tests/bitwise_tests/2pc_bitwise_and.c
# mpc_test 2 ./examples/C/mpc/unit_tests/bitwise_tests/2pc_bitwise_or.c
# mpc_test 2 ./examples/C/mpc/unit_tests/bitwise_tests/2pc_bitwise_xor.c
# # # build boolean tests
# mpc_test 2 ./examples/C/mpc/unit_tests/boolean_tests/2pc_boolean_and.c
# mpc_test 2 ./examples/C/mpc/unit_tests/boolean_tests/2pc_boolean_or.c
# mpc_test 2 ./examples/C/mpc/unit_tests/boolean_tests/2pc_boolean_equals.c
# # # build nary boolean tests
# mpc_test 2 ./examples/C/mpc/unit_tests/nary_boolean_tests/2pc_nary_boolean_and.c
# # # build const tests
# mpc_test 2 ./examples/C/mpc/unit_tests/const_tests/2pc_const_arith.c
# mpc_test 2 ./examples/C/mpc/unit_tests/const_tests/2pc_const_bool.c
# # build if statement tests
# mpc_test 2 ./examples/C/mpc/unit_tests/ite_tests/2pc_ite_ret_bool.c
# mpc_test 2 ./examples/C/mpc/unit_tests/ite_tests/2pc_ite_ret_int.c
# mpc_test 2 ./examples/C/mpc/unit_tests/ite_tests/2pc_ite_only_if.c
# # build div tests
# mpc_test 2 ./examples/C/mpc/unit_tests/div_tests/2pc_div.c
# # build array tests
# mpc_test 2 ./examples/C/mpc/unit_tests/array_tests/2pc_array_sum.c
# mpc_test 2 ./examples/C/mpc/unit_tests/array_tests/2pc_array_index.c
# mpc_test 2 ./examples/C/mpc/unit_tests/array_tests/2pc_array_index_2.c
# # build circ/compiler array tests
# mpc_test 2 ./examples/C/mpc/unit_tests/c_array_tests/2pc_array.c
# mpc_test 2 ./examples/C/mpc/unit_tests/c_array_tests/2pc_array_1.c
# mpc_test 2 ./examples/C/mpc/unit_tests/c_array_tests/2pc_array_2.c
# mpc_test 2 ./examples/C/mpc/unit_tests/c_array_tests/2pc_array_3.c
# mpc_test 2 ./examples/C/mpc/unit_tests/c_array_tests/2pc_array_sum_c.c
# # build misc tests
# mpc_test 2 ./examples/C/mpc/2pc_millionaires.c
# # build hycc benchmarks
# mpc_test 2 ./examples/C/mpc/benchmarks/2pc_kmeans.c
# mpc_test 2 ./examples/C/mpc/benchmarks/2pc_biomatch.c
# # build shift tests
# mpc_test 2 ./examples/C/mpc/unit_tests/shift_tests/2pc_lhs.c
# mpc_test 2 ./examples/C/mpc/unit_tests/shift_tests/2pc_rhs.c
# ilp benchmarks
# mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench_1.c
# mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench_2.c
# mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench_3.c
# mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench_4.c
# mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench_5.c
# mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench_6.c
# mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench_7.c
# mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench_8.c
# mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench_9.c
# mpc_test 2 ./examples/C/mpc/ilp_benchmarks/2pc_ilp_bench.c
# mpc_test 2 ./examples/C/mpc/unit_tests/arithmetic_tests/2pc_loop_add.c

View File

@@ -47,6 +47,7 @@ mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/2pc_structs.zok
# mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/bitwise_tests/2pc_bitwise_or.zok
# mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/bitwise_tests/2pc_bitwise_xor.zok
<<<<<<< HEAD
# # build boolean tests
# mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/boolean_tests/2pc_boolean_and.zok
# mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/boolean_tests/2pc_boolean_or.zok
@@ -58,6 +59,11 @@ mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/2pc_structs.zok
# # build const tests
# mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/const_tests/2pc_const_arith.zok
# mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/const_tests/2pc_const_bool.zok
=======
# build const tests
mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/const_tests/2pc_const_arith.zok
mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/const_tests/2pc_const_bool.zok
>>>>>>> origin/aby_benchmark
# # build ite tests
# mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/ite_tests/2pc_ite_ret_bool.zok
@@ -68,14 +74,28 @@ mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/2pc_structs.zok
# mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/array_tests/2pc_array_sum.zok
# mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/array_tests/2pc_array_ret.zok
<<<<<<< HEAD
# # build mps loop tests
# mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/loop_tests/2pc_loop_sum.zok
=======
# build array tests
mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/array_tests/2pc_array_sum.zok
mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/array_tests/2pc_array_ret.zok
# build mps loop tests
mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/loop_tests/2pc_loop_sum.zok
>>>>>>> origin/aby_benchmark
# # build function tests
# mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/function_tests/2pc_function_add.zok
<<<<<<< HEAD
# # build mpc misc tests
# mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/2pc_millionaires.zok
=======
# build misc tests
mpc_test 2 ./examples/ZoKrates/mpc/2pc_millionaires.zok
>>>>>>> origin/aby_benchmark
# build shift tests
# mpc_test 2 ./examples/ZoKrates/mpc/unit_tests/shift_tests/2pc_lhs.zok

View File

@@ -1616,6 +1616,73 @@ impl std::iter::Iterator for PostOrderIter {
}
}
/// A graph representation of a Computation
#[derive(Clone)]
pub struct ComputationSubgraph {
/// List of terms in subgraph
pub nodes: TermSet,
/// Adjacency list of edges in subgraph
pub edges: TermMap<TermSet>,
/// Output leaf nodes
pub outs: TermSet,
/// Input leaf nodes
pub ins: TermSet,
}
impl Default for ComputationSubgraph {
fn default() -> Self {
Self::new()
}
}
impl ComputationSubgraph {
/// default constructor
pub fn new() -> Self {
Self {
nodes: TermSet::new(),
edges: TermMap::new(),
outs: TermSet::new(),
ins: TermSet::new(),
}
}
/// Insert nodes into ComputationSubgraph
pub fn insert_node(&mut self, node: &Term) {
if !self.nodes.contains(node) {
self.nodes.insert(node.clone());
}
}
/// Insert edges based on nodes in the subgraph
pub fn insert_edges(&mut self) {
let mut defs : FxHashSet<Term> = FxHashSet::default();
for t in self.nodes.iter() {
self.edges.insert(t.clone(), TermSet::new());
let mut flag = true;
for c in t.cs.iter() {
if self.nodes.contains(c) {
self.edges.get_mut(t).unwrap().insert(c.clone());
defs.insert(c.clone());
flag = false;
}
}
if flag{
self.ins.insert(t.clone());
}
}
// Find the leaf node in each subgraph
// TODO: defs.difference(&_uses) ?
for t in self.nodes.iter(){
if !defs.contains(t){
self.outs.insert(t.clone());
}
}
println!("Input nodes of partition: {}", self.ins.len());
println!("Output nodes of partition: {}", self.outs.len());
}
}
/// A party identifier
pub type PartyId = u8;
@@ -1876,6 +1943,18 @@ impl Computation {
terms.pop();
terms.into_iter()
}
/// Convert Computation to ComputationSubgraph
pub fn to_subgraph(&self) -> ComputationSubgraph {
let mut cg = ComputationSubgraph::new();
for a in &self.outputs {
for t in PostOrderIter::new(a.clone()) {
cg.insert_node(&t);
}
}
cg.insert_edges();
cg
}
}
#[cfg(test)]

View File

@@ -38,6 +38,7 @@ use crate::ir::term::*;
use crate::target::ilp::{variable, Expression, Ilp, Variable};
use std::{env::var, fs::File, path::Path};
use std::collections::HashMap;
/// A cost model for ABY operations and share conversions
#[derive(Debug)]
@@ -137,7 +138,7 @@ impl CostModel {
}
/// Uses an ILP to assign...
pub fn assign(c: &Computation, cm: &str) -> SharingMap {
pub fn assign(c: &ComputationSubgraph, cm: &str) -> SharingMap {
let base_dir = match cm {
"opa" => "opa",
"hycc" => "hycc",
@@ -152,15 +153,36 @@ pub fn assign(c: &Computation, cm: &str) -> SharingMap {
build_ilp(c, &costs)
}
fn build_ilp(c: &Computation, costs: &CostModel) -> SharingMap {
/// Uses an ILP to assign and abandon the outer assignments
pub fn assign_mut(c: &ComputationSubgraph, cm: &str, co: &ComputationSubgraph) -> SharingMap {
let base_dir = match cm {
"opa" => "opa",
"hycc" => "hycc",
_ => panic!("Unknown cost model type: {}", cm),
};
let p = format!(
"{}/third_party/{}/adapted_costs.json",
var("CARGO_MANIFEST_DIR").expect("Could not find env var CARGO_MANIFEST_DIR"),
base_dir
);
let costs = CostModel::from_opa_cost_file(&p);
let mut smap = build_ilp(c, &costs);
let mut trunc_smap = TermMap::new();
for node in co.nodes.clone(){
let share = smap.get_mut(&node).unwrap();
trunc_smap.insert(node, *share);
}
println!("#### Assignment cost of partition: {}", calculate_node_cost(&trunc_smap, &costs));
trunc_smap
}
fn build_ilp(c: &ComputationSubgraph, costs: &CostModel) -> SharingMap {
let mut terms: TermSet = TermSet::new();
let mut def_uses: FxHashSet<(Term, Term)> = FxHashSet::default();
for o in &c.outputs {
for t in PostOrderIter::new(o.clone()) {
terms.insert(t.clone());
for c in &t.cs {
def_uses.insert((c.clone(), t.clone()));
}
for (node, edges) in c.edges.clone() {
terms.insert(node.clone());
for c in edges.iter() {
def_uses.insert((c.clone(), node.clone()));
}
}
let terms: FxHashMap<Term, usize> =
@@ -270,6 +292,317 @@ fn build_ilp(c: &Computation, costs: &CostModel) -> SharingMap {
assignment
}
/// A simple ilp for mp testing
pub fn simple_ilp(i: f64){
let base_dir = "hycc";
let p = format!(
"{}/third_party/{}/adapted_costs.json",
var("CARGO_MANIFEST_DIR").expect("Could not find env var CARGO_MANIFEST_DIR"),
base_dir
);
let _cost = CostModel::from_opa_cost_file(&p);
let mut ilp = Ilp::new();
let v = ilp.new_variable( variable().binary(), format!("v"));
let b = ilp.new_variable( variable().binary(), format!("b"));
ilp.maximize(v+ b + i);
let (_opt, solution) = ilp.default_solve().unwrap();
println!("v: {}, {}", i, solution.get("v").unwrap());
println!("b: {}, {}", i, solution.get("b").unwrap());
}
/// Use a ILP to find a optimal combination of mutation assignments
pub fn comb_selection(mut_maps: &HashMap<usize, HashMap<usize, SharingMap>>, cs_map: &HashMap<usize, ComputationSubgraph>, cm: &str)-> HashMap<usize, SharingMap>{
let base_dir = match cm {
"opa" => "opa",
"hycc" => "hycc",
_ => panic!("Unknown cost model type: {}", cm),
};
let p = format!(
"{}/third_party/{}/adapted_costs.json",
var("CARGO_MANIFEST_DIR").expect("Could not find env var CARGO_MANIFEST_DIR"),
base_dir
);
let costs = CostModel::from_opa_cost_file(&p);
build_comb_ilp(mut_maps, cs_map, &costs)
}
/**
* Combination algo:
*
* Notations:
* - P ^ i: partitions
* - l^i_j: assignment j for P^i
* - C^i_j: inner cost (node and inner edges) of P^i with l^i_j
* - X^i_j: Assign l^i_j to P^i
* - K_{p, p'}: conversion cost from p to p'
* - v^i_{k,p}: (edge) vertex k in partition P^i with assignment p
* - B^i_{k, p}: Set of indices j such that l^i_j assign p to k
* - E_{u, w, p, p'}: cross partition edges that assign u, w with p, p' repsectively
*
* Constraints:
* - [ for any i, \sum_j X^i_j >= 1 ]: Each partition must have a assignment
* - [ for any i,k, \sum_p v^i_{k, p} >= 1 ]: Each node must have a assignment
* - [ E_{u, w, p, p'} >= v{u, p} + v{w, p'} - 1 ]: Edge is added if u and v is assigned with p and p' resp.
*
* Object:
* - min[\sum_{i, j} C^i_j X^i_j + \sum E{u,w,p,p'}K_{p, p'}]
*
*/
fn build_comb_ilp(mut_maps: &HashMap<usize, HashMap<usize, SharingMap>>, cs_map: &HashMap<usize, ComputationSubgraph>, costs: &CostModel) -> HashMap<usize, SharingMap>{
// global vars
let mut ilp = Ilp::new();
let mut x_vars: FxHashMap<(usize, usize), (Variable, f64, String)> = FxHashMap::default();
let mut v_vars: FxHashMap<(Term, ShareType), (Variable, f64, String)> = FxHashMap::default();
let mut e_vars: FxHashMap<(Term, ShareType, ShareType), (Variable, f64)> = FxHashMap::default();
let mut b_set: FxHashMap<(usize, Term, ShareType), Vec<Variable>> = FxHashMap::default();
// build variables for selection in each partition X^i_j
for (pid, smaps) in mut_maps.iter(){
let mut vars = vec![];
for (mid, maps) in smaps.iter(){
let name = format!("X_{}_{}", pid, mid);
let v = ilp.new_variable(variable().binary(), name.clone());
// TODO: update this buggy function
let map_cost = calculate_cost(&maps, costs);
x_vars.insert(
(*pid, *mid),
(v, map_cost, name)
);
vars.push(v);
}
// Sum of assignment selection is at least 1
ilp.new_constraint(
vars.into_iter()
.fold((0.0).into(), |acc: Expression, v| acc + v)
>> 1.0,
);
}
//
// build b set
// build variables for each edge node v^i_{k,p}
let mut edge_terms: FxHashSet<(usize, usize, Term)> = FxHashSet::default();
let mut def_uses: FxHashSet<(Term, Term, usize, usize)> = FxHashSet::default();
for (pid, cs) in cs_map.iter(){
let mut index: usize = 1;
for t in cs.ins.clone(){
edge_terms.insert((*pid, index, t.clone()));
index = index + 1;
// get all cross partition egdes:
for outer_node in t.cs.iter(){
def_uses.insert((outer_node.clone(), t.clone(), *pid, index));
}
}
for t in cs.outs.clone(){
edge_terms.insert((*pid, index, t.clone()));
index = index + 1;
}
}
for (pid, i, t) in edge_terms.iter(){
let mut vars = vec![];
match &t.op {
Op::Var(..) | Op::Const(_) => {
for ty in &SHARE_TYPES {
let name = format!("t_{}_{}_{}", pid, i, ty.char());
let v = ilp.new_variable(variable().binary(), name.clone());
v_vars.insert((t.clone(), *ty), (v, 0.0, name));
vars.push(v);
// TODO: add constraints for B here
let mut x_vec = vec![];
for (mid, maps) in mut_maps.get(pid).unwrap().iter(){
// buggy?
let a_ty = maps.get(t).unwrap();
if ty == a_ty{
if !b_set.contains_key(&(*pid, t.clone(), *ty)) {
b_set.insert((*pid, t.clone(), *ty), Vec::new());
}
b_set.get_mut(&(*pid, t.clone(), *ty)).unwrap().push(
x_vars.get(&(*pid, *mid)).unwrap().0
);
x_vec.push(
x_vars.get(&(*pid, *mid)).unwrap().0
);
}
}
ilp.new_constraint(
x_vec.into_iter()
.fold((0.0).into(), |acc: Expression, v| acc + v)
>> v,
);
}
}
_ => {
if let Some(costs) = costs.ops.get(&t.op) {
for (ty, cost) in costs {
let name = format!("t_{}_{}_{}", pid, i, ty.char());
let v = ilp.new_variable(variable().binary(), name.clone());
v_vars.insert((t.clone(), *ty), (v, *cost, name));
vars.push(v);
// TODO: add constraints for B here
let mut x_vec = vec![];
for (mid, maps) in mut_maps.get(pid).unwrap().iter(){
// buggy?
let a_ty = maps.get(t).unwrap();
if ty == a_ty{
if !b_set.contains_key(&(*pid, t.clone(), *ty)) {
b_set.insert((*pid, t.clone(), *ty), Vec::new());
}
b_set.get_mut(&(*pid, t.clone(), *ty)).unwrap().push(
x_vars.get(&(*pid, *mid)).unwrap().0
);
x_vec.push(
x_vars.get(&(*pid, *mid)).unwrap().0
);
}
}
ilp.new_constraint(
x_vec.into_iter()
.fold((0.0).into(), |acc: Expression, v| acc + v)
>> v,
);
}
} else {
panic!("No cost for op {}", &t.op)
}
}
}
// Sum of assignments is at least 1.
ilp.new_constraint(
vars.into_iter()
.fold((0.0).into(), |acc: Expression, v| acc + v)
>> 1.0,
);
}
// build variables for conversion
for (def, use_, pid, idx) in &def_uses {
for from_ty in &SHARE_TYPES {
for to_ty in &SHARE_TYPES {
// if def can be from_ty, and use can be to_ty
if v_vars.contains_key(&(def.clone(), *from_ty))
&& v_vars.contains_key(&(use_.clone(), *to_ty))
&& from_ty != to_ty
{
let v = ilp.new_variable(
variable().binary(),
format!("c_{}_{}_{}2{}", pid, idx, from_ty.char(), to_ty.char()),
);
e_vars.insert(
(def.clone(), *from_ty, *to_ty),
(v, *costs.conversions.get(&(*from_ty, *to_ty)).unwrap()),
);
}
}
}
}
let def_uses: FxHashMap<Term, Vec<Term>> = {
let mut t = FxHashMap::default();
for (d, u, _, _) in def_uses {
t.entry(d).or_insert_with(Vec::new).push(u);
}
t
};
for (def, uses) in def_uses {
for use_ in uses {
for from_ty in &SHARE_TYPES {
for to_ty in &SHARE_TYPES {
e_vars.get(&(def.clone(), *from_ty, *to_ty)).map(|c| {
v_vars.get(&(def.clone(), *from_ty)).map(|t_from| {
// c[term i from pi to pi'] >= t[term j with pi'] + t[term i with pi] - 1
v_vars
.get(&(use_.clone(), *to_ty))
.map(|t_to| ilp.new_constraint(c.0 >> (t_from.0 + t_to.0 - 1.0)))
})
});
}
}
}
}
ilp.maximize(
-e_vars
.values()
.map(|(a, b)| (a, b))
.chain(x_vars.values().map(|(a, b, _)| (a, b)))
.fold(0.0.into(), |acc: Expression, (v, cost)| acc + *v * *cost),
);
let (_opt, solution) = ilp.default_solve().unwrap();
let mut local_assignments: HashMap<usize, SharingMap> = HashMap::new();
for (pid, smaps) in mut_maps.iter(){
for (mid, _maps) in smaps.iter(){
let name = format!("X_{}_{}", pid, mid);
if solution.get(&name).unwrap() == &1.0{
let map = mut_maps.get(pid).unwrap().get(mid).unwrap().clone();
local_assignments.insert(*pid, map);
}
}
}
local_assignments
}
/// Calculate the cost of a global assignment
pub fn calculate_node_cost(smap: &SharingMap, costs: &CostModel) -> f64{
// remove the double counting for cost
let mut cost:f64 = 0.0;
for (t, from_ty) in smap{
match &t.op {
Op::Var(..) | Op::Const(_) => {
cost = cost + 0.0;
}
_ => {
cost = cost + costs.ops.get(&t.op).unwrap().get(from_ty).unwrap();
}
}
}
cost
}
/// Calculate the cost of a global assignment
pub fn calculate_cost(smap: &SharingMap, costs: &CostModel) -> f64{
let mut cost:f64 = 0.0;
let mut conv_cost: HashMap<(Term, ShareType), f64> = HashMap::new();
for (t, to_ty) in smap{
match &t.op {
Op::Var(..) | Op::Const(_) => {
cost = cost + 0.0;
}
_ => {
cost = cost + costs.ops.get(&t.op).unwrap().get(to_ty).unwrap();
}
}
for arg_t in &t.cs{
if smap.contains_key(&arg_t){
let from_ty = smap.get(&arg_t).unwrap();
if from_ty != to_ty{
let c = costs.conversions.get(&(*to_ty, *from_ty)).unwrap();
conv_cost.insert((arg_t.clone(), *to_ty), *c);
}
}
}
}
cost = cost + conv_cost.values().fold(0.0, |acc, &x| acc + x);
cost
}
#[cfg(test)]
mod tests {
use super::*;
@@ -319,7 +652,8 @@ mod tests {
metadata: ComputationMetadata::default(),
values: None,
};
let _assignment = build_ilp(&cs, &costs);
let cg = cs.to_subgraph();
let _assignment = build_ilp(&cg, &costs);
}
#[test]
@@ -358,7 +692,8 @@ mod tests {
metadata: ComputationMetadata::default(),
values: None,
};
let assignment = build_ilp(&cs, &costs);
let cg = cs.to_subgraph();
let assignment = build_ilp(&cg, &costs);
// Big enough to do the math with arith
assert_eq!(
&ShareType::Arithmetic,
@@ -395,7 +730,8 @@ mod tests {
metadata: ComputationMetadata::default(),
values: None,
};
let assignment = build_ilp(&cs, &costs);
let cg = cs.to_subgraph();
let assignment = build_ilp(&cg, &costs);
// All yao
assert_eq!(
&ShareType::Yao,

View File

@@ -43,8 +43,18 @@ pub fn all_boolean_sharing(c: &Computation) -> SharingMap {
.collect()
}
/// Assigns boolean sharing to all yap terms
pub fn all_yao_sharing(c: &Computation) -> SharingMap {
c.outputs
.iter()
.flat_map(|output| {
PostOrderIter::new(output.clone()).map(|term| (term, ShareType::Yao))
})
.collect()
}
/// Assigns arithmetic sharing to addition and multiplication
pub fn some_arith_sharing(c: &Computation, _cm: &str) -> SharingMap {
pub fn some_arith_sharing(c: &Computation) -> SharingMap {
c.outputs
.iter()
.flat_map(|output| {
@@ -59,3 +69,20 @@ pub fn some_arith_sharing(c: &Computation, _cm: &str) -> SharingMap {
})
.collect()
}
/// Assigns arithmetic sharing to addition and multiplication
pub fn some_arith_sharing_ay(c: &Computation) -> SharingMap {
c.outputs
.iter()
.flat_map(|output| {
PostOrderIter::new(output.clone()).map(|term| match &term.op {
Op::BvNaryOp(o) => match o {
BvNaryOp::Add => (term.clone(), ShareType::Arithmetic),
BvNaryOp::Mul => (term.clone(), ShareType::Arithmetic),
_ => (term.clone(), ShareType::Yao),
},
_ => (term.clone(), ShareType::Yao),
})
})
.collect()
}

View File

@@ -5,15 +5,20 @@
//! [Link to comment in EzPC Compiler](https://github.com/mpc-msri/EzPC/blob/da94a982709123c8186d27c9c93e27f243d85f0e/EzPC/EzPC/codegen.ml)
use crate::ir::term::*;
#[cfg(feature = "lp")]
use crate::target::aby::assignment::ilp::assign;
// #[cfg(feature = "lp")]
// use crate::target::aby::assignment::ilp::assign;
use crate::target::aby::assignment::SharingMap;
use crate::target::aby::utils::*;
use crate::target::graph::trans::get_share_map;
use std::fmt;
use std::path::Path;
#[cfg(not(feature = "lp"))]
use super::assignment::some_arith_sharing;
use super::assignment::all_boolean_sharing;
use super::assignment::some_arith_sharing_ay;
use super::assignment::all_yao_sharing;
// #[cfg(not(feature = "lp"))]
// const BOOLEAN_BITLEN: i32 = 1;
@@ -403,20 +408,25 @@ impl ToABY {
}
/// Convert this (IR) `ir` to ABY.
pub fn to_aby(ir: Computation, path: &Path, lang: &str, cm: &str) {
pub fn to_aby(ir: Computation, path: &Path, lang: &str, cm: &str, am: &str, ps: &usize) {
let Computation {
outputs: terms,
metadata: md,
..
} = ir.clone();
#[cfg(feature = "lp")]
let s_map: SharingMap = assign(&ir, cm);
#[cfg(not(feature = "lp"))]
let s_map: SharingMap = some_arith_sharing(&ir, cm);
let s_map = match am {
"all_boolean" => all_boolean_sharing(&ir),
"all_yao" => all_yao_sharing(&ir),
"boolean_arith" => some_arith_sharing(&ir),
"yao_arith" => some_arith_sharing_ay(&ir),
"ilp" => get_share_map(&ir, cm, path, lang, false, ps),
"ilp_mut" => get_share_map(&ir, cm, path, lang, true, ps),
e => {
panic!("Unsupported assignment mode: {:?}", e);
},
};
let mut converter = ToABY::new(s_map, md, path, lang);
for t in terms {
// println!("terms: {}", t);
converter.map_terms_to_shares(t.clone());

3
src/target/graph/mod.rs Normal file
View File

@@ -0,0 +1,3 @@
//! Graph partitioning backend
pub mod trans;

703
src/target/graph/trans.rs Normal file
View File

@@ -0,0 +1,703 @@
//! Translation from IR to Chaco file input format
//! This input format can be found in [Jostle User Guide](https://chriswalshaw.co.uk/jostle/jostle-exe.pdf)
//!
//!
use crate::ir::term::*;
use crate::target::aby::assignment::ilp::assign;
use crate::target::aby::assignment::ilp::assign_mut;
use crate::target::aby::assignment::ilp::calculate_cost;
use crate::target::aby::assignment::ilp::comb_selection;
use crate::target::aby::assignment::ilp::CostModel;
use crate::target::aby::assignment::SharingMap;
use std::collections::HashMap;
use std::env::var;
use std::fs;
use std::fs::File;
use std::io::prelude::*;
use std::io::{self, BufRead};
use std::path::Path;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::Instant;
use std::thread;
// use std::sync::mpsc::channel;
#[derive(Clone, PartialEq, Eq, Hash)]
struct Node {
idx: usize,
}
#[derive(Clone)]
struct Edges<T> {
vec: Vec<T>,
}
impl<T: PartialEq> Edges<T> {
fn add(&mut self, item: T) -> bool {
if !self.vec.contains(&item) {
self.vec.push(item);
return true;
}
false
}
}
struct ParitionGraph {
num_nodes: usize,
num_edges: usize,
next_idx: usize,
partition_size: usize,
num_parts: usize,
term_to_node: HashMap<Term, Node>,
node_to_term: HashMap<Node, Term>,
term_to_part: HashMap<Term, usize>,
edges: HashMap<Node, Edges<Node>>,
cs: Computation,
cm: String,
path: PathBuf,
lang: String,
graph_path: String,
part_path: String,
}
impl ParitionGraph {
fn new(partition_size: usize, cs: &Computation, cm: &str, path: &Path, lang: &str) -> Self {
let mut graph = Self {
num_nodes: 0,
num_edges: 0,
next_idx: 0,
partition_size,
num_parts: 0,
term_to_node: HashMap::new(),
node_to_term: HashMap::new(),
term_to_part: HashMap::new(),
edges: HashMap::new(),
cs: cs.clone(),
cm: cm.to_string(),
path: PathBuf::from(path),
lang: lang.to_string(),
graph_path: "".to_string(),
part_path: "".to_string(),
};
graph.init_paths();
graph
}
// Get file path to write Chaco graph to
fn get_graph_path(&self) -> String {
let filename = Path::new(&self.path.iter().last().unwrap().to_os_string())
.file_stem()
.unwrap()
.to_os_string()
.into_string()
.unwrap();
let name = format!("{}_{}", filename, self.lang);
let path = format!("scripts/aby_tests/tests/{}.graph", name);
if Path::new(&path).exists() {
fs::remove_file(&path).expect("Failed to remove old graph file");
}
path
}
// Get file path to write graph partitioning output to
fn get_part_path(&self) -> String {
let filename = Path::new(&self.path.iter().last().unwrap().to_os_string())
.file_stem()
.unwrap()
.to_os_string()
.into_string()
.unwrap();
let name = format!("{}_{}", filename, &self.lang);
let path = format!("scripts/aby_tests/tests/{}.part", name);
if Path::new(&path).exists() {
fs::remove_file(&path).expect("Failed to remove old partition file");
}
path
}
// Initialize paths to write Chaco graph and partition files
fn init_paths(&mut self) {
self.graph_path = self.get_graph_path();
self.part_path = self.get_part_path();
}
// Insert node into PartitionGraph
fn insert_node(&mut self, t: &Term) {
if !self.term_to_node.contains_key(t) {
self.next_idx += 1;
let new_node = Node { idx: self.next_idx };
self.term_to_node.insert(t.clone(), new_node.clone());
self.node_to_term.insert(new_node, t.clone());
self.num_nodes += 1;
}
}
// Insert edge into PartitionGraph
fn insert_edge(&mut self, from: &Term, to: &Term) {
self.insert_node(from);
self.insert_node(to);
let from_node = self.term_to_node.get(from).unwrap().clone();
let to_node = self.term_to_node.get(to).unwrap().clone();
if !self.edges.contains_key(&from_node) {
self.edges
.insert(from_node.clone(), Edges { vec: Vec::new() });
}
let added = self.edges.get_mut(&from_node).unwrap().add(to_node);
if added {
self.num_edges += 1;
}
}
// Write Chaco graph to file
fn write_graph(&mut self) {
if !Path::new(&self.graph_path).exists() {
println!("graph_path: {}", self.graph_path);
fs::File::create(&self.graph_path).expect("Failed to create graph file");
}
let mut file = fs::OpenOptions::new()
.write(true)
.append(true)
.open(&self.graph_path)
.expect("Failed to open graph file");
// write number of nodes and edges
file.write_all(format!("{} {}\n", self.num_nodes, self.num_edges / 2).as_bytes())
.expect("Failed to write to graph file");
// for Nodes 1..N, write their neighbors
for i in 0..(self.num_nodes) {
let node = Node { idx: i + 1 };
match self.edges.get(&node) {
Some(edges) => {
let line = edges
.vec
.clone()
.into_iter()
.map(|node| node.idx.to_string())
.collect::<Vec<String>>()
.join(" ");
file.write_all(line.as_bytes())
.expect("Failed to write to graph file");
}
None => {
let line = "";
file.write_all(line.as_bytes())
.expect("Failed to write to graph file");
}
}
file.write_all("\n".as_bytes())
.expect("Failed to write to graph file");
}
}
// Convert each node to Chaco graph representation
fn chaco_(&mut self, t: &Term) {
for c in PostOrderIter::new(t.clone()) {
match &c.op {
Op::Var(_, _) | Op::Const(_) => {
self.insert_node(&c);
}
Op::Ite
| Op::Not
| Op::Eq
| Op::BvBinOp(_)
| Op::BvNaryOp(_)
| Op::BvBinPred(_)
| Op::BoolNaryOp(_) => {
for cs in c.cs.iter() {
self.insert_edge(cs, &c);
}
for cs in c.cs.iter().rev() {
self.insert_edge(&c, cs);
}
}
_ => unimplemented!("Haven't implemented conversion of {:#?}, {:#?}", c, c.op),
}
}
}
// Convert IR to Chaco graph format
fn chaco(&mut self) {
println!("Writing IR to Chaco format");
let Computation { outputs, .. } = self.cs.clone();
for t in &outputs {
self.chaco_(t);
}
self.write_graph();
self.get_num_partitions();
}
// Determine number of partitions based on the number of terms in the Computation
fn get_num_partitions(&mut self) {
self.num_parts = self.num_nodes / self.partition_size + 1;
}
// Check if input graph is formatted correctly
fn check_graph(&self) {
//TODO: fix path
let output = Command::new("../../../../KaHIP/deploy/graphchecker")
.arg(&self.graph_path)
.stdout(Stdio::piped())
.output()
.unwrap();
let stdout = String::from_utf8(output.stdout).unwrap();
assert!(stdout.contains("The graph format seems correct."));
}
// Call graph partitioning algorithm on input graph
fn call_graph_partitioner(&self) {
//TODO: fix path
let output = Command::new("../../../../KaHIP/deploy/kaffpa")
.arg(&self.graph_path)
.arg("--k")
.arg(self.num_parts.to_string()) //TODO: make this a function on the number of terms
.arg("--preconfiguration=fast")
.arg(format!("--output_filename={}", &self.part_path))
.stdout(Stdio::piped())
.output()
.unwrap();
let stdout = String::from_utf8(output.stdout).unwrap();
println!("stdout: {}", stdout);
assert!(stdout.contains(&format!("writing partition to {}", &self.part_path)));
}
// Read a file line by line
fn read_lines<P>(&self, filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
P: AsRef<Path>,
{
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
// Partition IR graph into HashMap<usize (part), ComputationSubgraph>
fn partition_ir(&mut self) -> HashMap<usize, ComputationSubgraph> {
let mut partitions: HashMap<usize, ComputationSubgraph> = HashMap::new();
// Initialize partitions
for part in 0..self.num_parts {
partitions.insert(part, ComputationSubgraph::new());
}
if let Ok(lines) = self.read_lines(&self.part_path) {
for line in lines.into_iter().enumerate() {
if let (i, Ok(part)) = line {
let node = Node { idx: i + 1 };
let term = self.node_to_term.get(&node);
let part_num = part.parse::<usize>().unwrap();
if let Some(t) = term {
if let Some(subgraph) = partitions.get_mut(&part_num) {
subgraph.insert_node(t);
self.term_to_part.insert(t.clone(), part_num);
} else {
panic!("Subgraph not found for index: {}", part_num);
}
} else {
panic!("Node: {} - was not mapped in node_to_term map", i + 1);
}
}
}
}
// Find edges for each subgraph
let mut new_partitions: HashMap<usize, ComputationSubgraph> = HashMap::new();
for (i, mut subgraph) in partitions.into_iter() {
subgraph.insert_edges();
new_partitions.insert(i, subgraph.clone());
}
new_partitions
}
fn _get_outer(&self, cs: &ComputationSubgraph) -> ComputationSubgraph {
let mut mut_cs: ComputationSubgraph = ComputationSubgraph::new();
for node in cs.nodes.clone() {
mut_cs.insert_node(&node);
}
for node in cs.ins.clone() {
for outer_node in node.cs.iter() {
mut_cs.insert_node(&outer_node)
}
}
mut_cs.insert_edges();
mut_cs
}
fn _mutate_partitions(
&self,
cs: &HashMap<usize, ComputationSubgraph>,
) -> HashMap<usize, HashMap<usize, SharingMap>> {
// TODO: merge and stop
let mut mut_smaps: HashMap<usize, HashMap<usize, SharingMap>> = HashMap::new();
for (i, c) in cs.iter() {
mut_smaps.insert(*i, HashMap::new());
println!("#### Assignment of partition: {}, {}", i, 0);
mut_smaps.get_mut(i).unwrap().insert(0, assign(c, &self.cm));
let outer_cs_1 = self._get_outer(c);
println!("#### Assignment of partition: {}, {}", i, 1);
mut_smaps
.get_mut(i)
.unwrap()
.insert(1, assign_mut(&outer_cs_1, &self.cm, c));
let outer_cs_2 = self._get_outer(&outer_cs_1);
println!("#### Assignment of partition: {}, {}", i, 2);
mut_smaps
.get_mut(i)
.unwrap()
.insert(2, assign_mut(&outer_cs_2, &self.cm, c));
let outer_cs_3 = self._get_outer(&outer_cs_2);
println!("#### Assignment of partition: {}, {}", i, 3);
mut_smaps
.get_mut(i)
.unwrap()
.insert(3, assign_mut(&outer_cs_3, &self.cm, c));
}
mut_smaps
}
/// Mutations with multi threading
fn _mutate_partitions_mp(
&self,
cs: &HashMap<usize, ComputationSubgraph>,
) -> HashMap<usize, HashMap<usize, SharingMap>> {
// TODO: merge and stop
let mut mut_smaps: HashMap<usize, HashMap<usize, SharingMap>> = HashMap::new();
let mut mut_sets: HashMap<(usize, usize), (ComputationSubgraph, ComputationSubgraph)> = HashMap::new();
for (i, c) in cs.iter() {
mut_smaps.insert(*i, HashMap::new());
mut_sets.insert((*i, 0), (c.clone(), c.clone()));
let outer_cs_1 = self._get_outer(c);
mut_sets.insert((*i, 1), (outer_cs_1.clone(), c.clone()));
let outer_cs_2 = self._get_outer(&outer_cs_1);
mut_sets.insert((*i, 2), (outer_cs_2.clone(), c.clone()));
let outer_cs_3 = self._get_outer(&outer_cs_2);
mut_sets.insert((*i, 3), (outer_cs_3.clone(), c.clone()));
}
let mut children = vec![];
// let (tx, rx) = channel();
for ((i, j), (c, c_ref)) in mut_sets.iter(){
// let tx = tx.clone();
let cm = self.cm.clone();
let i = i.clone();
let j = j.clone();
let c = c.clone();
let c_ref = c_ref.clone();
// thread::spawn(move|| {
// tx.send((i, j, assign_mut(&c, &cm, &c_ref))).unwrap();
// });
children.push(
thread::spawn(move|| {
(i, j, assign_mut(&c, &cm, &c_ref))
})
);
}
for child in children{
let (i, j, smap) = child.join().unwrap();
mut_smaps
.get_mut(&i)
.unwrap()
.insert(j, smap);
}
// let n = mut_sets.len();
// for _ in 0..n{
// let (i, j, smap) = rx.recv().unwrap();
// mut_smaps
// .get_mut(&i)
// .unwrap()
// .insert(j, smap);
// }
mut_smaps
}
// Partition IR and get mapping
fn get_partitions(&mut self) {
self.check_graph();
self.call_graph_partitioner();
}
// Get Local Assignments for a ComputationSubgraph
fn get_local_assignments(
&self,
cs: &HashMap<usize, ComputationSubgraph>,
) -> HashMap<usize, SharingMap> {
let mut local_smaps: HashMap<usize, SharingMap> = HashMap::new();
for (i, c) in cs.iter() {
local_smaps.insert(*i, assign(c, &self.cm));
}
local_smaps
}
// fn get_mutate_local_assignments(
// &self,
// cs: &HashMap<usize, ComputationSubgraph>,
// ) -> HashMap<usize, SharingMap> {
// let mut local_smaps: HashMap<usize, SharingMap> = HashMap::new();
// for (i, c) in cs.iter() {
// local_smaps.insert(*i, assign(c, &self.cm));
// }
// local_smaps
// }
fn get_global_assignments(&self, local_smaps: &HashMap<usize, SharingMap>) -> SharingMap {
let mut global_smap: SharingMap = SharingMap::new();
let Computation { outputs, .. } = self.cs.clone();
for term_ in &outputs {
for t in PostOrderIter::new(term_.clone()) {
// get term partition assignment
let part = self.term_to_part.get(&t).unwrap();
// get local assignment
let local_share = local_smaps.get(part).unwrap().get(&t).unwrap();
// TODO: mutate local assignments ilp
// assign to global share
global_smap.insert(t.clone(), *local_share);
}
}
global_smap
}
fn _gen_all_seq(&self, ps: usize, ms: usize) -> Vec<Vec<usize>> {
println!("gen_all_seq({}, {})", ps, ms);
let mut result = Vec::new();
if ps == 1 {
let mut i = 0;
while i < ms {
let mut vec = Vec::new();
vec.push(i);
result.push(vec);
i = i + 1;
}
} else {
let prev_result = self._gen_all_seq(ps - 1, ms);
let mut i = 0;
while i < ms {
for prev in &prev_result {
let mut vec = Vec::new();
vec.push(i);
// println!("prev: {:?}", prev);
for j in prev {
vec.push(*j);
}
result.push(vec);
}
i = i + 1;
}
}
println!("gen_all_seq result: {}", result.len());
result
}
fn _brute_force(&self, cs: &HashMap<usize, HashMap<usize, SharingMap>>) -> SharingMap {
println!("Start brute forcing...");
let mut best_smap: SharingMap = SharingMap::new();
let mut cost: f64 = 0.0;
// get cost model
// let base_dir = match self.cm {
// "opa" => "opa",
// "hycc" => "hycc",
// _ => panic!("Unknown cost model type: {}", &self.cm),
// };
let p = format!(
"{}/third_party/{}/adapted_costs.json",
var("CARGO_MANIFEST_DIR").expect("Could not find env var CARGO_MANIFEST_DIR"),
"hycc"
);
let cm = CostModel::from_opa_cost_file(&p);
// get all combinations
let combs = self._gen_all_seq(self.num_parts, 4);
for comb in combs {
let mut smaps: HashMap<usize, SharingMap> = HashMap::new();
for part in 0..self.num_parts {
let mut_id = comb.get(part).unwrap();
let smap = cs.get(&part).unwrap().get(&mut_id).unwrap().clone();
smaps.insert(part, smap);
}
let global_map = self.get_global_assignments(&smaps);
let cur_cost = calculate_cost(&global_map, &cm);
// println!("Cur cost for muts: {}", cur_cost);
if cost == 0.0 {
cost = cur_cost;
best_smap = global_map;
} else {
if cur_cost < cost {
cost = cur_cost;
best_smap = global_map;
}
}
}
println!("Best cost for muts: {}", cost);
best_smap
}
}
/// Convert this (IR) constraint system `cs` to the Chaco file
/// input format.
/// Write the result to the input file path.
pub fn get_share_map(cs: &Computation, cm: &str, path: &Path, lang: &str, _mut: bool, partition_size: &usize) -> SharingMap {
let mut pg = ParitionGraph::new(*partition_size, cs, cm, path, lang);
// Convert IR to Chaco format
pg.chaco();
let before_part = Instant::now();
// Call graph partitioner on Chaco
pg.get_partitions();
// Partition IR
let partitions = pg.partition_ir();
let after_part = Instant::now();
// get local assignments
// let local_smaps = pg.get_local_assignments(&partitions);
// TODO: remove this
let p = format!(
"{}/third_party/{}/adapted_costs.json",
var("CARGO_MANIFEST_DIR").expect("Could not find env var CARGO_MANIFEST_DIR"),
"hycc"
);
let cm_ = CostModel::from_opa_cost_file(&p);
let global_assign = match _mut {
true => {
// With mutation
let before_mut = Instant::now();
// let mutation_smaps = pg._mutate_partitions(&partitions);
let mutation_smaps = pg._mutate_partitions_mp(&partitions);
let after_mut = Instant::now();
let selected_mut_maps = comb_selection(&mutation_smaps, &partitions, &cm);
let after_assign = Instant::now();
println!("Mutation time: {:?}", after_mut.duration_since(before_mut));
println!("ILP time: {:?}", after_assign.duration_since(after_mut));
pg.get_global_assignments(&selected_mut_maps)
}
false => {
// Without mutation
let before_assign = Instant::now();
let local_smaps = pg.get_local_assignments(&partitions);
let after_assign = Instant::now();
println!("ILP time: {:?}", after_assign.duration_since(before_assign));
pg.get_global_assignments(&local_smaps)
}
};
println!("Part time: {:?}", after_part.duration_since(before_part));
let cost = calculate_cost(&global_assign, &cm_);
println!("Cost of assignment: {}", cost);
global_assign
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_to_chaco() {
// Millionaire's example
let cs = Computation {
outputs: vec![term![ITE;
term![BV_ULT;
leaf_term(Op::Var("a".to_owned(), Sort::BitVector(32))),
leaf_term(Op::Var("b".to_owned(), Sort::BitVector(32)))],
leaf_term(Op::Var("a".to_owned(), Sort::BitVector(32))),
leaf_term(Op::Var("b".to_owned(), Sort::BitVector(32)))]],
metadata: ComputationMetadata::default(),
values: None,
};
let mut pg = ParitionGraph::new(2, &cs, "opa", &Path::new("test"), "c");
pg.chaco();
assert_eq!(pg.num_nodes, 4);
assert_eq!(pg.num_edges / 2, 5);
}
#[test]
fn test_gen_seq() {
let cs = Computation {
outputs: vec![term![ITE;
term![BV_ULT;
leaf_term(Op::Var("a".to_owned(), Sort::BitVector(32))),
leaf_term(Op::Var("b".to_owned(), Sort::BitVector(32)))],
leaf_term(Op::Var("a".to_owned(), Sort::BitVector(32))),
leaf_term(Op::Var("b".to_owned(), Sort::BitVector(32)))]],
metadata: ComputationMetadata::default(),
values: None,
};
let pg = ParitionGraph::new(2, &cs, "opa", &Path::new("test"), "c");
let combs = pg._gen_all_seq(5, 4);
for comb in combs {
println!("{:?}", comb);
}
}
#[test]
fn test_mp() {
// Millionaire's example
let t = true;
let cs = Computation {
outputs: vec![term![ITE;
term![BV_ULT;
leaf_term(Op::Var("a".to_owned(), Sort::BitVector(32))),
leaf_term(Op::Var("b".to_owned(), Sort::BitVector(32)))],
leaf_term(Op::Var("a".to_owned(), Sort::BitVector(32))),
leaf_term(Op::Var("b".to_owned(), Sort::BitVector(32)))]],
metadata: ComputationMetadata::default(),
values: None,
};
let mut pg = ParitionGraph::new(1, &cs, "opa", &Path::new("test"), "c");
pg.chaco();
// Call graph partitioner on Chaco
pg.get_partitions();
// Partition IR
let partitions = pg.partition_ir();
let _maps = match t{
true =>{
let mut children = vec![];
for (_, c) in partitions.iter() {
for i in 1..10000 {
let cs = c.clone();
children.push(
thread::spawn(move|| {
// simple_ilp(i as f64);
let cm = "hycc";
(i, assign_mut(&cs, cm, &cs))
})
);
}
}
let mut mut_smaps: HashMap<usize, SharingMap> = HashMap::new();
for child in children{
let (i, smap) = child.join().unwrap();
mut_smaps.insert(i, smap);
}
mut_smaps
}
false =>{
println!("HAHA\n");
let mut_smaps: HashMap<usize, SharingMap> = HashMap::new();
mut_smaps
}
};
}
}

View File

@@ -1,6 +1,7 @@
//! Target circuit representations (and lowering passes)
pub mod aby;
pub mod graph;
#[cfg(feature = "lp")]
pub mod ilp;
pub mod r1cs;