├── .gitignore ├── COPYING ├── Makefile ├── README.md ├── common.php ├── config-example.php ├── fetch-blacklist ├── generate-answers ├── import-prompts ├── public ├── backend.php ├── background-kobold.avif ├── caution.avif ├── favicon.avif ├── frontend.js └── index.xhtml └── schema.sql /.gitignore: -------------------------------------------------------------------------------- 1 | blacklist.php 2 | config.php 3 | db.sqlite* 4 | llama.cpp 5 | llama.log 6 | models 7 | prompts.json 8 | public/bootstrap.css 9 | public/deps.js 10 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | fetch-deps: public/deps.js public/bootstrap.css 2 | 3 | public/deps.js: 4 | curl "https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" "https://code.jquery.com/jquery-3.7.1.min.js" "https://raw.githubusercontent.com/cure53/DOMPurify/main/dist/purify.min.js" "https://cdn.jsdelivr.net/npm/marked/lib/marked.umd.js" "https://cdn.jsdelivr.net/npm/marked-xhtml/lib/index.umd.js" > $@.tmp 5 | mv -f $@.tmp $@ 6 | 7 | public/bootstrap.css: 8 | curl -o $@.tmp "https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" 9 | mv -f $@.tmp $@ 10 | 11 | # can be useful when generating new answers on another database. 12 | # import with $(xzcat answers.sql.xz | sqlite3 -bail db.sqlite) 13 | answers.sql.xz: db.sqlite 14 | (echo "BEGIN;"; printf ".mode insert models\nselect * from models;\n.mode insert prompts\nselect * from prompts;\n.mode insert answers\nselect * from answers;\n" | sqlite3 -init /dev/fd/0 db.sqlite; echo "COMMIT;") | sed 's/^INSERT INTO/INSERT OR IGNORE INTO/g' | xz -0v > $@.tmp 15 | mv -f $@.tmp $@ 16 | 17 | host: 18 | @echo "Starting PHP's builtin web server. Browse to http://127.0.0.1:8080/index.xhtml to see the interface." 19 | php -S 127.0.0.1:8080 -t public 20 | 21 | clean: 22 | rm -f public/deps.js public/bootstrap.css 23 | 24 | .PHONY: host clean 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # llm-eval 2 | 3 | A super simple web interface to perform blind tests on LLM outputs. Released 4 | under the Apache License, version 2.0. 5 | 6 | Dependencies: PHP, SQLite3. 7 | 8 | [**See a live demo here.**](https://freya.artefact2.com/llm-eval/) 9 | 10 | # Quickstart guide 11 | 12 | ``` 13 | git clone https://github.com/ggerganov/llama.cpp 14 | make -C llama.cpp server 15 | 16 | sqlite3 db.sqlite < schema.sql 17 | 18 | cp config{-example,}.php 19 | $EDITOR config.php 20 | 21 | # prompts.json should be an array of strings 22 | # (or populate the prompts table on your own) 23 | ./import-prompts < prompts.json 24 | 25 | # generate-answer args: 26 | # - path to model file, 27 | # - instruct prefix, 28 | # - instruct suffix, 29 | # - json array of stop sequences, 30 | # - comma-separated worker index and worker count 31 | # (or populate the answers table on your own) 32 | parallel -n1 -j1 --ungroup ./generate-answers {} '[INST]' '[/INST]' '["[/INST]"]' 10 ::: ./models/*.gguf 33 | 34 | make fetch-deps 35 | make host 36 | ``` 37 | 38 | # Updating 39 | 40 | ``` 41 | git pull 42 | 43 | # check for changes in the default configuration file 44 | git diff master@{1}..master config-example.php 45 | 46 | # check for schema updates 47 | git log --grep='^schema[,:]' --reverse master@{1}..master 48 | ``` 49 | -------------------------------------------------------------------------------- /common.php: -------------------------------------------------------------------------------- 1 | 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | if(!isset($config)) { 18 | $config = require __DIR__.'/config.php'; 19 | } 20 | 21 | function get_db(int $mode = \SQLITE3_OPEN_READWRITE) { 22 | $db = new \SQLite3(__DIR__.'/db.sqlite', $mode); 23 | $db->exec('PRAGMA busy_timeout = 15000;'); 24 | $db->exec('PRAGMA foreign_keys = 1;'); 25 | return $db; 26 | } 27 | -------------------------------------------------------------------------------- /config-example.php: -------------------------------------------------------------------------------- 1 | '', 6 | /* if you have lots of prompts, increase this to 1,2,3... etc to reduce the number of voting pairs */ 7 | 'prune_voting_pairs' => 0, 8 | /* will be passed to llama.cpp server binary */ 9 | 'server_args' => function(string $model_path): string { return '-cb -np 8 -c 32768 -ngl 999'; }, 10 | /* rate limits: array of [ num_seconds => max_requests, ... ], set to 11 | * empty array [] to disable, keep sorted in descending key order */ 12 | 'rate_limits' => [ 600 => 120, 180 => 60 ], 13 | /* returns the IP of the client, if you have a proxy you might want HTTP_X_FORWARDED_FOR here */ 14 | 'remote_addr' => function() { return $_SERVER['REMOTE_ADDR']; }, 15 | /* if the whitelist returns true, access is allowed and the blacklist is not checked. */ 16 | 'whitelist' => function(string $ip): bool { return false; }, 17 | /* if the blacklist returns true, access is denied. */ 18 | 'blacklist' => function(string $ip): bool { return false; }, 19 | /* sample blacklist implementation: blocks tor exits, vpns and datacenters 20 | * run $(./fetch-blacklist > blacklist.php) then uncomment the line below */ 21 | // 'blacklist' => require __DIR__.'/blacklist.php'; 22 | ]; 23 | -------------------------------------------------------------------------------- /fetch-blacklist: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env php 2 | 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | function is_v6(string $ip): bool { 19 | return strpos($ip, ':') !== false; 20 | } 21 | 22 | function process(string $uri, array &$list): void { 23 | $f = fopen($uri, 'rb'); 24 | while($line = fgets($f)) { 25 | $line = explode('/', trim($line)); 26 | if(count($line) === 1) { 27 | if(is_v6($line[0])) { 28 | $line[] = '128'; 29 | } else { 30 | $line[] = '32'; 31 | } 32 | } 33 | list($ip, $mask) = $line; 34 | $k = is_v6($ip) ? 'ipv6' : 'ipv4'; 35 | $ip = inet_pton($ip); 36 | if($ip === false) continue; 37 | $list[$k][$ip] = (int)$mask; 38 | } 39 | } 40 | 41 | $list = [ 'ipv4' => [], 'ipv6' => [] ]; 42 | process('https://raw.githubusercontent.com/X4BNet/lists_vpn/main/output/datacenter/ipv4.txt', $list); 43 | process('https://www.dan.me.uk/torlist/?exit', $list); 44 | ksort($list['ipv4']); 45 | ksort($list['ipv6']); 46 | 47 | echo '= $stop; --$i) {'; 52 | echo 'if($i < $bits) { $byte = intdiv($i, 8); $bit = 7 - $i%8; $ip[$byte]=chr(ord($ip[$byte]) & (~(1<<$bit))); }'; 53 | echo 'if(($list[$ip] ?? -1) === $i) return true;'; 54 | echo '}'; 55 | echo 'return false;'; 56 | echo '};'; 57 | echo 'if(strpos($ip, ":") !== false) { return $walk(inet_pton($ip), 128, 128, $list["ipv6"]); }'; 58 | echo 'else { return $walk(inet_pton($ip), 32, 10, $list["ipv4"]); }'; 59 | echo '};', PHP_EOL; 60 | -------------------------------------------------------------------------------- /generate-answers: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env php 2 | 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | require __DIR__.'/common.php'; 19 | 20 | if($argc < 5 || $argc > 6) { 21 | fprintf(STDERR, "Usage: %s [num_workers]\n", $argv[0]); 22 | die(1); 23 | } 24 | if($argc === 5) $argv[] = "1"; 25 | list(, $model_path, $prefix, $suffix, $stops, $workers) = $argv; 26 | 27 | function spawn_server(string $model_path): int { 28 | if(($pid = pcntl_fork()) > 0) { 29 | do { 30 | sleep(2); 31 | $status = @json_decode(file_get_contents('http://127.0.0.1:24498/health'), true); 32 | } while(($status['status'] ?? "error") !== "ok"); 33 | return $pid; 34 | } 35 | global $config; 36 | $server_args = $config['server_args']($model_path); 37 | passthru(escapeshellcmd(__DIR__.'/llama.cpp/server').' --host 127.0.0.1 --port 24498 -m '.escapeshellarg($model_path).' '.$server_args); 38 | die(0); 39 | } 40 | 41 | function insert_answer(int $model_id, int $prompt_id, string $answer, int $retry = 5): bool { 42 | /* get a new handle just for writing this answer. sqlite does not like 43 | * long lived connections for writing and often gets stuck in locked 44 | * states */ 45 | $dbw = get_db(); 46 | $ins_stmt = $dbw->prepare('INSERT INTO answers(prompt_id, model_id, answer) VALUES(:pid, :model, :answer);'); 47 | $ins_stmt->bindValue(':model', $model_id); 48 | $ins_stmt->bindValue(':pid', $prompt_id); 49 | $ins_stmt->bindValue(':answer', $answer); 50 | $res = $ins_stmt->execute(); 51 | $ins_stmt->close(); 52 | $dbw->close(); 53 | if($res !== false) return true; 54 | if($retry === 0) return false; 55 | sleep(1); 56 | return insert_answer($model, $prompt_id, $answer, $retry - 1); 57 | } 58 | 59 | function spawn_worker(int $model_id, int $worker_id, int $worker_count, string $prefix, string $suffix, string $stops): int { 60 | if(($pid = pcntl_fork()) > 0) return $pid; 61 | $db = $db = get_db(\SQLITE3_OPEN_READONLY); 62 | $pq = $db->prepare('SELECT prompts.prompt_id, prompt FROM prompts 63 | LEFT JOIN answers ON answers.prompt_id = prompts.prompt_id AND answers.model_id = :model 64 | WHERE MOD(prompts.prompt_id, :n) = :k AND answers.prompt_id IS NULL;'); 65 | $pq->bindValue(':model', $model_id); 66 | $pq->bindValue(':k', $worker_id); 67 | $pq->bindValue(':n', $worker_count); 68 | $prompts = $pq->execute(); 69 | while($row = $prompts->fetchArray()) { 70 | printf("\e[1m\e[33mworker %d: generating prompt_id %d\e[0m\n", $worker_id, $row['prompt_id']); 71 | $ctx = stream_context_create([ 72 | 'http' => [ 73 | 'method' => 'POST', 74 | 'timeout' => 300, 75 | 'header' => 'Content-Type: application/json', 76 | 'content' => json_encode([ 77 | 'prompt' => $prefix.$row['prompt'].$suffix, 78 | 'n_predict' => 512, 79 | 'samplers' => 'min_p', 80 | 'min_p' => 0.05, 81 | 'repeat_penalty' => 1.0, 82 | 'seed' => 42, 83 | 'stop' => $stops, 84 | ]), 85 | ], 86 | ]); 87 | $ans = file_get_contents('http://127.0.0.1:24498/completion', false, $ctx); 88 | if($ans === false) { 89 | var_dump($row); 90 | die(1); 91 | } 92 | $answer = json_decode($ans, true)['content']; 93 | if(!is_string($answer) || trim($answer) === '') break; 94 | if(insert_answer($model_id, $row['prompt_id'], $answer) === false) break; 95 | } 96 | die(0); 97 | } 98 | 99 | $model = pathinfo($model_path, \PATHINFO_FILENAME); 100 | $db = get_db(); 101 | if($db->exec('BEGIN;') === false) die(1); 102 | $mq = $db->prepare('SELECT model_id FROM models WHERE model_name = :model;'); 103 | $mq->bindValue(':model', $model); 104 | if(($mq = $mq->execute()) === false) die(1); 105 | if($mq = $mq->fetchArray()) { 106 | $model_id = $mq[0]; 107 | } else { 108 | $mq = $db->prepare('INSERT INTO models(model_name) VALUES(:model);'); 109 | $mq->bindValue(':model', $model); 110 | if($mq->execute() === false) die(1); 111 | $model_id = $db->lastInsertRowID(); 112 | } 113 | if($db->exec('COMMIT;') === false) die(1); 114 | 115 | 116 | $todo = $db->prepare('SELECT count(*) FROM prompts 117 | LEFT JOIN answers ON answers.prompt_id = prompts.prompt_id AND answers.model_id = :mid 118 | WHERE answers.prompt_id IS NULL'); 119 | $todo->bindValue(':mid', $model_id); 120 | if($todo->execute()->fetchArray()[0] === 0) { 121 | /* don't spawn the server for nothing */ 122 | die(0); 123 | } 124 | unset($mq, $todo, $db); 125 | 126 | $server_pid = spawn_server($model_path); 127 | $worker_pids = []; 128 | for($i = 0; $i < $workers; ++$i) { 129 | $worker_pids[] = spawn_worker($model_id, $i, $workers, $prefix, $suffix, $stops); 130 | } 131 | 132 | register_shutdown_function(function() { posix_kill(0, SIGKILL); }); 133 | pcntl_signal(SIGTERM, function() { die(0); }); 134 | pcntl_signal(SIGINT, function() { die(0); }); 135 | 136 | foreach($worker_pids as $p) { 137 | pcntl_waitpid($p, $status); 138 | } 139 | posix_kill($server_pid, SIGTERM); 140 | pcntl_waitpid($server_pid, $status); 141 | -------------------------------------------------------------------------------- /import-prompts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env php 2 | 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | require __DIR__.'/common.php'; 19 | 20 | $json = json_decode(file_get_contents('php://stdin'), true); 21 | $db = get_db(); 22 | 23 | if($db->exec('BEGIN IMMEDIATE;') === false) { 24 | fprintf(STDERR, "%s: could not begin immediate transaction\n", $argv[1]); 25 | die(1); 26 | } 27 | 28 | $sel_stmt = $db->prepare('SELECT prompt_id FROM prompts WHERE prompt = :prompt'); 29 | $sel_stmt->bindParam(':prompt', $prompt); 30 | $ins_stmt = $db->prepare('INSERT INTO prompts(prompt) VALUES(:prompt);'); 31 | $ins_stmt->bindParam(':prompt', $prompt); 32 | 33 | foreach($json as $prompt) { 34 | $prompt = $prompt; 35 | if($sel_stmt->execute()->fetchArray() === false) { 36 | $ins_stmt->execute(); 37 | echo '.'; 38 | } 39 | } 40 | 41 | $db->exec('COMMIT;'); 42 | echo PHP_EOL; 43 | -------------------------------------------------------------------------------- /public/backend.php: -------------------------------------------------------------------------------- 1 | 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | require realpath(__DIR__).'/../common.php'; 18 | 19 | function hmac($anything): string { 20 | global $config; 21 | if(strlen($config['hmac_secret']) < 32) { 22 | trigger_error('hmac_secret not long enough (needs at least 32 characters), update your settings.php', \E_USER_ERROR); 23 | die(1); 24 | } 25 | return hash_hmac('sha256', var_export($anything, true), $config['hmac_secret']); 26 | } 27 | 28 | function get_self_ip(): string|false { 29 | static $ip = null; 30 | if($ip !== null) return $ip; 31 | global $config; 32 | $ip = inet_pton($config['remote_addr']()); 33 | if($ip === false) return false; 34 | /* check for IPv4-mapped IPv6, some proxies use this */ 35 | if(substr($ip, 0, 12) === "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF") { 36 | $ip = substr($ip, 12); 37 | } 38 | if(strlen($ip) === 4) { 39 | /* keep 28 bits of entropy for ipv4 addresses. it's a good 40 | * balance between false positives and anonymity */ 41 | $ip = substr(hmac($ip), 0, 7); 42 | } else { 43 | /* for ipv6, keep 40 bits of the /48 */ 44 | $ip = substr(hmac(substr($ip, 0, 6)), 0, 10); 45 | } 46 | return $ip; 47 | } 48 | 49 | function get_session_id($db, $insert_if_missing = true): int|false|null { 50 | $ip = get_self_ip(); 51 | if($ip === false) return false; 52 | $ua = $_SERVER['HTTP_USER_AGENT'] ?? false; 53 | if($ua === false) return false; 54 | $ua = substr(hmac([ 55 | $_SERVER['HTTP_USER_AGENT'] ?? null, 56 | $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? null, 57 | $_SERVER['HTTP_DNT'] ?? null, 58 | ]), 0, 3); /* and 12 bits of entropy from client headers */ 59 | $sid = $db->querySingle($sql = 'SELECT session_id FROM sessions WHERE ip_addr =\''.$ip.'\' AND user_agent = \''.$ua.'\';'); 60 | if($sid === false) return false; 61 | if($sid !== null) return $sid; 62 | if($sid === null && $insert_if_missing === false) return null; 63 | if($db->exec('BEGIN IMMEDIATE;') === false) return false; 64 | $sid = $db->querySingle($sql); 65 | if($sid === false) return false; 66 | if($sid !== null) { 67 | $db->exec('ROLLBACK;'); 68 | return $sid; 69 | } 70 | if($db->exec('INSERT INTO sessions(ip_addr, user_agent, timestamp) VALUES(\''.$ip.'\', \''.$ua.'\', '.time().');') === false) { 71 | $db->exec('ROLLBACK;'); 72 | return false; 73 | } 74 | $sid = $db->lastInsertRowID(); 75 | if($sid > 0 && $db->exec('COMMIT;') !== false) { 76 | return $sid; 77 | } 78 | $db->exec('ROLLBACK;'); 79 | return false; 80 | } 81 | 82 | function should_swap(int $sid, int $pid, int $model_id_a, int $model_id_b): bool { 83 | /* deterministically returns true about 50% of the time */ 84 | return preg_match('/^[0-7]/', hmac([ $sid, $pid, $model_id_a, $model_id_b ])); 85 | } 86 | 87 | 88 | 89 | header('Content-Type: application/json'); 90 | 91 | /* should normally be overwritten */ 92 | $reply = [ 93 | 'status' => 'server-error', 94 | 'error' => 'backend did not generate a reply', 95 | ]; 96 | 97 | register_shutdown_function(function() use(&$reply, &$db) { 98 | switch($reply['status'] ?? 'server-error') { 99 | case 'ok': 100 | break; 101 | case 'client-error': 102 | header('HTTP/1.1 400 Bad Request', true, 400); 103 | break; 104 | default: 105 | header('HTTP/1.1 500 Internal Server Error', true, 500); 106 | } 107 | 108 | echo json_encode($reply); 109 | 110 | if($db ?? false) { 111 | $db->exec('PRAGMA analysis_limit=1000;'); 112 | $db->exec('PRAGMA optimize;'); 113 | } 114 | }); 115 | 116 | 117 | 118 | if($_SERVER['REQUEST_METHOD'] !== 'POST') { 119 | $reply = [ 120 | 'status' => 'client-error', 121 | 'error' => 'only POST requests are allowed', 122 | ]; 123 | die(); 124 | } 125 | 126 | 127 | 128 | if($config['whitelist']($_SERVER['REMOTE_ADDR']) === false && $config['blacklist']($_SERVER['REMOTE_ADDR']) === true) { 129 | $reply = [ 130 | 'status' => 'client-error', 131 | 'error' => 'ip has been blacklisted', 132 | ]; 133 | die(); 134 | } 135 | 136 | 137 | 138 | 139 | $ip = get_self_ip(); 140 | $db = get_db(); 141 | foreach($config['rate_limits'] as $secs => $reqs) { 142 | if($db->querySingle('SELECT COUNT(ip_hash) FROM rate_limit WHERE ip_hash=\''.$ip.'\' AND timestamp > (unixepoch() - '.$secs.');') > $reqs) { 143 | $reply = [ 144 | 'status' => 'client-error', 145 | 'error' => 'rate limit exceeded, try again in a few minutes' 146 | ]; 147 | die(); 148 | } 149 | } 150 | if($config['rate_limits'] !== []) { 151 | if($db->exec('BEGIN IMMEDIATE;') === false) { 152 | $reply = [ 153 | 'status' => 'server-error', 154 | 'error' => 'db error' 155 | ]; 156 | die(); 157 | } 158 | $db->exec('INSERT INTO rate_limit(ip_hash, timestamp) VALUES(\''.$ip.'\', unixepoch(\'subsec\'));'); 159 | reset($config['rate_limits']); 160 | $db->exec('DELETE FROM rate_limit WHERE timestamp < (unixepoch() - '.key($config['rate_limits']).');'); 161 | $db->exec('COMMIT;'); 162 | } 163 | 164 | 165 | 166 | $payload = json_decode(file_get_contents('php://input'), true); 167 | if(!is_array($payload) || !isset($payload['a'])) { 168 | $reply = [ 169 | 'status' => 'client-error', 170 | 'error' => 'payload parse error or no action specified', 171 | ]; 172 | die(); 173 | } 174 | 175 | 176 | 177 | if($payload['a'] === 'models') { 178 | $q = $db->query('SELECT model_id, model_name FROM models ORDER BY model_name ASC;'); 179 | if($q === false) { 180 | $reply = [ 181 | 'status' => 'server-error', 182 | 'error' => 'db error', 183 | ]; 184 | die(); 185 | } 186 | $reply = [ 187 | 'status' => 'ok', 188 | 'models' => [], 189 | ]; 190 | while($m = $q->fetchArray(\SQLITE3_NUM)) { 191 | $reply['models'][$m[0]] = $m[1]; 192 | } 193 | die(); 194 | } 195 | 196 | if($payload['a'] === 'get-voting-pair') { 197 | $models = $payload['models']; 198 | if(!is_array($models) || count($models) < 2) { 199 | $reply = [ 200 | 'status' => 'client-error', 201 | 'error' => 'at least 2 models must be selected', 202 | ]; 203 | die(); 204 | } 205 | $sid = get_session_id($db); 206 | if($sid === false) { 207 | $reply = [ 'status' => 'server-error', 'error' => 'failed to generate sid' ]; 208 | die(); 209 | } 210 | $models = array_map('intval', $models); 211 | if(count($models) > 2) { 212 | $mq = $db->prepare('SELECT model_id_a, model_id_b FROM results_agg WHERE model_id_a IN (SELECT value FROM json_each(:models)) AND model_id_b IN (SELECT value FROM json_each(:models)) ORDER BY n_votes, random() LIMIT 1;'); 213 | $mq->bindValue(':models', json_encode($models)); 214 | $mq = $mq->execute(); 215 | $models = []; 216 | while($row = $mq->fetchArray(\SQLITE3_NUM)) { 217 | $models[] = $row[0]; 218 | $models[] = $row[1]; 219 | } 220 | } 221 | $p = $db->prepare('SELECT session_id, prompt_id, model_id_a, model_id_b, prompt, answer_a, answer_b FROM voting_pairs WHERE session_id = :sid AND model_id_a = :ma AND model_id_b = :mb AND MOD(prompt_id, :p) = :q LIMIT 1;'); 222 | $p->bindValue(':sid', $sid); 223 | $p->bindValue(':ma', min($models)); 224 | $p->bindValue(':mb', max($models)); 225 | $p->bindValue(':p', $prune = (1<<$config['prune_voting_pairs'])); 226 | $p->bindValue(':q', rand() & ($prune-1)); 227 | $pair = $p->execute()->fetchArray(\SQLITE3_ASSOC); 228 | if(!isset($pair['prompt_id'])) { 229 | $reply = [ 'status' => 'server-error', 'error' => 'failed to fetch a voting pair' ]; 230 | die(); 231 | } 232 | 233 | if(should_swap($pair['session_id'], $pair['prompt_id'], $pair['model_id_a'], $pair['model_id_b'])) { 234 | $old = $pair['answer_a']; 235 | $pair['answer_a'] = $pair['answer_b']; 236 | $pair['answer_b'] = $old; 237 | } 238 | 239 | foreach([ 'prompt', 'answer_a', 'answer_b' ] as $k) { 240 | $pair[$k] = trim($pair[$k]); 241 | } 242 | 243 | $reply = [ 244 | 'status' => 'ok', 245 | 'pair' => $pair, 246 | 'hmac' => hmac($pair), 247 | ]; 248 | die(); 249 | } 250 | 251 | if($payload['a'] === 'submit-voting-pair') { 252 | if(hmac($payload['pair']) !== $payload['hmac']) { 253 | $reply = [ 254 | 'status' => 'client-error', 255 | 'error' => 'hmac mismatch', 256 | ]; 257 | die(); 258 | } 259 | if(get_session_id($db, false) !== $payload['pair']['session_id']) { 260 | $reply = [ 261 | 'status' => 'client-error', 262 | 'error' => 'session_id mismatch', 263 | ]; 264 | die(); 265 | } 266 | if(isset($payload['vote']) && ($swap = should_swap( 267 | $payload['pair']['session_id'], 268 | $payload['pair']['prompt_id'], 269 | $payload['pair']['model_id_a'], 270 | $payload['pair']['model_id_b']))) { 271 | $payload['vote'] = -$payload['vote']; 272 | } 273 | if($db->exec('BEGIN IMMEDIATE;') === false) { 274 | $reply = [ 'status' => 'server-error', 'error' => 'db error' ]; 275 | die(); 276 | } 277 | $stmt = $db->prepare('INSERT INTO voted_answers(session_id, prompt_id, model_id) VALUES(:sid, :pid, :ma), (:sid, :pid, :mb);'); 278 | $stmt->bindValue(':sid', $payload['pair']['session_id']); 279 | $stmt->bindValue(':pid', $payload['pair']['prompt_id']); 280 | $stmt->bindValue(':ma', $payload['pair']['model_id_a']); 281 | $stmt->bindValue(':mb', $payload['pair']['model_id_b']); 282 | if($stmt->execute() === false) { 283 | $reply = [ 'status' => 'server-error', 'error' => 'db error' ]; 284 | die(); 285 | } 286 | $stmt = $db->prepare('INSERT INTO votes(session_id, prompt_id, model_id_a, model_id_b, vote, timestamp) VALUES(:sid, :pid, :ma, :mb, :vote, :ts);'); 287 | $stmt->bindValue(':sid', $payload['pair']['session_id']); 288 | $stmt->bindValue(':pid', $payload['pair']['prompt_id']); 289 | $stmt->bindValue(':ma', $payload['pair']['model_id_a']); 290 | $stmt->bindValue(':mb', $payload['pair']['model_id_b']); 291 | $stmt->bindValue(':vote', $payload['vote']); 292 | $stmt->bindValue(':ts', time()); 293 | if($stmt->execute() === false || $db->exec('COMMIT;') === false) { 294 | $reply = [ 'status' => 'server-error', 'error' => 'db error' ]; 295 | die(); 296 | } 297 | $reply = [ 'status' => 'ok', 'swap' => $swap ]; 298 | die(); 299 | } 300 | 301 | if($payload['a'] === 'get-results-global' || $payload['a'] === 'get-results-session') { 302 | $keys = []; 303 | $data = []; 304 | if($payload['a'] === 'get-results-global') { 305 | $q = $db->query('SELECT model_id_a, model_id_b, s_votes, n_votes FROM results_agg;'); 306 | } else { 307 | $sid = get_session_id($db, false); 308 | if($sid === false) die(); 309 | if($sid === null) { 310 | $reply = [ 'status' => 'ok', 'results' => [] ]; 311 | die(); 312 | } 313 | $q = $db->query('SELECT model_id_a, model_id_b, s_votes, n_votes FROM results_per_session WHERE session_id='.$sid.';'); 314 | } 315 | while($row = $q->fetchArray(\SQLITE3_ASSOC)) { 316 | $keys[$row['model_id_a']] = true; 317 | $keys[$row['model_id_b']] = true; 318 | $data[$row['model_id_a']][$row['model_id_b']] = [ 319 | $row['s_votes'], $row['n_votes'], 320 | ]; 321 | $data[$row['model_id_b']][$row['model_id_a']] = [ 322 | -$row['s_votes'], $row['n_votes'], 323 | ]; 324 | } 325 | foreach($keys as $a => $x) { 326 | foreach($keys as $b => $x) { 327 | if(isset($data[$a][$b])) continue; 328 | $data[$a][$b] = [ 0, 0 ]; 329 | } 330 | ksort($data[$a]); 331 | } 332 | ksort($data); 333 | $reply = [ 334 | 'status' => 'ok', 335 | 'results' => $data, 336 | ]; 337 | die(); 338 | } 339 | 340 | $reply = [ 341 | 'status' => 'client-error', 342 | 'error' => 'unknown action', 343 | ]; 344 | -------------------------------------------------------------------------------- /public/background-kobold.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Artefact2/llm-eval/2261c77397d49b9dca356bbebbee0aea001f80c8/public/background-kobold.avif -------------------------------------------------------------------------------- /public/caution.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Artefact2/llm-eval/2261c77397d49b9dca356bbebbee0aea001f80c8/public/caution.avif -------------------------------------------------------------------------------- /public/favicon.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Artefact2/llm-eval/2261c77397d49b9dca356bbebbee0aea001f80c8/public/favicon.avif -------------------------------------------------------------------------------- /public/frontend.js: -------------------------------------------------------------------------------- 1 | /* Copyright 2024 Romain "Artefact2" Dal Maso 2 | * 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | 16 | let models = {}; 17 | 18 | const error_alert = message => { 19 | let div = $(document.createElement('div')); 20 | div.addClass('alert alert-danger alert-dismissible fade show mb-0'); 21 | div.append(document.createTextNode(message)); 22 | let btn = $(document.createElement('button')); 23 | btn.attr('type', 'button'); 24 | btn.addClass('btn-close'); 25 | btn.attr('data-bs-dismiss', 'alert'); 26 | div.append(btn); 27 | $("body > nav.navbar").after(div); 28 | }; 29 | 30 | const post = (params, success, complete) => { 31 | $.post({ 32 | url: 'backend.php', 33 | data: JSON.stringify(params), 34 | contentType: 'application/json; charset=utf-8', 35 | dataType: 'json', 36 | success: data => { 37 | if(!("status" in data) || data.status !== "ok") { 38 | error_alert("Backend returned an error: " + JSON.stringify(data)); 39 | return; 40 | } 41 | success(data); 42 | }, 43 | error: (jqxhr, status) => { 44 | error_alert("Backend request errored out (" + status + ": " + jqxhr.responseText + "). Open the console for more details."); 45 | console.error(jqxhr); 46 | }, 47 | complete: (jqxhr, status) => { 48 | if(complete !== undefined) complete(jqxhr, status); 49 | }, 50 | }); 51 | }; 52 | 53 | const chop_text = (text, delay, delay_inc) => { 54 | let dfrag = document.createElement('span'); 55 | let chopped = text.split(/(\p{P}|\p{Z})/u); 56 | let make_span = (delay) => { 57 | let span = document.createElement('span'); 58 | span.setAttribute('class', 'typewrite'); 59 | span.setAttribute('style', 'animation-delay: ' + delay + 'ms;'); 60 | return span; 61 | }; 62 | let span = make_span(delay); 63 | delay += delay_inc; 64 | for(let frag of chopped) { 65 | span.appendChild(document.createTextNode(frag)); 66 | if(frag.match(/^(\p{P}|\p{Z})*$/u) === null) { 67 | dfrag.appendChild(span); 68 | span = make_span(delay); 69 | delay += delay_inc; 70 | } 71 | } 72 | dfrag.appendChild(span); 73 | return [ dfrag, delay ]; 74 | }; 75 | 76 | const chop_element = (element, delay, delay_inc) => { 77 | for(let i = 0; i < element.childNodes.length; ++i) { 78 | let ch = element.childNodes[i]; 79 | if(ch.nodeType === 3) { 80 | /* text node */ 81 | let chopped = chop_text(ch.wholeText, delay, delay_inc); 82 | element.replaceChild(chopped[0], ch); 83 | delay = chopped[1]; 84 | } else if(ch.nodeType === 1) { 85 | /* element node */ 86 | ch.classList.add('typewrite'); 87 | ch.setAttribute('style', 'animation-delay: ' + delay + 'ms;'); 88 | delay = chop_element(ch, delay, delay_inc); 89 | } 90 | } 91 | return delay; 92 | }; 93 | 94 | const parse_and_sanitize_md = s => { 95 | const config = { 96 | PARSER_MEDIA_TYPE: 'application/xhtml+xml', 97 | RETURN_DOM_FRAGMENT: true, 98 | ALLOWED_TAGS: [ 99 | "a", "article", "b", "blockquote", "br", "caption", "code", "del", "details", "div", "em", 100 | "h1", "h2", "h3", "h4", "h5", "h6", "hr", "i", "img", "ins", "kbd", "li", "main", "ol", 101 | "p", "pre", "section", "span", "strike", "strong", "sub", "summary", "sup", "table", 102 | "tbody", "td", "th", "thead", "tr", "u", "ul", "#text", 103 | ], 104 | KEEP_CONTENT: true, 105 | }; 106 | let frag = DOMPurify.sanitize(marked.parse(s), config); 107 | $(frag).find('table').addClass('table table-striped'); 108 | if(frag) return frag; 109 | /* some prompts/answers have things that *look* like HTML, but are not 110 | * (eg, C++ templates like Foo), and this trips up the sanitizer. 111 | * fall back to raw text in this case. */ 112 | frag = document.createElement('div'); 113 | frag.setAttribute('style', 'white-space: pre-wrap;'); 114 | frag.textContent = s; 115 | return frag; 116 | }; 117 | 118 | const load_voting_pair = () => { 119 | let selected = $("div#model-select option").filter(':selected'); 120 | let selected_vals = []; 121 | for(let opt of selected) { 122 | selected_vals.push(opt.value); 123 | } 124 | post({ 125 | a: 'get-voting-pair', 126 | models: selected_vals, 127 | }, data => { 128 | $("div#voting-ui").data('current-pair', data); 129 | $("div#voting-ui-a, div#voting-ui-b, div#voting-ui-prompt").fadeOut(200).promise().done(() => { 130 | $("div#voting-ui-a, div#voting-ui-b, div#voting-ui-prompt").empty().fadeIn(200); 131 | $("div#voting-ui-prompt").empty().append(parse_and_sanitize_md(data.pair.prompt)); 132 | chop_element($("div#voting-ui-a").empty().append(parse_and_sanitize_md(data.pair.answer_a))[0], 0, 30); 133 | chop_element($("div#voting-ui-b").empty().append(parse_and_sanitize_md(data.pair.answer_b))[0], 0, 30); 134 | $("div#voting-ui div.overflow-y-scroll").scrollTop(0); 135 | setTimeout(() => { $("div#voting-ui button").prop('disabled', false); }, 5000); 136 | 137 | }); 138 | }, () => { 139 | setTimeout(() => { $("button#vote-skip").prop('disabled', false); }, 5000); 140 | }); 141 | }; 142 | 143 | const submit_vote = score => { 144 | $("div#voting-ui button").prop('disabled', true); 145 | if(score === undefined) { 146 | /* not actually voting, just skipping this prompt */ 147 | load_voting_pair(); 148 | return; 149 | } 150 | 151 | let outer = document.createElement('div'), spinner = document.createElement('div'), span = document.createElement('span'); 152 | spinner.setAttribute('class', 'spinner-border spinner-border'); 153 | span.setAttribute('class', 'visually-hidden'); 154 | span.appendChild(document.createTextNode('Loading...')); 155 | spinner.appendChild(span); 156 | outer.setAttribute('class', 'spinner-outer mt-2 text-center'); 157 | outer.appendChild(spinner); 158 | $("div#vote-feedback").empty().append(outer); 159 | 160 | let cpair = $("div#voting-ui").data('current-pair'); 161 | cpair.a = 'submit-voting-pair'; 162 | cpair.vote = score; 163 | post(cpair, data => { 164 | let operand, mna = models[cpair.pair.model_id_a], mnb = models[cpair.pair.model_id_b]; 165 | if(cpair.vote === -1) operand = ' > '; 166 | else if(cpair.vote === 0) operand = ' = '; 167 | else operand = ' < '; 168 | if(data.swap) { 169 | operand = mnb + operand + mna; 170 | } else { 171 | operand = mna + operand + mnb; 172 | } 173 | let alert = document.createElement('div'), strong = document.createElement('strong'); 174 | alert.setAttribute('class', 'alert alert-success'); 175 | alert.appendChild(document.createTextNode('Vote successful! ')); 176 | strong.appendChild(document.createTextNode(operand)); 177 | alert.appendChild(strong); 178 | alert.appendChild(document.createTextNode(' for prompt ' + cpair.pair.prompt_id + '.')); 179 | $("div#vote-feedback").fadeOut(200).promise().done(() => { 180 | $("div#vote-feedback").empty().append(alert).fadeIn(200); 181 | }); 182 | load_voting_pair(); 183 | }, () => { 184 | setTimeout(() => { 185 | $("div#voting-ui button").prop('disabled', false); 186 | $("div#vote-feedback > div.spinner-outer").remove(); 187 | }, 5000); 188 | }); 189 | }; 190 | 191 | const format_pairwise_cell = (element, s_votes, n_votes) => { 192 | if(n_votes === 0) { 193 | /* no data */ 194 | return; 195 | } 196 | 197 | /* get a win frequency in [0;1] */ 198 | let f = 1.0 - (s_votes/n_votes + 1.0) / 2.0; 199 | /* 99% lower bound, https://en.wikipedia.org/wiki/Standard_normal_table */ 200 | let s = 2.33 * 0.5/Math.sqrt(n_votes); 201 | 202 | let cont = document.createElement('div'), row = document.createElement('div'); 203 | cont.appendChild(row); 204 | element.appendChild(cont); 205 | cont.setAttribute('class', 'container-fluid'); 206 | row.setAttribute('class', 'row'); 207 | let pbar = document.createElement('div'); 208 | element.appendChild(pbar); 209 | pbar.setAttribute('class', 'progress-stacked'); 210 | pbar.setAttribute('style', 'height: 2px;'); 211 | 212 | let col = document.createElement('div'); 213 | row.appendChild(col); 214 | col.classList.add('col-6'); 215 | col.classList.add('ps-0'); 216 | col.classList.add('text-start'); 217 | if(f-s > 0.005) { 218 | col.textContent = (new Intl.NumberFormat(undefined, {style: "percent"})).format(f-s); 219 | col.classList.add('text-success'); 220 | if(f-s > 0.5) col.classList.add('fw-bold'); 221 | let pbe = document.createElement('div'); 222 | pbar.appendChild(pbe); 223 | pbe.setAttribute('class', 'progress-bar bg-success'); 224 | pbe.setAttribute('style', 'width: ' + (100.0 * (f-s)).toFixed(2) + '%;'); 225 | } else { 226 | col.textContent = '0%'; 227 | col.classList.add('text-body-tertiary'); 228 | } 229 | let pbe = document.createElement('div'); 230 | pbar.appendChild(pbe); 231 | pbe.setAttribute('class', 'progress-bar bg-dark'); 232 | pbe.setAttribute('style', 'width: ' + (100.0 * (1 - Math.max(0.0, f-s) - Math.max(0.0, 1-f-s))).toFixed(2) + '%;'); 233 | col = document.createElement('div'); 234 | row.appendChild(col); 235 | col.classList.add('col-6'); 236 | col.classList.add('pe-0'); 237 | col.classList.add('text-end'); 238 | if(f+s < .995) { 239 | col.textContent = (new Intl.NumberFormat(undefined, {style: "percent"})).format(1-f-s); 240 | col.classList.add('text-danger'); 241 | if(f+s < 0.5) col.classList.add('fw-bold'); 242 | let pbe = document.createElement('div'); 243 | pbar.appendChild(pbe); 244 | pbe.setAttribute('class', 'progress-bar bg-danger'); 245 | pbe.setAttribute('style', 'width: ' + (100.0 * (1-f-s)).toFixed(2) + '%;'); 246 | } else { 247 | col.textContent = '0%'; 248 | col.classList.add('text-body-tertiary'); 249 | } 250 | }; 251 | 252 | /* XXX: making a lot of assumptions here wrt model names */ 253 | const model_base_name = k => k.match(/^(.+)[-.](q|iq|f|bf)[1-8]/i)[1]; 254 | const model_quant_name = k => k.match(/(^|[-.])((q|iq|f|bf)[1-8](.*?))([-.]|$)/i)[2]; 255 | 256 | const format_pairwise_results = (element, data) => { 257 | let heading = document.createElement('h5'); 258 | element.appendChild(heading); 259 | heading.classList.add('mt-4'); 260 | heading.classList.add('pt-4'); 261 | heading.textContent = 'Pairwise preference rate (lower bound, 99% confidence)'; 262 | 263 | /* XXX: assuming all models share the same base name */ 264 | let table_name = model_base_name; 265 | let row_name = k => 'prefers ' + model_quant_name(k); 266 | let col_name = k => 'vs ' + model_quant_name(k); 267 | let table = document.createElement('table'); 268 | element.appendChild(table); 269 | table.setAttribute('data-ts', (new Date()).getTime()); 270 | table.classList.add('table'); 271 | table.classList.add('table-striped'); 272 | 273 | let thead = document.createElement('thead'); 274 | table.appendChild(thead); 275 | for(let a in data.results) { 276 | let tr = document.createElement('tr'); 277 | let th = document.createElement('th'); 278 | th.append(document.createTextNode(table_name(models[a]))); 279 | tr.appendChild(th); 280 | thead.appendChild(tr); 281 | for(let b in data.results[a]) { 282 | let th = document.createElement('th'); 283 | th.appendChild(document.createTextNode(col_name(models[b]))); 284 | tr.appendChild(th); 285 | } 286 | break; 287 | } 288 | 289 | let tbody = document.createElement('tbody'); 290 | table.appendChild(tbody); 291 | for(let a in data.results) { 292 | let tr = document.createElement('tr'); 293 | let th = document.createElement('th'); 294 | th.append(document.createTextNode(row_name(models[a]))); 295 | tr.appendChild(th); 296 | tbody.appendChild(tr); 297 | for(let b in data.results[a]) { 298 | let td = document.createElement('td'); 299 | format_pairwise_cell( 300 | td, 301 | data.results[a][b][0], 302 | data.results[a][b][1] 303 | ); 304 | tr.appendChild(td); 305 | } 306 | } 307 | }; 308 | 309 | const format_btl_results = (element, data) => { 310 | let heading = document.createElement('h5'); 311 | element.appendChild(heading); 312 | heading.textContent = 'Estimated model strength (BTL maximum likelihood estimation, 99% CI)'; 313 | 314 | let table = document.createElement('table'), 315 | tbody = document.createElement('tbody'), 316 | thead = document.createElement('thead'), 317 | tr = document.createElement('tr'), th, div; 318 | element.appendChild(table); 319 | table.appendChild(thead); 320 | table.appendChild(tbody); 321 | table.classList.add('table'); 322 | table.classList.add('table-striped'); 323 | 324 | thead.appendChild(tr); 325 | th = document.createElement('th'); 326 | tr.appendChild(th); 327 | th.classList.add('col-3'); 328 | th = document.createElement('th'); 329 | tr.appendChild(th); 330 | th.classList.add('col-1'); 331 | th = document.createElement('th'); 332 | div = document.createElement('div'); 333 | tr.appendChild(th); 334 | th.appendChild(div); 335 | th.classList.add('col-8'); 336 | div.classList.add('container'); 337 | let row = document.createElement('div'); 338 | div.appendChild(row); 339 | row.classList.add('row'); 340 | for(let e of [ [ 'Weaker', 'text-start' ], [ 'Stronger', 'text-end' ] ]) { 341 | let col = document.createElement('div'); 342 | row.appendChild(col); 343 | col.classList.add('col-6'); 344 | col.classList.add(e[1]); 345 | col.textContent = e[0]; 346 | } 347 | 348 | if($.isEmptyObject(data.results)) { 349 | tr = document.createElement('tr'); 350 | tbody.appendChild(tr); 351 | let td = document.createElement('td'); 352 | tr.appendChild(td); 353 | td.classList.add('text-body-tertiary'); 354 | td.setAttribute('colwidth', '3'); 355 | return; 356 | } 357 | 358 | /* https://en.wikipedia.org/wiki/Bradley%E2%80%93Terry_model */ 359 | const indices = Object.keys(data.results); 360 | const n = indices.length; 361 | const w = (i, j) => (-data.results[indices[i]][indices[j]][0] + data.results[indices[i]][indices[j]][1]) / 2.0; 362 | let p = Array(n).fill(1.0); 363 | for(let k = 0; k < 10; ++k) { 364 | let p2 = p.slice(0, n); 365 | for(let i = 0; i < n; ++i) { 366 | let num = 0.0, denum = 0.0; 367 | for(let j = 0; j < n; ++j) { 368 | num += w(i, j) * p[j] / (p[i] + p[j]); 369 | denum += w(j, i) / (p[i] + p[j]); 370 | } 371 | p2[i] = num/denum; 372 | } 373 | p = p2; 374 | } 375 | 376 | /* https://arxiv.org/abs/2110.03874 proposition 4.1 */ 377 | let ci = []; 378 | for(let i = 0; i < n; ++i) { 379 | let sum = 0.0; 380 | for(let j = 0; j < n; ++j) { 381 | let L = data.results[indices[i]][indices[j]][1]; 382 | let th = p[i] / p[j]; 383 | sum += L * th / Math.pow(1 + th, 2.0); 384 | } 385 | ci.push(2.58 / Math.sqrt(sum)); 386 | } 387 | let p_ci = []; 388 | for(let i = 0; i < n; ++i) { 389 | p_ci.push([ 390 | Math.exp(Math.log(p[i]) - ci[i]), 391 | Math.exp(Math.log(p[i]) + ci[i]), 392 | ]); 393 | } 394 | 395 | let max = 0.0; 396 | for(let i = 0; i < n; ++i) { 397 | if(p_ci[i][1] > max) max = p_ci[i][1]; 398 | } 399 | 400 | let i = 0; 401 | for(let a in data.results) { 402 | tr = document.createElement('tr'); 403 | tbody.appendChild(tr); 404 | th = document.createElement('th'); 405 | tr.appendChild(th); 406 | th.textContent = model_base_name(models[a]); 407 | th = document.createElement('th'); 408 | tr.appendChild(th); 409 | th.textContent = model_quant_name(models[a]); 410 | let td = document.createElement('td'); 411 | tr.appendChild(td); 412 | let pbar = document.createElement('div'); 413 | td.appendChild(pbar); 414 | td.setAttribute('class', 'align-middle'); 415 | pbar.setAttribute('class', 'progress-stacked'); 416 | let pbe = document.createElement('div'); 417 | pbar.appendChild(pbe); 418 | pbe.setAttribute('class', 'progress-bar bg-primary'); 419 | pbe.setAttribute('style', 'width: ' + (100.0 * p_ci[i][0] / max) + '%;'); 420 | pbe = document.createElement('div'); 421 | pbar.appendChild(pbe); 422 | pbe.setAttribute('class', 'progress-bar bg-primary'); 423 | pbe.setAttribute('style', 'opacity: 0.5; width: ' + (100.0 * (p_ci[i][1] - p_ci[i][0]) / max) + '%;'); 424 | ++i; 425 | } 426 | }; 427 | 428 | const show_section = (section_id, delay) => { 429 | if(delay === undefined) delay = 250; 430 | $("body > section").fadeOut(delay).promise().done(() => { 431 | $(document.getElementById(section_id)) 432 | .removeClass('d-none') 433 | .hide() 434 | .trigger('my-show') 435 | .fadeIn(delay); 436 | $("body > nav.navbar a.active").removeClass('active'); 437 | $("body > nav.navbar a[href='#" + section_id + "']").addClass('active'); 438 | }); 439 | }; 440 | 441 | const maybe_refresh_results = a => { 442 | let div = $("div#results-" + a); 443 | let table = div.find('table'); 444 | if(table.length && ((new Date()).getTime() - parseInt(table.data('ts'))) < 10000) return; 445 | let ch = div.children('div.accordion-body'); 446 | ch.fadeOut(200).promise().done(() => { 447 | ch.empty(); 448 | let spinner = document.createElement('div'), span = document.createElement('span'); 449 | spinner.setAttribute('class', 'spinner-border'); 450 | spinner.appendChild(span); 451 | span.setAttribute('class', 'visually-hidden'); 452 | span.appendChild(document.createTextNode('Loading...')); 453 | ch.empty().append(spinner); 454 | ch.fadeIn(200); 455 | post({ a: 'get-results-' + a }, data => { 456 | ch.fadeOut(200).promise().done(() => { 457 | ch.empty(); 458 | let n_votes = 0; 459 | let min_votes = Number.MAX_VALUE, min_pair; 460 | let max_votes = Number.MIN_VALUE, max_pair; 461 | let nf = new Intl.NumberFormat(); 462 | for(let ma in data.results) { 463 | for(let mb in data.results[ma]) { 464 | if(ma >= mb) continue; 465 | let n = data.results[ma][mb][1]; 466 | n_votes += data.results[ma][mb][1]; 467 | if(n > max_votes) { 468 | max_votes = n; 469 | max_pair = [ ma, mb ]; 470 | } 471 | if(n < min_votes) { 472 | min_votes = n; 473 | min_pair = [ ma, mb ]; 474 | } 475 | } 476 | } 477 | let ul = document.createElement('ul'), li = document.createElement('li'); 478 | li.textContent = 'Using aggregated data of N=' + nf.format(n_votes) + ' votes.'; 479 | ul.appendChild(li); 480 | if(n_votes > 0) { 481 | li = document.createElement('li'); 482 | li.textContent = 'Most voted model pair: ' + models[max_pair[0]] + ' vs ' + models[max_pair[1]] + ' (' + nf.format(max_votes) + ' votes).'; 483 | ul.appendChild(li); 484 | li = document.createElement('li'); 485 | li.textContent = 'Least voted model pair: ' + models[min_pair[0]] + ' vs ' + models[min_pair[1]] + ' (' + nf.format(min_votes) + ' votes).'; 486 | ul.appendChild(li); 487 | } 488 | ch[0].appendChild(ul); 489 | format_btl_results(ch[0], data); 490 | format_pairwise_results(ch[0], data); 491 | ch.fadeIn(200); 492 | }); 493 | }); 494 | }); 495 | }; 496 | 497 | 498 | 499 | $(() => { 500 | $('div#javascript-check').remove(); 501 | marked.use(markedXhtml.markedXhtml(), { breaks: true }); 502 | 503 | let disclaimer_shown = false; 504 | $("section#play").on('my-show', () => { 505 | if(disclaimer_shown === true) return; 506 | (new bootstrap.Modal('#disclaimer-modal', {})).show(); 507 | disclaimer_shown = true; 508 | 509 | let badge = $("div#model-select").closest("div.accordion-item").find("span.badge"); 510 | if(badge.find('div.spinner-border').length) { 511 | let select = $("div#model-select select"); 512 | select.on('change', () => { 513 | badge.empty(); 514 | badge.text(select.children(':selected').length + ' models selected'); 515 | }); 516 | select.empty(); 517 | for(let model_id in models) { 518 | let optn = document.createElement('option'); 519 | optn.setAttribute('value', model_id); 520 | optn.setAttribute('selected', 'selected'); 521 | optn.textContent = models[model_id]; 522 | select.append(optn); 523 | } 524 | select.prop('disabled', false); 525 | select.trigger('change'); 526 | select.next('button').prop('disabled', false); 527 | } 528 | }); 529 | 530 | $("div#model-select form").on('submit', function(e) { 531 | e.preventDefault(); 532 | $("div#voting-ui").closest("div.accordion-item").find("button.accordion-button").click(); 533 | }); 534 | 535 | $("div#voting-ui").closest("div.accordion-item").find("button.accordion-button").on('click', function(e) { 536 | if($("div#voting-ui div.spinner-border").length === 0) return; 537 | load_voting_pair(); 538 | }); 539 | $("button#vote-skip").on('click', () => { submit_vote(); }); 540 | $("button#vote-draw").on('click', () => { submit_vote(0); }); 541 | $("button#vote-a").on('click', () => { submit_vote(-1); }); 542 | $("button#vote-b").on('click', () => { submit_vote(1); }); 543 | 544 | $("section#results").on('my-show', () => { 545 | if($("section#results div.collapse.show").length) return; 546 | $("div#results-global").prev().find('button').click(); 547 | }); 548 | 549 | for(let a of [ "global", "session" ]) { 550 | (a => { 551 | let div = $("div#results-" + a); 552 | div.prev().find('button').on('click', () => { 553 | /* XXX: also fires when hiding */ 554 | maybe_refresh_results(a); 555 | }); 556 | })(a); 557 | } 558 | 559 | post({ a: 'models' }, data => { 560 | models = data.models; 561 | 562 | addEventListener("hashchange", e => { 563 | show_section(window.location.hash.substring(1)); 564 | }); 565 | if(window.location.hash.length > 1) { 566 | show_section(window.location.hash.substring(1), 0); 567 | } else { 568 | window.location.hash = "#play"; 569 | } 570 | }); 571 | }); 572 | -------------------------------------------------------------------------------- /public/index.xhtml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | llm-eval 5 | 6 | 7 | 8 | 9 | 10 |