mirror of
https://github.com/vllm-project/vllm.git
synced 2025-10-26 19:14:33 +08:00
Compare commits
1015 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 79d406e918 | |||
| abad5746a7 | |||
| e58294ddf2 | |||
| f1e15da6fe | |||
| 0097bb1829 | |||
| ea4b570483 | |||
| a41357e941 | |||
| ae96ef8fbd | |||
| 69ec3ca14c | |||
| 81d7a50f24 | |||
| 27902d42be | |||
| 56b325e977 | |||
| 3dd507083f | |||
| 0ed646b7aa | |||
| 1dab9bc8a9 | |||
| 3de6e6a30e | |||
| 966fe72141 | |||
| 62963d129e | |||
| d9e98f42e4 | |||
| 3c6325f0fc | |||
| 47f0954af0 | |||
| 7cd2ebb025 | |||
| f1c78138aa | |||
| 3a86b54fb0 | |||
| f666207161 | |||
| d830656a97 | |||
| d18bab3587 | |||
| 9831aec49f | |||
| 482045ee77 | |||
| 9d6a8daa87 | |||
| ee93f4f92a | |||
| 7c008c51a9 | |||
| 4d26d806e1 | |||
| c5832d2ae9 | |||
| 15aba081f3 | |||
| 31354e563f | |||
| 98d6682cd1 | |||
| 2c37540aa6 | |||
| 3476ed0809 | |||
| 54600709b6 | |||
| e373853e12 | |||
| c87ebc3ef9 | |||
| c4059ea54f | |||
| 8e0817c262 | |||
| 83bdcb6ac3 | |||
| 12a59959ed | |||
| dec6fc6f3b | |||
| 8893130b63 | |||
| bb60326836 | |||
| 4050d646e5 | |||
| d76084c12f | |||
| 80ca1e6a3a | |||
| 614aa51203 | |||
| af9ad46fca | |||
| 7836fdcc11 | |||
| deacb7ec44 | |||
| f5e73c9f1b | |||
| c6c240aa0a | |||
| 2be6955a3f | |||
| 9d47f64eb6 | |||
| cff6a1fec1 | |||
| bcc6a09b63 | |||
| 9def10664e | |||
| 75aa1442db | |||
| 99397da534 | |||
| 8dbfcd35bf | |||
| f7dac83d95 | |||
| 7c01f70641 | |||
| 51e971d39e | |||
| 329df38f1a | |||
| 580353da93 | |||
| ba4994443a | |||
| 906a19cdb0 | |||
| c4bca740e8 | |||
| 7f83f40dee | |||
| 54814fd85b | |||
| 7041de4384 | |||
| 6a62cb82cc | |||
| 5d2a1a9cf0 | |||
| 4bf35ed9ae | |||
| be0b3af9e0 | |||
| 2cd402e169 | |||
| b185230744 | |||
| 6a2d659d28 | |||
| b2c620230a | |||
| b90d8cd832 | |||
| 3b752a6555 | |||
| ec1ad0046c | |||
| 57f09a419c | |||
| 5932634409 | |||
| 5cbe8d155c | |||
| 0d0e3a42ac | |||
| 74d55c065b | |||
| f136da15e1 | |||
| c3dde367f1 | |||
| 64e8d2a783 | |||
| 79c92c7c8a | |||
| 736ed38849 | |||
| 365791ff81 | |||
| 691e29ecf3 | |||
| 3fd02bda51 | |||
| 98cf2ed678 | |||
| e9d32d077d | |||
| 2061f0b8a7 | |||
| 96354d6a29 | |||
| d12af207d2 | |||
| 6eabc6cb0e | |||
| 2110557dab | |||
| b9e84259e9 | |||
| 294104c3f9 | |||
| 38a1674abb | |||
| f5c8628fdc | |||
| cbc53b6b8d | |||
| c54269d967 | |||
| 5bfd1bbc98 | |||
| 6984c02a27 | |||
| 3439c5a8e3 | |||
| 6806998bf9 | |||
| 515080ad2f | |||
| 3aa7b6cf66 | |||
| dda4811591 | |||
| 82079729cc | |||
| c2a8ac75e0 | |||
| f178e56c68 | |||
| dd793d1de5 | |||
| bc34937d68 | |||
| dd248f7675 | |||
| d9b34baedd | |||
| c18ebfdd71 | |||
| 67882dbb44 | |||
| 7b99314301 | |||
| 2ce5d6688b | |||
| f23871e9ee | |||
| e9de9dd551 | |||
| ba991d5c84 | |||
| 1744cc99ba | |||
| e72dc6cb35 | |||
| c246212952 | |||
| edd5fe5fa2 | |||
| 5d4d90536f | |||
| 6c916ac8a8 | |||
| 832ea88fcb | |||
| 8c00f9c15d | |||
| 0cbc1d2b4f | |||
| ff9ddbceee | |||
| 9c62db07ed | |||
| cf90ae0123 | |||
| f5dda63eb5 | |||
| 7187507301 | |||
| f1e72cc19a | |||
| 5b15bde539 | |||
| bd620b01fb | |||
| d9a252bc8e | |||
| 67005a07bc | |||
| c35e4a3dd7 | |||
| 1f5674218f | |||
| b12518d3cf | |||
| 6c5b7af152 | |||
| 8065a7e220 | |||
| 3f3b6b2150 | |||
| a7dcc62086 | |||
| ad137cd111 | |||
| 111af1fa2c | |||
| 1b2eaac316 | |||
| 3730a1c832 | |||
| 949e49a685 | |||
| 4a30d7e3cc | |||
| e83db9e7e3 | |||
| 78687504f7 | |||
| d571ca0108 | |||
| afed90a034 | |||
| 3ee5c4bca5 | |||
| e9c2732b97 | |||
| d8714530d1 | |||
| 7d46c8d378 | |||
| da971ec7a5 | |||
| 3eea74889f | |||
| f758aed0e8 | |||
| e5150f2c28 | |||
| 59a1eb59c9 | |||
| 6820724e51 | |||
| b23ce92032 | |||
| 2bd231a7b7 | |||
| 8a173382c8 | |||
| 07feecde1a | |||
| 19091efc44 | |||
| 95db455e7f | |||
| 7879f24dcc | |||
| 13db4369d9 | |||
| 4ad7b53e59 | |||
| f0cc0e68e3 | |||
| db5ec52ad7 | |||
| 114d7270ff | |||
| 32c86e494a | |||
| 8eadcf0b90 | |||
| 5002175e80 | |||
| daef218b55 | |||
| fa9e385229 | |||
| 26e1188e51 | |||
| a3e8a05d4c | |||
| e441bad674 | |||
| 1b44aaf4e3 | |||
| 9e4e6fe207 | |||
| ab66536dbf | |||
| 728c4c8a06 | |||
| 1f12122b17 | |||
| 890d8d960b | |||
| 9e74d9d003 | |||
| 9333fb8eb9 | |||
| e2b85cf86a | |||
| 845a3f26f9 | |||
| f07d513320 | |||
| 4a6769053a | |||
| f31c1f90e3 | |||
| 3ce2c050dd | |||
| 1c0afa13c5 | |||
| d919ecc771 | |||
| e691918e3b | |||
| 81fbb3655f | |||
| 0e9164b40a | |||
| 1b8a0d71cf | |||
| bd7efe95d0 | |||
| f5bb85b435 | |||
| 28c145eb57 | |||
| e2afb03c92 | |||
| 6e2527a7cb | |||
| cdab68dcdb | |||
| d1c3d7d139 | |||
| 77490c6f2f | |||
| 48f589e18b | |||
| 348616ac4b | |||
| 15985680e2 | |||
| d74674bbd9 | |||
| 703475f6c2 | |||
| d47af2bc02 | |||
| 319ad7f1d3 | |||
| 0f0d8bc065 | |||
| 55d6361b13 | |||
| cd9c0d65d9 | |||
| 50eed24d25 | |||
| e38042d4af | |||
| 33e3b37242 | |||
| 1696efe6c9 | |||
| 6b0511a57b | |||
| a8fda4f661 | |||
| 30299a41fa | |||
| 85657b5607 | |||
| 0ce7b952f8 | |||
| 39873476f8 | |||
| 03dccc886e | |||
| a65634d3ae | |||
| 80aa7e91fc | |||
| bd43973522 | |||
| 23ec72fa03 | |||
| c2637a613b | |||
| 88407532e7 | |||
| 916d219d62 | |||
| ea3890a5f0 | |||
| 2135cacb45 | |||
| 7d19de2e9c | |||
| 94a07bbdd8 | |||
| b8d4dfff9c | |||
| 622d45128c | |||
| 51602eefd3 | |||
| 5cc50a531f | |||
| 5985e3427d | |||
| 8b82a89997 | |||
| c3c2903e72 | |||
| 1a8bfd92d5 | |||
| 847cdcca1c | |||
| e3c12bf6d2 | |||
| 3dd6853bc8 | |||
| 8f89d72090 | |||
| 99dac099ab | |||
| c4bd03c7c5 | |||
| dcbf4286af | |||
| 00e6a2dc53 | |||
| 2e02311a1b | |||
| 89ec06c33b | |||
| 9fde251bf0 | |||
| 4c2ffb28ff | |||
| 246598a6b1 | |||
| 8bab4959be | |||
| 3c4cebf751 | |||
| d8f31f2f8b | |||
| 640052b069 | |||
| 351d5e7b82 | |||
| a008629807 | |||
| 76477a93b7 | |||
| 77c87beb06 | |||
| 114332b88e | |||
| cb77ad836f | |||
| 856c990041 | |||
| c5602f0baa | |||
| f7f9c5f97b | |||
| 2c0d933594 | |||
| 774d1035e4 | |||
| 6b29d6fe70 | |||
| 0bfa1c4f13 | |||
| c81da5f56d | |||
| 68bc81703e | |||
| 5884c2b454 | |||
| 45f92c00cf | |||
| 5467ac3196 | |||
| 5d7e3d0176 | |||
| 0373e1837e | |||
| c09dade2a2 | |||
| 8ea5e44a43 | |||
| 9fb900f90c | |||
| c96fc06747 | |||
| b3376e5c76 | |||
| e69ded7d1c | |||
| 767c727a81 | |||
| 6840a71610 | |||
| 7a9cb294ae | |||
| ca3ea51bde | |||
| dc49fb892c | |||
| 18a277b52d | |||
| 8d75fe48ca | |||
| 388596c914 | |||
| baa15a9ec3 | |||
| 15063741e3 | |||
| ccdc490dda | |||
| a31cab7556 | |||
| 828da0d44e | |||
| abe855d637 | |||
| 4efff036f0 | |||
| 89c920785f | |||
| 7b0a0dfb22 | |||
| 3a6ae1d33c | |||
| 8f1729b829 | |||
| 6a7c7711a2 | |||
| 0f83ddd4d7 | |||
| 065aff6c16 | |||
| 3d33e372a1 | |||
| faf71bcd4b | |||
| f270a39537 | |||
| 51a08e7d8f | |||
| eb8fcd2666 | |||
| 5563a4dea8 | |||
| ccd4f129e8 | |||
| 02cc3b51a7 | |||
| d5b1eb081e | |||
| f0a500545f | |||
| c65146e75e | |||
| 41ca62cf03 | |||
| 974fc9b845 | |||
| fee4dcc33a | |||
| 650a4cc55e | |||
| 9ca62d8668 | |||
| 45c35f0d58 | |||
| 9ba093b4f4 | |||
| 27208be66e | |||
| 87d5abef75 | |||
| ec784b2526 | |||
| a58f24e590 | |||
| f42a006b15 | |||
| 3a434b07ed | |||
| bd0e7802e0 | |||
| 06b2550cbb | |||
| f775a07e30 | |||
| 4f0d17c05c | |||
| 10c38e3e46 | |||
| cafb8e06c5 | |||
| cbb2f59cc8 | |||
| 0ab278ca31 | |||
| 7a64d24aad | |||
| dfbe60dc62 | |||
| a66cf40b20 | |||
| f790ad3c50 | |||
| ed59a7ed23 | |||
| 044793d8df | |||
| c2d6d2f960 | |||
| 8279078e21 | |||
| b9c0605a8e | |||
| 37464a0f74 | |||
| c354072828 | |||
| f081c3ce4b | |||
| 260d119e86 | |||
| a360ff80bb | |||
| 1197e02141 | |||
| 657579113f | |||
| e9899fb7a4 | |||
| a377f0bd5e | |||
| e9d3aa04f6 | |||
| a22dea54d3 | |||
| 533c217792 | |||
| 6d21fa1cad | |||
| b35be5403f | |||
| 45a1a69b98 | |||
| 87a658c812 | |||
| 429d89720e | |||
| a9bcc7afb2 | |||
| d79d9eaaff | |||
| f758505c73 | |||
| d910816c73 | |||
| 87d41c849d | |||
| e07aff9e52 | |||
| 5bf185a1c4 | |||
| 4fbcb0f27e | |||
| 7c3604fb68 | |||
| b1c255630d | |||
| eb6c50cdc2 | |||
| eecd864388 | |||
| ae495c74ea | |||
| 4238bc82f2 | |||
| 594392d27a | |||
| 18c1f16d86 | |||
| 5bd3c65072 | |||
| 616e600e0b | |||
| dfba529b40 | |||
| 5ae5ed1e60 | |||
| 290f4ada2b | |||
| dd8de11f0a | |||
| 9ba415588a | |||
| d4f3985907 | |||
| 890aa93d27 | |||
| fbdb7b3ee2 | |||
| 1102bef219 | |||
| f17a1a8f96 | |||
| d5a1697772 | |||
| 325c119961 | |||
| 8e192ff967 | |||
| e64fde4b01 | |||
| 919770957f | |||
| 6a50f4cafa | |||
| e3470f8753 | |||
| a1242324c9 | |||
| 5eda2ea02a | |||
| 2ba80bed27 | |||
| 6066253296 | |||
| ee3eea0a1b | |||
| a36de682d4 | |||
| eb6d3c264d | |||
| 97b030005c | |||
| a3a73ab069 | |||
| 8674f9880e | |||
| c74c913bfb | |||
| 5f6d10c14c | |||
| 9b9a10d6cb | |||
| 99eff67ba9 | |||
| 14772eeb8e | |||
| 757b62c495 | |||
| e941f88584 | |||
| f12c3b5b3d | |||
| d130b573a0 | |||
| 65ae8c2c8f | |||
| c3af44722c | |||
| 1937e29848 | |||
| f0eecee610 | |||
| 943e72ca56 | |||
| 546a97ef69 | |||
| da5a0b539d | |||
| 6287537a0c | |||
| b57e6c5949 | |||
| 27ce85476e | |||
| f68470e803 | |||
| 2e9a2227ec | |||
| c0724fc915 | |||
| 86b45ae065 | |||
| c5711ef985 | |||
| 48d5985a08 | |||
| 33e0823de5 | |||
| 26148120b3 | |||
| 0150a10630 | |||
| 8e7fb5d43a | |||
| 9a31a817a8 | |||
| 2060e93659 | |||
| 8435b207af | |||
| 10fa9eea21 | |||
| e08188081b | |||
| b5853f9963 | |||
| f09edd8a25 | |||
| 6979ade384 | |||
| 9216b9cc38 | |||
| 5e0391c040 | |||
| dbc0754ddf | |||
| 99caa49106 | |||
| 5c342570d7 | |||
| 973617ae02 | |||
| 30e754390c | |||
| 52f8107cf2 | |||
| fc0d9dfc3a | |||
| 361c461a12 | |||
| a5675d348b | |||
| e9cdd2b1e2 | |||
| 65bf2ac165 | |||
| 8a7cc254a0 | |||
| 29bc01bf3b | |||
| 676a99982f | |||
| dc72402b57 | |||
| ccb63a8245 | |||
| c579b750a0 | |||
| 4bfa7e7f75 | |||
| ac1fbf7fd2 | |||
| 33d3914b1e | |||
| 1356df53bd | |||
| ce532ff45c | |||
| 8bc68e198c | |||
| 0fca3cdcf2 | |||
| e7c46b9527 | |||
| 350f9e107f | |||
| 702bee461f | |||
| a7be4d0072 | |||
| a709e87a4f | |||
| 6eaccb7353 | |||
| e254497b66 | |||
| 4e12131089 | |||
| fcc2994be6 | |||
| 2e7796f2cf | |||
| 706588a77d | |||
| 6a0f617210 | |||
| dac6a3f6ed | |||
| 64b77dfd7e | |||
| 51d4094fda | |||
| e965d46184 | |||
| 208b71bcc1 | |||
| c833101740 | |||
| 379da6dcb5 | |||
| ebce310b74 | |||
| be0c5180ac | |||
| cea64430f6 | |||
| a3c124570a | |||
| ff5abcd746 | |||
| 0ee535b294 | |||
| 190bc838e1 | |||
| f12b20decc | |||
| 16bc0a098f | |||
| e288df0632 | |||
| 8b9241be3a | |||
| f942efb5a3 | |||
| 89579a201f | |||
| 230c4b38c1 | |||
| 20cfcdec99 | |||
| ad932a221d | |||
| 5510cf0e8a | |||
| 0f9a6e3d22 | |||
| f6a593093a | |||
| d7740ea4dc | |||
| cc466a3290 | |||
| 8344f7742b | |||
| 469f85c782 | |||
| 10760da800 | |||
| 478aed5827 | |||
| 63575bc2e1 | |||
| a98187cf72 | |||
| bd99d22629 | |||
| 19cb4716ee | |||
| e186d37cb1 | |||
| 323f27b904 | |||
| 0650e5935b | |||
| c7f2cf2b7f | |||
| 8d8357c8ed | |||
| 4302987069 | |||
| 021b1a2ab7 | |||
| 2a052011ca | |||
| 36fb68f947 | |||
| bc8ad68455 | |||
| 344bf7cd2d | |||
| ab50275111 | |||
| 43c413ec57 | |||
| f8e7adda21 | |||
| 7e65477e5e | |||
| 3521ba4f25 | |||
| 2d7bce9cd5 | |||
| ce3f1eedf8 | |||
| 808632d3b4 | |||
| 344a5d0c33 | |||
| 0f8a91401c | |||
| 9b5c9f9484 | |||
| 32881f3f31 | |||
| 5b8a7c1cb0 | |||
| 1ff0c73a79 | |||
| 5ad60b0cbd | |||
| fb087af52e | |||
| 7038e8b803 | |||
| 2a85f93007 | |||
| cf8cac8c70 | |||
| 5e401bce17 | |||
| 0d62fe58db | |||
| b8afa8b95a | |||
| 826b82a260 | |||
| c9d852d601 | |||
| 6ef09b08f8 | |||
| 3a922c1e7e | |||
| c47ba4aaa9 | |||
| 24bb4fe432 | |||
| a657bfc48a | |||
| 24750f4cad | |||
| b38e42fbca | |||
| 8b798eec75 | |||
| 69909126a7 | |||
| e491c7e053 | |||
| 4dc8026d86 | |||
| a88bb9b032 | |||
| 6f1df80436 | |||
| d6f4bd7cdd | |||
| c3845d82dc | |||
| a822eb3413 | |||
| f458112e8a | |||
| 2e240c69a9 | |||
| ee37328da0 | |||
| 6ad58f42c5 | |||
| dd1a50a8bc | |||
| 715c2d854d | |||
| a494140433 | |||
| 111815d482 | |||
| b31a1fb63c | |||
| 4bb53e2dde | |||
| 26f2fb5113 | |||
| fa32207842 | |||
| d627a3d837 | |||
| f4f921b7f1 | |||
| ac5ccf0156 | |||
| 73c8d677e5 | |||
| df29793dc7 | |||
| 03dd7d52bf | |||
| bf480c5302 | |||
| 9c7306ac11 | |||
| 4ea1f9678d | |||
| ba4be44c32 | |||
| d6e520e170 | |||
| 81661da7b2 | |||
| dfea173148 | |||
| 7134303cbb | |||
| 3da24c2df7 | |||
| eefeb16464 | |||
| 18d23f642a | |||
| 87f545ba6f | |||
| 8947bc3c15 | |||
| 12628d3c78 | |||
| 258a2c58d0 | |||
| aba47be3fe | |||
| a62aaf1df5 | |||
| 603ad84815 | |||
| a88081bf76 | |||
| 2f30e7c72f | |||
| a74dee9b62 | |||
| cf29b7eda4 | |||
| efffb63f58 | |||
| 15e7c675b0 | |||
| b6dcb4d442 | |||
| b5b4a398a7 | |||
| f4bc4de1b1 | |||
| bd7a8eef25 | |||
| 7ee82bef1e | |||
| fbf152d976 | |||
| 479d69fad0 | |||
| 96e90fdeb3 | |||
| a395a638c2 | |||
| 2768884ac4 | |||
| aae08249ac | |||
| 7923dcad12 | |||
| 3cd9b5bb2d | |||
| 468d761b32 | |||
| e4bf860a54 | |||
| 91f50a6fe2 | |||
| 79a268c4ab | |||
| eace8bf0b9 | |||
| 1e8f4252aa | |||
| 2b7949c1c2 | |||
| 62b5166bd4 | |||
| d86285a4a4 | |||
| d87f39e9a9 | |||
| d3c8180ac4 | |||
| 62b8aebc6f | |||
| 050f285ff6 | |||
| 8f2ea22bde | |||
| 0ae11f78ab | |||
| 34128a697e | |||
| c1b4e4157c | |||
| ceaf4ed003 | |||
| ad8d696a99 | |||
| 3d925165f2 | |||
| 1543680691 | |||
| 077f0a2e8a | |||
| e73ed0f1c6 | |||
| 296cdf8ac7 | |||
| 747b1a7147 | |||
| 95e5b087cf | |||
| a37d815b83 | |||
| 7f2593b164 | |||
| fe7d648fe5 | |||
| cc74b2b232 | |||
| 91528575ec | |||
| a22cdea371 | |||
| 682789d402 | |||
| 138485a82d | |||
| bc9df1571b | |||
| 15b86408a8 | |||
| 7be4f5628f | |||
| 8f20fc04bf | |||
| 221d93ecbf | |||
| d17c8477f1 | |||
| a134ef6f5e | |||
| 8a7a3e4436 | |||
| 8f9c28fd40 | |||
| cd2f63fb36 | |||
| 87fa80c91f | |||
| e1bb2fd52d | |||
| 705578ae14 | |||
| e8cc7967ff | |||
| 53b018edcb | |||
| 66ded03067 | |||
| 6dc1fc9cfe | |||
| 533d2a1f39 | |||
| a53222544c | |||
| fe3b5bbc23 | |||
| 8438e0569e | |||
| 11d652bd4f | |||
| d150e4f89f | |||
| e95cd87959 | |||
| 69e1d2fb69 | |||
| 05434764cd | |||
| 4e7ee664e2 | |||
| 37e84a403d | |||
| 4695397dcf | |||
| d619ae2d19 | |||
| eb46fbfda2 | |||
| 0003e9154b | |||
| e11e200736 | |||
| 8db1bf32f8 | |||
| aceb17cf2d | |||
| 563c54f760 | |||
| 2cd6b4f362 | |||
| 711a000255 | |||
| 989ae2538d | |||
| 0a430b4ae2 | |||
| ec8e3c695f | |||
| 98afde19fc | |||
| 5c2e66e487 | |||
| 546e721168 | |||
| b8aacac31a | |||
| d04973ad54 | |||
| fbb9d9eef4 | |||
| 09473ee41c | |||
| d4ec9ffb95 | |||
| 96b6a6d790 | |||
| 36729bac13 | |||
| 7fd3949a0b | |||
| 1096717ae9 | |||
| c2b4a1bce9 | |||
| e46a60aa4c | |||
| 1e96c3341a | |||
| 95e7d4a97c | |||
| 559eb852f8 | |||
| a10d3056da | |||
| 8afca50889 | |||
| 08ccee1e83 | |||
| c1dc547129 | |||
| f3d0bf7589 | |||
| e9da5a40c6 | |||
| e42df7227d | |||
| caada5e50a | |||
| 67b4221a61 | |||
| 63e7176f26 | |||
| 934d3662f7 | |||
| 92cd2e2f21 | |||
| e4c4072c94 | |||
| e35397468f | |||
| 8b317c6dd0 | |||
| bd3c144e0b | |||
| 0258b7a94b | |||
| b3104b2a10 | |||
| c2e00af523 | |||
| c013d32c75 | |||
| 11dd6ebb89 | |||
| 6c0b04515f | |||
| e23a43aef8 | |||
| e7c7067b45 | |||
| 6d592eb430 | |||
| d036198e23 | |||
| 59a6abf3c9 | |||
| bc0c0192d1 | |||
| f46864d68d | |||
| b4543c8f6b | |||
| 0ce0539d47 | |||
| 2f19283549 | |||
| 95baec828f | |||
| e4be7d70bb | |||
| 54951ac4bf | |||
| 18de883489 | |||
| 1d7c940d74 | |||
| cfaf49a167 | |||
| 9edec652e2 | |||
| e0dd4d3589 | |||
| e5043a3e75 | |||
| d03d64fd2e | |||
| 78107fa091 | |||
| c391e4b68e | |||
| 9117f892f0 | |||
| db2a6a41e2 | |||
| ca81ff5196 | |||
| b7782002e1 | |||
| 819a309c0f | |||
| aabe8f40f2 | |||
| 498eb5cfa3 | |||
| 537ee25f43 | |||
| 294f8f6665 | |||
| b95047f2da | |||
| 2ff767b513 | |||
| 3dcb3e8b98 | |||
| c64cf38673 | |||
| 76b889bf1d | |||
| c9b506dad4 | |||
| 5757d90e26 | |||
| a3c226e7eb | |||
| b321d4881b | |||
| ad6eca408b | |||
| 205b94942e | |||
| 3bec41f41a | |||
| 0739b1947f | |||
| 77a6572aa5 | |||
| 0e3f06fe9c | |||
| eb69d68804 | |||
| 7d4e1b85e7 | |||
| 93deb0b38f | |||
| ccb58b23e6 | |||
| 49782fcb76 | |||
| f03cc667a0 | |||
| 563c1d7ec5 | |||
| 9c82a1bec3 | |||
| b6d103542c | |||
| 51c31bc10c | |||
| 3ad438c66f | |||
| 203d4f82ac | |||
| 991143cfcd | |||
| 8b2d3cbc1b | |||
| 9765b5c406 | |||
| 430530fc18 | |||
| 97356f3c7e | |||
| f510395bbf | |||
| 6110c39dc8 | |||
| d8658c8cc1 | |||
| 7bc94a0fdd | |||
| 756b30a5f3 | |||
| 395aa823ea | |||
| 26422e477b | |||
| f342153b48 | |||
| 27a57cad52 | |||
| 98a42e7078 | |||
| 0267fef52a | |||
| 4716a32dd4 | |||
| c0935c96d3 | |||
| cb40b3ab6b | |||
| 515386ef3c | |||
| a4075cba4d | |||
| 96aa014d1e | |||
| 1715056fef | |||
| b51c1cc9d2 | |||
| ce567a2926 | |||
| d6ea427f04 | |||
| 14ccd94c89 | |||
| 8267b06c30 | |||
| 3492859b68 | |||
| 098e1776ba | |||
| 10e6322283 | |||
| 6d9aa00fc4 | |||
| 1182607e18 | |||
| 45b6ef6513 | |||
| 1956931436 | |||
| e24336b5a7 | |||
| d18f4e73f3 | |||
| 82c540bebf | |||
| 8f44facddd | |||
| e66b629c04 | |||
| 76879342a3 | |||
| 566b57c5c4 | |||
| 0dc72273b8 | |||
| a979d9771e | |||
| 8af890a865 | |||
| dfeb2ecc3a | |||
| 3a243095e5 | |||
| 64172a976c | |||
| f408d05c52 | |||
| 0b4997e05c | |||
| c13ad1b7bd | |||
| 819924e749 | |||
| 01bfb22b41 | |||
| e67c295b0c | |||
| 925f3332ca | |||
| b0dfa91dd7 | |||
| 56a8652f33 | |||
| 6d93d35308 | |||
| 837e185142 | |||
| 42bc386129 | |||
| 8b268a46a7 | |||
| 41deac4a3d | |||
| af9e53496f | |||
| f8a12ecc7f | |||
| 3c5ab9b811 | |||
| 743a0b7402 | |||
| bfdb1ba5c3 | |||
| cf2f084d56 | |||
| f721096d48 | |||
| e90fc21f2e | |||
| ea5f14e6ff | |||
| b7050ca7df | |||
| c188ecb080 | |||
| 865732342b | |||
| 4c07dd28c0 | |||
| 3bbff9e5ab | |||
| 6ebd02bdef | |||
| 523e30ea0c | |||
| f1c0fc3919 | |||
| 6e435de766 | |||
| 426ec4ec67 | |||
| 80e254834d | |||
| ba8ae1d84f | |||
| 84eaa68425 | |||
| 5ee14494e4 | |||
| 4ad521d8b5 | |||
| 9474e89ba4 | |||
| 20478c4d3a | |||
| 63e8b28a99 | |||
| cc63d03fbb | |||
| 2a60c9bd17 | |||
| c614cfee58 | |||
| 7341c77d69 | |||
| ef65dcfa6f | |||
| 6a9c583e73 | |||
| b37cdce2b1 | |||
| b30880a762 | |||
| 49eedea373 | |||
| 9fdf3de346 | |||
| c0c17d4896 | |||
| 097aa0ea22 | |||
| 482b0adf1b | |||
| 8c654c045f | |||
| 9101d832e6 | |||
| 93348d9458 | |||
| abfc4f3387 | |||
| 6b78837b29 | |||
| 120157fd2a | |||
| 8e67598aa6 | |||
| ad50bf4b25 | |||
| cf6ff18246 | |||
| 14e3f9a1b2 | |||
| 3123f15138 | |||
| 413366e9a2 | |||
| 10585e035e | |||
| fb96c1e98c | |||
| 8fa7357f2d | |||
| a7af4538ca | |||
| 604f235937 | |||
| 14b8ae02e7 | |||
| 03d37f2441 | |||
| a7c871680e | |||
| 429284dc37 | |||
| 253a98078a | |||
| 21539e6856 | |||
| b522c4476f | |||
| 78b6c4845a | |||
| b983ba35bd | |||
| 54be8a0be2 | |||
| dfc77408bd | |||
| c17ca8ef18 | |||
| 06ec486794 | |||
| 8fe8386591 | |||
| a37415c31b | |||
| 81653d9688 | |||
| eeab52a4ff | |||
| c33afd89f5 | |||
| 7e9bd08f60 | |||
| ae0ccb4017 | |||
| 739c350c19 | |||
| ba8dc958a3 | |||
| e221910e77 | |||
| b167109ba1 | |||
| 602358f8a8 | |||
| 49a3c8662b | |||
| b0925b3878 | |||
| 654865e21d | |||
| c9415c19d3 | |||
| 4c922709b6 | |||
| 657061fdce | |||
| 2f8844ba08 | |||
| 4b59f00e91 | |||
| 9e8744a545 | |||
| e4a28e5316 | |||
| 0bba88df03 | |||
| 8437bae6ef | |||
| f48c6791b7 | |||
| c2c5e0909a | |||
| 1cb0cc2975 | |||
| 99c3cfb83c | |||
| 1ece1ae829 | |||
| c59e120c55 | |||
| d2339d6840 | |||
| b35cc93420 | |||
| 8cbba4622c | |||
| 385da2dae2 | |||
| 2daf23ab0c | |||
| cbf4c05b15 | |||
| d3c04b6a39 | |||
| 4cb3b924cd | |||
| a33ce60c66 | |||
| 24aecf421a | |||
| 2efce05dc3 | |||
| 8999ec3c16 | |||
| 05af6da8d9 | |||
| 9a4548bae7 | |||
| ff578cae54 | |||
| 22de45235c | |||
| 76e8a70476 | |||
| 9cbc7e5f3b | |||
| 27a7b070db | |||
| 901cf4c52b | |||
| d0fae88114 | |||
| 17c3103c56 | |||
| 996d095c54 | |||
| d65fac2738 | |||
| ce4f5a29fb | |||
| baee28c46c | |||
| 29e70e3e88 |
36
.buildkite/check-wheel-size.py
Normal file
36
.buildkite/check-wheel-size.py
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
import os
|
||||||
|
import zipfile
|
||||||
|
|
||||||
|
MAX_SIZE_MB = 200
|
||||||
|
|
||||||
|
|
||||||
|
def print_top_10_largest_files(zip_file):
|
||||||
|
with zipfile.ZipFile(zip_file, 'r') as z:
|
||||||
|
file_sizes = [(f, z.getinfo(f).file_size) for f in z.namelist()]
|
||||||
|
file_sizes.sort(key=lambda x: x[1], reverse=True)
|
||||||
|
for f, size in file_sizes[:10]:
|
||||||
|
print(f"{f}: {size/(1024*1024)} MBs uncompressed.")
|
||||||
|
|
||||||
|
|
||||||
|
def check_wheel_size(directory):
|
||||||
|
for root, _, files in os.walk(directory):
|
||||||
|
for f in files:
|
||||||
|
if f.endswith(".whl"):
|
||||||
|
wheel_path = os.path.join(root, f)
|
||||||
|
wheel_size = os.path.getsize(wheel_path)
|
||||||
|
wheel_size_mb = wheel_size / (1024 * 1024)
|
||||||
|
if wheel_size_mb > MAX_SIZE_MB:
|
||||||
|
print(
|
||||||
|
f"Wheel {wheel_path} is too large ({wheel_size_mb} MB) "
|
||||||
|
f"compare to the allowed size ({MAX_SIZE_MB} MB).")
|
||||||
|
print_top_10_largest_files(wheel_path)
|
||||||
|
return 1
|
||||||
|
else:
|
||||||
|
print(f"Wheel {wheel_path} is within the allowed size "
|
||||||
|
f"({wheel_size_mb} MB).")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import sys
|
||||||
|
sys.exit(check_wheel_size(sys.argv[1]))
|
||||||
14
.buildkite/download-images.sh
Normal file
14
.buildkite/download-images.sh
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
set -o pipefail
|
||||||
|
|
||||||
|
(which wget && which curl) || (apt-get update && apt-get install -y wget curl)
|
||||||
|
|
||||||
|
# aws s3 sync s3://air-example-data-2/vllm_opensource_llava/ images/
|
||||||
|
mkdir -p images
|
||||||
|
cd images
|
||||||
|
wget https://air-example-data-2.s3.us-west-2.amazonaws.com/vllm_opensource_llava/stop_sign.jpg
|
||||||
|
wget https://air-example-data-2.s3.us-west-2.amazonaws.com/vllm_opensource_llava/cherry_blossom.jpg
|
||||||
|
|
||||||
|
cd -
|
||||||
@ -0,0 +1,11 @@
|
|||||||
|
# bash .buildkite/lm-eval-harness/run-lm-eval-gsm-hf-baseline.sh -m meta-llama/Meta-Llama-3-70B-Instruct -b 32 -l 250 -f 5
|
||||||
|
model_name: "meta-llama/Meta-Llama-3-70B-Instruct"
|
||||||
|
tasks:
|
||||||
|
- name: "gsm8k"
|
||||||
|
metrics:
|
||||||
|
- name: "exact_match,strict-match"
|
||||||
|
value: 0.892
|
||||||
|
- name: "exact_match,flexible-extract"
|
||||||
|
value: 0.892
|
||||||
|
limit: 250
|
||||||
|
num_fewshot: 5
|
||||||
@ -0,0 +1,11 @@
|
|||||||
|
# bash .buildkite/lm-eval-harness/run-lm-eval-gsm-hf-baseline.sh -m neuralmagic/Meta-Llama-3-8B-Instruct-FP8 -b 32 -l 250 -f 5 -t 1
|
||||||
|
model_name: "neuralmagic/Meta-Llama-3-8B-Instruct-FP8"
|
||||||
|
tasks:
|
||||||
|
- name: "gsm8k"
|
||||||
|
metrics:
|
||||||
|
- name: "exact_match,strict-match"
|
||||||
|
value: 0.756
|
||||||
|
- name: "exact_match,flexible-extract"
|
||||||
|
value: 0.752
|
||||||
|
limit: 250
|
||||||
|
num_fewshot: 5
|
||||||
@ -0,0 +1,11 @@
|
|||||||
|
# bash .buildkite/lm-eval-harness/run-lm-eval-gsm-hf-baseline.sh -m meta-llama/Meta-Llama-3-8B-Instruct -b 32 -l 250 -f 5 -t 1
|
||||||
|
model_name: "meta-llama/Meta-Llama-3-8B-Instruct"
|
||||||
|
tasks:
|
||||||
|
- name: "gsm8k"
|
||||||
|
metrics:
|
||||||
|
- name: "exact_match,strict-match"
|
||||||
|
value: 0.756
|
||||||
|
- name: "exact_match,flexible-extract"
|
||||||
|
value: 0.752
|
||||||
|
limit: 250
|
||||||
|
num_fewshot: 5
|
||||||
@ -0,0 +1,11 @@
|
|||||||
|
# bash ./run-lm-eval-gsm-vllm-baseline.sh -m neuralmagic/Mixtral-8x22B-Instruct-v0.1-FP8-dynamic -b "auto" -l 250 -f 5 -t 8
|
||||||
|
model_name: "neuralmagic/Mixtral-8x22B-Instruct-v0.1-FP8-dynamic"
|
||||||
|
tasks:
|
||||||
|
- name: "gsm8k"
|
||||||
|
metrics:
|
||||||
|
- name: "exact_match,strict-match"
|
||||||
|
value: 0.86
|
||||||
|
- name: "exact_match,flexible-extract"
|
||||||
|
value: 0.86
|
||||||
|
limit: 250
|
||||||
|
num_fewshot: 5
|
||||||
@ -0,0 +1,11 @@
|
|||||||
|
# bash ./run-lm-eval-gsm-vllm-baseline.sh -m neuralmagic/Mixtral-8x7B-Instruct-v0.1-FP8 -b "auto" -l 250 -f 5 -t 4
|
||||||
|
model_name: "neuralmagic/Mixtral-8x7B-Instruct-v0.1-FP8"
|
||||||
|
tasks:
|
||||||
|
- name: "gsm8k"
|
||||||
|
metrics:
|
||||||
|
- name: "exact_match,strict-match"
|
||||||
|
value: 0.624
|
||||||
|
- name: "exact_match,flexible-extract"
|
||||||
|
value: 0.624
|
||||||
|
limit: 250
|
||||||
|
num_fewshot: 5
|
||||||
@ -0,0 +1,11 @@
|
|||||||
|
# bash .buildkite/lm-eval-harness/run-lm-eval-gsm-hf-baseline.sh -m neuralmagic/Mixtral-8x7B-Instruct-v0.1 -b 32 -l 250 -f 5 -t 4
|
||||||
|
model_name: "mistralai/Mixtral-8x7B-Instruct-v0.1"
|
||||||
|
tasks:
|
||||||
|
- name: "gsm8k"
|
||||||
|
metrics:
|
||||||
|
- name: "exact_match,strict-match"
|
||||||
|
value: 0.616
|
||||||
|
- name: "exact_match,flexible-extract"
|
||||||
|
value: 0.632
|
||||||
|
limit: 250
|
||||||
|
num_fewshot: 5
|
||||||
@ -0,0 +1,11 @@
|
|||||||
|
# bash ./run-lm-eval-gsm-vllm-baseline.sh -m Qwen/Qwen2-57B-A14B-Instruct -b "auto" -l 250 -f 5 -t 4
|
||||||
|
model_name: "Qwen/Qwen2-57B-A14B-Instruct"
|
||||||
|
tasks:
|
||||||
|
- name: "gsm8k"
|
||||||
|
metrics:
|
||||||
|
- name: "exact_match,strict-match"
|
||||||
|
value: 0.792
|
||||||
|
- name: "exact_match,flexible-extract"
|
||||||
|
value: 0.824
|
||||||
|
limit: 250
|
||||||
|
num_fewshot: 5
|
||||||
3
.buildkite/lm-eval-harness/configs/models-large.txt
Normal file
3
.buildkite/lm-eval-harness/configs/models-large.txt
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
Meta-Llama-3-70B-Instruct.yaml
|
||||||
|
Mixtral-8x7B-Instruct-v0.1.yaml
|
||||||
|
Qwen2-57B-A14-Instruct.yaml
|
||||||
2
.buildkite/lm-eval-harness/configs/models-small.txt
Normal file
2
.buildkite/lm-eval-harness/configs/models-small.txt
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
Meta-Llama-3-8B-Instruct.yaml
|
||||||
|
Meta-Llama-3-8B-Instruct-FP8.yaml
|
||||||
46
.buildkite/lm-eval-harness/run-lm-eval-gsm-hf-baseline.sh
Normal file
46
.buildkite/lm-eval-harness/run-lm-eval-gsm-hf-baseline.sh
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# We can use this script to compute baseline accuracy on GSM for transformers.
|
||||||
|
#
|
||||||
|
# Make sure you have lm-eval-harness installed:
|
||||||
|
# pip install git+https://github.com/EleutherAI/lm-evaluation-harness.git@9516087b81a61d0e220b22cc1b75be76de23bc10
|
||||||
|
|
||||||
|
usage() {
|
||||||
|
echo``
|
||||||
|
echo "Runs lm eval harness on GSM8k using huggingface transformers."
|
||||||
|
echo "This pathway is intended to be used to create baselines for "
|
||||||
|
echo "our automated nm-test-accuracy workflow"
|
||||||
|
echo
|
||||||
|
echo "usage: ${0} <options>"
|
||||||
|
echo
|
||||||
|
echo " -m - huggingface stub or local directory of the model"
|
||||||
|
echo " -b - batch size to run the evaluation at"
|
||||||
|
echo " -l - limit number of samples to run"
|
||||||
|
echo " -f - number of fewshot samples to use"
|
||||||
|
echo
|
||||||
|
}
|
||||||
|
|
||||||
|
while getopts "m:b:l:f:" OPT; do
|
||||||
|
case ${OPT} in
|
||||||
|
m )
|
||||||
|
MODEL="$OPTARG"
|
||||||
|
;;
|
||||||
|
b )
|
||||||
|
BATCH_SIZE="$OPTARG"
|
||||||
|
;;
|
||||||
|
l )
|
||||||
|
LIMIT="$OPTARG"
|
||||||
|
;;
|
||||||
|
f )
|
||||||
|
FEWSHOT="$OPTARG"
|
||||||
|
;;
|
||||||
|
\? )
|
||||||
|
usage
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
lm_eval --model hf \
|
||||||
|
--model_args pretrained=$MODEL,parallelize=True \
|
||||||
|
--tasks gsm8k --num_fewshot $FEWSHOT --limit $LIMIT \
|
||||||
|
--batch_size $BATCH_SIZE
|
||||||
51
.buildkite/lm-eval-harness/run-lm-eval-gsm-vllm-baseline.sh
Normal file
51
.buildkite/lm-eval-harness/run-lm-eval-gsm-vllm-baseline.sh
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# We can use this script to compute baseline accuracy on GSM for vllm.
|
||||||
|
# We use this for fp8, which HF does not support.
|
||||||
|
#
|
||||||
|
# Make sure you have lm-eval-harness installed:
|
||||||
|
# pip install lm-eval==0.4.2
|
||||||
|
|
||||||
|
usage() {
|
||||||
|
echo``
|
||||||
|
echo "Runs lm eval harness on GSM8k using huggingface transformers."
|
||||||
|
echo "This pathway is intended to be used to create baselines for "
|
||||||
|
echo "our automated nm-test-accuracy workflow"
|
||||||
|
echo
|
||||||
|
echo "usage: ${0} <options>"
|
||||||
|
echo
|
||||||
|
echo " -m - huggingface stub or local directory of the model"
|
||||||
|
echo " -b - batch size to run the evaluation at"
|
||||||
|
echo " -l - limit number of samples to run"
|
||||||
|
echo " -f - number of fewshot samples to use"
|
||||||
|
echo " -t - tensor parallel size to run at"
|
||||||
|
echo
|
||||||
|
}
|
||||||
|
|
||||||
|
while getopts "m:b:l:f:t:" OPT; do
|
||||||
|
case ${OPT} in
|
||||||
|
m )
|
||||||
|
MODEL="$OPTARG"
|
||||||
|
;;
|
||||||
|
b )
|
||||||
|
BATCH_SIZE="$OPTARG"
|
||||||
|
;;
|
||||||
|
l )
|
||||||
|
LIMIT="$OPTARG"
|
||||||
|
;;
|
||||||
|
f )
|
||||||
|
FEWSHOT="$OPTARG"
|
||||||
|
;;
|
||||||
|
t )
|
||||||
|
TP_SIZE="$OPTARG"
|
||||||
|
;;
|
||||||
|
\? )
|
||||||
|
usage
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
lm_eval --model vllm \
|
||||||
|
--model_args pretrained=$MODEL,tensor_parallel_size=$TP_SIZE \
|
||||||
|
--tasks gsm8k --num_fewshot $FEWSHOT --limit $LIMIT \
|
||||||
|
--batch_size $BATCH_SIZE
|
||||||
59
.buildkite/lm-eval-harness/run-tests.sh
Normal file
59
.buildkite/lm-eval-harness/run-tests.sh
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
usage() {
|
||||||
|
echo``
|
||||||
|
echo "Runs lm eval harness on GSM8k using vllm and compares to "
|
||||||
|
echo "precomputed baseline (measured by HF transformers.)"
|
||||||
|
echo
|
||||||
|
echo "usage: ${0} <options>"
|
||||||
|
echo
|
||||||
|
echo " -c - path to the test data config (e.g. configs/small-models.txt)"
|
||||||
|
echo " -t - tensor parallel size"
|
||||||
|
echo
|
||||||
|
}
|
||||||
|
|
||||||
|
SUCCESS=0
|
||||||
|
|
||||||
|
while getopts "c:t:" OPT; do
|
||||||
|
case ${OPT} in
|
||||||
|
c )
|
||||||
|
CONFIG="$OPTARG"
|
||||||
|
;;
|
||||||
|
t )
|
||||||
|
TP_SIZE="$OPTARG"
|
||||||
|
;;
|
||||||
|
\? )
|
||||||
|
usage
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# Parse list of configs.
|
||||||
|
IFS=$'\n' read -d '' -r -a MODEL_CONFIGS < $CONFIG
|
||||||
|
|
||||||
|
for MODEL_CONFIG in "${MODEL_CONFIGS[@]}"
|
||||||
|
do
|
||||||
|
LOCAL_SUCCESS=0
|
||||||
|
|
||||||
|
echo "=== RUNNING MODEL: $MODEL_CONFIG WITH TP SIZE: $TP_SIZE==="
|
||||||
|
|
||||||
|
export LM_EVAL_TEST_DATA_FILE=$PWD/configs/${MODEL_CONFIG}
|
||||||
|
export LM_EVAL_TP_SIZE=$TP_SIZE
|
||||||
|
pytest -s test_lm_eval_correctness.py || LOCAL_SUCCESS=$?
|
||||||
|
|
||||||
|
if [[ $LOCAL_SUCCESS == 0 ]]; then
|
||||||
|
echo "=== PASSED MODEL: ${MODEL_CONFIG} ==="
|
||||||
|
else
|
||||||
|
echo "=== FAILED MODEL: ${MODEL_CONFIG} ==="
|
||||||
|
fi
|
||||||
|
|
||||||
|
SUCCESS=$((SUCCESS + LOCAL_SUCCESS))
|
||||||
|
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ "${SUCCESS}" -eq "0" ]; then
|
||||||
|
exit 0
|
||||||
|
else
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
54
.buildkite/lm-eval-harness/test_lm_eval_correctness.py
Normal file
54
.buildkite/lm-eval-harness/test_lm_eval_correctness.py
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
"""
|
||||||
|
LM eval harness on model to compare vs HF baseline computed offline.
|
||||||
|
Configs are found in configs/$MODEL.yaml
|
||||||
|
|
||||||
|
* export LM_EVAL_TEST_DATA_FILE=configs/Meta-Llama-3-70B-Instruct.yaml
|
||||||
|
* export LM_EVAL_TP_SIZE=4
|
||||||
|
* pytest -s test_lm_eval_correctness.py
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import lm_eval
|
||||||
|
import numpy
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
RTOL = 0.02
|
||||||
|
TEST_DATA_FILE = os.environ.get(
|
||||||
|
"LM_EVAL_TEST_DATA_FILE",
|
||||||
|
".buildkite/lm-eval-harness/configs/Meta-Llama-3-8B-Instruct.yaml")
|
||||||
|
|
||||||
|
TP_SIZE = os.environ.get("LM_EVAL_TP_SIZE", 1)
|
||||||
|
|
||||||
|
|
||||||
|
def launch_lm_eval(eval_config):
|
||||||
|
model_args = f"pretrained={eval_config['model_name']}," \
|
||||||
|
f"tensor_parallel_size={TP_SIZE}"
|
||||||
|
|
||||||
|
results = lm_eval.simple_evaluate(
|
||||||
|
model="vllm",
|
||||||
|
model_args=model_args,
|
||||||
|
tasks=[task["name"] for task in eval_config["tasks"]],
|
||||||
|
num_fewshot=eval_config["num_fewshot"],
|
||||||
|
limit=eval_config["limit"],
|
||||||
|
batch_size="auto")
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
def test_lm_eval_correctness():
|
||||||
|
eval_config = yaml.safe_load(
|
||||||
|
Path(TEST_DATA_FILE).read_text(encoding="utf-8"))
|
||||||
|
|
||||||
|
# Launch eval requests.
|
||||||
|
results = launch_lm_eval(eval_config)
|
||||||
|
|
||||||
|
# Confirm scores match ground truth.
|
||||||
|
for task in eval_config["tasks"]:
|
||||||
|
for metric in task["metrics"]:
|
||||||
|
ground_truth = metric["value"]
|
||||||
|
measured_value = results["results"][task["name"]][metric["name"]]
|
||||||
|
print(f'{task["name"]} | {metric["name"]}: '
|
||||||
|
f'ground_truth={ground_truth} | measured={measured_value}')
|
||||||
|
assert numpy.isclose(ground_truth, measured_value, rtol=RTOL)
|
||||||
103
.buildkite/nightly-benchmarks/README.md
Normal file
103
.buildkite/nightly-benchmarks/README.md
Normal file
@ -0,0 +1,103 @@
|
|||||||
|
# vLLM benchmark suite
|
||||||
|
|
||||||
|
## Introduction
|
||||||
|
|
||||||
|
This directory contains the performance benchmarking CI for vllm.
|
||||||
|
The goal is to help developers know the impact of their PRs on the performance of vllm.
|
||||||
|
|
||||||
|
This benchmark will be *triggered* upon:
|
||||||
|
- A PR being merged into vllm.
|
||||||
|
- Every commit for those PRs with `perf-benchmarks` label.
|
||||||
|
|
||||||
|
**Benchmarking Coverage**: latency, throughput and fix-qps serving on A100 (the support for more GPUs is comming later), with different models.
|
||||||
|
|
||||||
|
**Benchmarking Duration**: about 1hr.
|
||||||
|
|
||||||
|
**For benchmarking developers**: please try your best to constraint the duration of benchmarking to less than 1.5 hr so that it won't take forever to run.
|
||||||
|
|
||||||
|
|
||||||
|
## Configuring the workload
|
||||||
|
|
||||||
|
The benchmarking workload contains three parts:
|
||||||
|
- Latency tests in `latency-tests.json`.
|
||||||
|
- Throughput tests in `throughput-tests.json`.
|
||||||
|
- Serving tests in `serving-tests.json`.
|
||||||
|
|
||||||
|
See [descriptions.md](tests/descriptions.md) for detailed descriptions.
|
||||||
|
|
||||||
|
### Latency test
|
||||||
|
|
||||||
|
Here is an example of one test inside `latency-tests.json`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"test_name": "latency_llama8B_tp1",
|
||||||
|
"parameters": {
|
||||||
|
"model": "meta-llama/Meta-Llama-3-8B",
|
||||||
|
"tensor_parallel_size": 1,
|
||||||
|
"load_format": "dummy",
|
||||||
|
"num_iters_warmup": 5,
|
||||||
|
"num_iters": 15
|
||||||
|
}
|
||||||
|
},
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
In this example:
|
||||||
|
- The `test_name` attributes is a unique identifier for the test. In `latency-tests.json`, it must start with `latency_`.
|
||||||
|
- The `parameters` attribute control the command line arguments to be used for `benchmark_latency.py`. Note that please use underline `_` instead of the dash `-` when specifying the command line arguments, and `run-benchmarks-suite.sh` will convert the underline to dash when feeding the arguments to `benchmark_latency.py`. For example, the corresponding command line arguments for `benchmark_latency.py` will be `--model meta-llama/Meta-Llama-3-8B --tensor-parallel-size 1 --load-format dummy --num-iters-warmup 5 --num-iters 15`
|
||||||
|
|
||||||
|
Note that the performance numbers are highly sensitive to the value of the parameters. Please make sure the parameters are set correctly.
|
||||||
|
|
||||||
|
WARNING: The benchmarking script will save json results by itself, so please do not configure `--output-json` parameter in the json file.
|
||||||
|
|
||||||
|
|
||||||
|
### Throughput test
|
||||||
|
The tests are specified in `throughput-tests.json`. The syntax is similar to `latency-tests.json`, except for that the parameters will be fed forward to `benchmark_throughput.py`.
|
||||||
|
|
||||||
|
The number of this test is also stable -- a slight change on the value of this number might vary the performance numbers by a lot.
|
||||||
|
|
||||||
|
### Serving test
|
||||||
|
We test the throughput by using `benchmark_serving.py` with request rate = inf to cover the online serving overhead. The corresponding parameters are in `serving-tests.json`, and here is an example:
|
||||||
|
|
||||||
|
```
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"test_name": "serving_llama8B_tp1_sharegpt",
|
||||||
|
"qps_list": [1, 4, 16, "inf"],
|
||||||
|
"server_parameters": {
|
||||||
|
"model": "meta-llama/Meta-Llama-3-8B",
|
||||||
|
"tensor_parallel_size": 1,
|
||||||
|
"swap_space": 16,
|
||||||
|
"disable_log_stats": "",
|
||||||
|
"disable_log_requests": "",
|
||||||
|
"load_format": "dummy"
|
||||||
|
},
|
||||||
|
"client_parameters": {
|
||||||
|
"model": "meta-llama/Meta-Llama-3-8B",
|
||||||
|
"backend": "vllm",
|
||||||
|
"dataset_name": "sharegpt",
|
||||||
|
"dataset_path": "./ShareGPT_V3_unfiltered_cleaned_split.json",
|
||||||
|
"num_prompts": 200
|
||||||
|
}
|
||||||
|
},
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
Inside this example:
|
||||||
|
- The `test_name` attribute is also a unique identifier for the test. It must start with `serving_`.
|
||||||
|
- The `server-parameters` includes the command line arguments for vLLM server.
|
||||||
|
- The `client-parameters` includes the command line arguments for `benchmark_serving.py`.
|
||||||
|
- The `qps_list` controls the list of qps for test. It will be used to configure the `--request-rate` parameter in `benchmark_serving.py`
|
||||||
|
|
||||||
|
The number of this test is less stable compared to the delay and latency benchmarks (due to randomized sharegpt dataset sampling inside `benchmark_serving.py`), but a large change on this number (e.g. 5% change) still vary the output greatly.
|
||||||
|
|
||||||
|
WARNING: The benchmarking script will save json results by itself, so please do not configure `--save-results` or other results-saving-related parameters in `serving-tests.json`.
|
||||||
|
|
||||||
|
## Visualizing the results
|
||||||
|
The `convert-results-json-to-markdown.py` helps you put the benchmarking results inside a markdown table, by formatting [descriptions.md](tests/descriptions.md) with real benchmarking results.
|
||||||
|
You can find the result presented as a table inside the `buildkite/performance-benchmark` job page.
|
||||||
|
If you do not see the table, please wait till the benchmark finish running.
|
||||||
|
The json version of the table (together with the json version of the benchmark) will be also attached to the markdown file.
|
||||||
|
The raw benchmarking results (in the format of json files) are in the `Artifacts` tab of the benchmarking.
|
||||||
62
.buildkite/nightly-benchmarks/benchmark-pipeline.yaml
Normal file
62
.buildkite/nightly-benchmarks/benchmark-pipeline.yaml
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
steps:
|
||||||
|
- label: "Wait for container to be ready"
|
||||||
|
agents:
|
||||||
|
queue: A100
|
||||||
|
plugins:
|
||||||
|
- kubernetes:
|
||||||
|
podSpec:
|
||||||
|
containers:
|
||||||
|
- image: badouralix/curl-jq
|
||||||
|
command:
|
||||||
|
- sh
|
||||||
|
- .buildkite/nightly-benchmarks/scripts/wait-for-image.sh
|
||||||
|
- wait
|
||||||
|
- label: "A100 Benchmark"
|
||||||
|
agents:
|
||||||
|
queue: A100
|
||||||
|
plugins:
|
||||||
|
- kubernetes:
|
||||||
|
podSpec:
|
||||||
|
priorityClassName: perf-benchmark
|
||||||
|
containers:
|
||||||
|
- image: public.ecr.aws/q9t5s3a7/vllm-ci-test-repo:$BUILDKITE_COMMIT
|
||||||
|
command:
|
||||||
|
- bash .buildkite/nightly-benchmarks/run-benchmarks-suite.sh
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
nvidia.com/gpu: 8
|
||||||
|
volumeMounts:
|
||||||
|
- name: devshm
|
||||||
|
mountPath: /dev/shm
|
||||||
|
env:
|
||||||
|
- name: VLLM_USAGE_SOURCE
|
||||||
|
value: ci-test
|
||||||
|
- name: HF_TOKEN
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: hf-token-secret
|
||||||
|
key: token
|
||||||
|
nodeSelector:
|
||||||
|
nvidia.com/gpu.product: NVIDIA-A100-SXM4-80GB
|
||||||
|
volumes:
|
||||||
|
- name: devshm
|
||||||
|
emptyDir:
|
||||||
|
medium: Memory
|
||||||
|
# - label: "H100: NVIDIA SMI"
|
||||||
|
# agents:
|
||||||
|
# queue: H100
|
||||||
|
# plugins:
|
||||||
|
# - docker#v5.11.0:
|
||||||
|
# image: public.ecr.aws/q9t5s3a7/vllm-ci-test-repo:$BUILDKITE_COMMIT
|
||||||
|
# command:
|
||||||
|
# - bash
|
||||||
|
# - .buildkite/nightly-benchmarks/run-benchmarks-suite.sh
|
||||||
|
# mount-buildkite-agent: true
|
||||||
|
# propagate-environment: true
|
||||||
|
# propagate-uid-gid: false
|
||||||
|
# ipc: host
|
||||||
|
# gpus: all
|
||||||
|
# environment:
|
||||||
|
# - VLLM_USAGE_SOURCE
|
||||||
|
# - HF_TOKEN
|
||||||
|
|
||||||
27
.buildkite/nightly-benchmarks/kickoff-pipeline.sh
Executable file
27
.buildkite/nightly-benchmarks/kickoff-pipeline.sh
Executable file
@ -0,0 +1,27 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
# NOTE(simon): this script runs inside a buildkite agent with CPU only access.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
# Install system packages
|
||||||
|
apt update
|
||||||
|
apt install -y curl jq
|
||||||
|
|
||||||
|
# Install minijinja for templating
|
||||||
|
curl -sSfL https://github.com/mitsuhiko/minijinja/releases/latest/download/minijinja-cli-installer.sh | sh
|
||||||
|
source $HOME/.cargo/env
|
||||||
|
|
||||||
|
# If BUILDKITE_PULL_REQUEST != "false", then we check the PR labels using curl and jq
|
||||||
|
if [ "$BUILDKITE_PULL_REQUEST" != "false" ]; then
|
||||||
|
PR_LABELS=$(curl -s "https://api.github.com/repos/vllm-project/vllm/pulls/$BUILDKITE_PULL_REQUEST" | jq -r '.labels[].name')
|
||||||
|
|
||||||
|
if [[ $PR_LABELS == *"perf-benchmarks"* ]]; then
|
||||||
|
echo "This PR has the 'perf-benchmarks' label. Proceeding with the nightly benchmarks."
|
||||||
|
else
|
||||||
|
echo "This PR does not have the 'perf-benchmarks' label. Skipping the nightly benchmarks."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Upload sample.yaml
|
||||||
|
buildkite-agent pipeline upload .buildkite/nightly-benchmarks/benchmark-pipeline.yaml
|
||||||
358
.buildkite/nightly-benchmarks/run-benchmarks-suite.sh
Normal file
358
.buildkite/nightly-benchmarks/run-benchmarks-suite.sh
Normal file
@ -0,0 +1,358 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# This script should be run inside the CI process
|
||||||
|
# This script assumes that we are already inside the vllm/ directory
|
||||||
|
# Benchmarking results will be available inside vllm/benchmarks/results/
|
||||||
|
|
||||||
|
# Do not set -e, as the mixtral 8x22B model tends to crash occasionally
|
||||||
|
# and we still want to see other benchmarking results even when mixtral crashes.
|
||||||
|
set -o pipefail
|
||||||
|
|
||||||
|
check_gpus() {
|
||||||
|
# check the number of GPUs and GPU type.
|
||||||
|
declare -g gpu_count=$(nvidia-smi --list-gpus | wc -l)
|
||||||
|
if [[ $gpu_count -gt 0 ]]; then
|
||||||
|
echo "GPU found."
|
||||||
|
else
|
||||||
|
echo "Need at least 1 GPU to run benchmarking."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
declare -g gpu_type=$(echo $(nvidia-smi --query-gpu=name --format=csv,noheader) | awk '{print $2}')
|
||||||
|
echo "GPU type is $gpu_type"
|
||||||
|
}
|
||||||
|
|
||||||
|
check_hf_token() {
|
||||||
|
# check if HF_TOKEN is available and valid
|
||||||
|
if [[ -z "$HF_TOKEN" ]]; then
|
||||||
|
echo "Error: HF_TOKEN is not set."
|
||||||
|
exit 1
|
||||||
|
elif [[ ! "$HF_TOKEN" =~ ^hf_ ]]; then
|
||||||
|
echo "Error: HF_TOKEN does not start with 'hf_'."
|
||||||
|
exit 1
|
||||||
|
else
|
||||||
|
echo "HF_TOKEN is set and valid."
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
json2args() {
|
||||||
|
# transforms the JSON string to command line args, and '_' is replaced to '-'
|
||||||
|
# example:
|
||||||
|
# input: { "model": "meta-llama/Llama-2-7b-chat-hf", "tensor_parallel_size": 1 }
|
||||||
|
# output: --model meta-llama/Llama-2-7b-chat-hf --tensor-parallel-size 1
|
||||||
|
local json_string=$1
|
||||||
|
local args=$(
|
||||||
|
echo "$json_string" | jq -r '
|
||||||
|
to_entries |
|
||||||
|
map("--" + (.key | gsub("_"; "-")) + " " + (.value | tostring)) |
|
||||||
|
join(" ")
|
||||||
|
'
|
||||||
|
)
|
||||||
|
echo "$args"
|
||||||
|
}
|
||||||
|
|
||||||
|
wait_for_server() {
|
||||||
|
# wait for vllm server to start
|
||||||
|
# return 1 if vllm server crashes
|
||||||
|
timeout 1200 bash -c '
|
||||||
|
until curl localhost:8000/v1/completions; do
|
||||||
|
sleep 1
|
||||||
|
done' && return 0 || return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
kill_gpu_processes() {
|
||||||
|
# kill all processes on GPU.
|
||||||
|
pids=$(nvidia-smi --query-compute-apps=pid --format=csv,noheader)
|
||||||
|
if [ -z "$pids" ]; then
|
||||||
|
echo "No GPU processes found."
|
||||||
|
else
|
||||||
|
for pid in $pids; do
|
||||||
|
kill -9 "$pid"
|
||||||
|
echo "Killed process with PID: $pid"
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "All GPU processes have been killed."
|
||||||
|
fi
|
||||||
|
|
||||||
|
# waiting for GPU processes to be fully killed
|
||||||
|
sleep 10
|
||||||
|
|
||||||
|
# remove vllm config file
|
||||||
|
rm -rf ~/.config/vllm
|
||||||
|
|
||||||
|
# Print the GPU memory usage
|
||||||
|
# so that we know if all GPU processes are killed.
|
||||||
|
gpu_memory_usage=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits -i 0)
|
||||||
|
# The memory usage should be 0 MB.
|
||||||
|
echo "GPU 0 Memory Usage: $gpu_memory_usage MB"
|
||||||
|
}
|
||||||
|
|
||||||
|
upload_to_buildkite() {
|
||||||
|
# upload the benchmarking results to buildkite
|
||||||
|
|
||||||
|
# if the agent binary is not found, skip uploading the results, exit 0
|
||||||
|
if [ ! -f /workspace/buildkite-agent ]; then
|
||||||
|
echo "buildkite-agent binary not found. Skip uploading the results."
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
/workspace/buildkite-agent annotate --style "info" --context "benchmark-results" < $RESULTS_FOLDER/benchmark_results.md
|
||||||
|
/workspace/buildkite-agent artifact upload "$RESULTS_FOLDER/*"
|
||||||
|
}
|
||||||
|
|
||||||
|
run_latency_tests() {
|
||||||
|
# run latency tests using `benchmark_latency.py`
|
||||||
|
# $1: a json file specifying latency test cases
|
||||||
|
|
||||||
|
local latency_test_file
|
||||||
|
latency_test_file=$1
|
||||||
|
|
||||||
|
# Iterate over latency tests
|
||||||
|
jq -c '.[]' "$latency_test_file" | while read -r params; do
|
||||||
|
# get the test name, and append the GPU type back to it.
|
||||||
|
test_name=$(echo "$params" | jq -r '.test_name')
|
||||||
|
if [[ ! "$test_name" =~ ^latency_ ]]; then
|
||||||
|
echo "In latency-test.json, test_name must start with \"latency_\"."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# if TEST_SELECTOR is set, only run the test cases that match the selector
|
||||||
|
if [[ -n "$TEST_SELECTOR" ]] && [[ ! "$test_name" =~ $TEST_SELECTOR ]]; then
|
||||||
|
echo "Skip test case $test_name."
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
|
||||||
|
# get arguments
|
||||||
|
latency_params=$(echo "$params" | jq -r '.parameters')
|
||||||
|
latency_args=$(json2args "$latency_params")
|
||||||
|
|
||||||
|
# check if there is enough GPU to run the test
|
||||||
|
tp=$(echo "$latency_params" | jq -r '.tensor_parallel_size')
|
||||||
|
if [[ $gpu_count -lt $tp ]]; then
|
||||||
|
echo "Required tensor-parallel-size $tp but only $gpu_count GPU found. Skip testcase $testname."
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
|
||||||
|
latency_command="python3 benchmark_latency.py \
|
||||||
|
--output-json $RESULTS_FOLDER/${test_name}.json \
|
||||||
|
$latency_args"
|
||||||
|
|
||||||
|
echo "Running test case $test_name"
|
||||||
|
echo "Latency command: $latency_command"
|
||||||
|
|
||||||
|
# recoding benchmarking command ang GPU command
|
||||||
|
jq_output=$(jq -n \
|
||||||
|
--arg latency "$latency_command" \
|
||||||
|
--arg gpu "$gpu_type" \
|
||||||
|
'{
|
||||||
|
latency_command: $latency,
|
||||||
|
gpu_type: $gpu
|
||||||
|
}')
|
||||||
|
echo "$jq_output" > "$RESULTS_FOLDER/$test_name.commands"
|
||||||
|
|
||||||
|
# run the benchmark
|
||||||
|
eval "$latency_command"
|
||||||
|
|
||||||
|
kill_gpu_processes
|
||||||
|
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
run_throughput_tests() {
|
||||||
|
# run throughput tests using `benchmark_throughput.py`
|
||||||
|
# $1: a json file specifying throughput test cases
|
||||||
|
|
||||||
|
local throughput_test_file
|
||||||
|
throughput_test_file=$1
|
||||||
|
|
||||||
|
# Iterate over throughput tests
|
||||||
|
jq -c '.[]' "$throughput_test_file" | while read -r params; do
|
||||||
|
# get the test name, and append the GPU type back to it.
|
||||||
|
test_name=$(echo "$params" | jq -r '.test_name')
|
||||||
|
if [[ ! "$test_name" =~ ^throughput_ ]]; then
|
||||||
|
echo "In throughput-test.json, test_name must start with \"throughput_\"."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# if TEST_SELECTOR is set, only run the test cases that match the selector
|
||||||
|
if [[ -n "$TEST_SELECTOR" ]] && [[ ! "$test_name" =~ $TEST_SELECTOR ]]; then
|
||||||
|
echo "Skip test case $test_name."
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
|
||||||
|
# get arguments
|
||||||
|
throughput_params=$(echo "$params" | jq -r '.parameters')
|
||||||
|
throughput_args=$(json2args "$throughput_params")
|
||||||
|
|
||||||
|
# check if there is enough GPU to run the test
|
||||||
|
tp=$(echo $throughput_params | jq -r '.tensor_parallel_size')
|
||||||
|
if [[ $gpu_count -lt $tp ]]; then
|
||||||
|
echo "Required tensor-parallel-size $tp but only $gpu_count GPU found. Skip testcase $testname."
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
|
||||||
|
throughput_command="python3 benchmark_throughput.py \
|
||||||
|
--output-json $RESULTS_FOLDER/${test_name}.json \
|
||||||
|
$throughput_args"
|
||||||
|
|
||||||
|
echo "Running test case $test_name"
|
||||||
|
echo "Throughput command: $throughput_command"
|
||||||
|
# recoding benchmarking command ang GPU command
|
||||||
|
jq_output=$(jq -n \
|
||||||
|
--arg command "$throughput_command" \
|
||||||
|
--arg gpu "$gpu_type" \
|
||||||
|
'{
|
||||||
|
throughput_command: $command,
|
||||||
|
gpu_type: $gpu
|
||||||
|
}')
|
||||||
|
echo "$jq_output" > "$RESULTS_FOLDER/$test_name.commands"
|
||||||
|
|
||||||
|
# run the benchmark
|
||||||
|
eval "$throughput_command"
|
||||||
|
|
||||||
|
kill_gpu_processes
|
||||||
|
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
run_serving_tests() {
|
||||||
|
# run serving tests using `benchmark_serving.py`
|
||||||
|
# $1: a json file specifying serving test cases
|
||||||
|
|
||||||
|
local serving_test_file
|
||||||
|
serving_test_file=$1
|
||||||
|
|
||||||
|
# Iterate over serving tests
|
||||||
|
jq -c '.[]' "$serving_test_file" | while read -r params; do
|
||||||
|
# get the test name, and append the GPU type back to it.
|
||||||
|
test_name=$(echo "$params" | jq -r '.test_name')
|
||||||
|
if [[ ! "$test_name" =~ ^serving_ ]]; then
|
||||||
|
echo "In serving-test.json, test_name must start with \"serving_\"."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# if TEST_SELECTOR is set, only run the test cases that match the selector
|
||||||
|
if [[ -n "$TEST_SELECTOR" ]] && [[ ! "$test_name" =~ $TEST_SELECTOR ]]; then
|
||||||
|
echo "Skip test case $test_name."
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
|
# get client and server arguments
|
||||||
|
server_params=$(echo "$params" | jq -r '.server_parameters')
|
||||||
|
client_params=$(echo "$params" | jq -r '.client_parameters')
|
||||||
|
server_args=$(json2args "$server_params")
|
||||||
|
client_args=$(json2args "$client_params")
|
||||||
|
qps_list=$(echo "$params" | jq -r '.qps_list')
|
||||||
|
qps_list=$(echo "$qps_list" | jq -r '.[] | @sh')
|
||||||
|
echo "Running over qps list $qps_list"
|
||||||
|
|
||||||
|
# check if there is enough GPU to run the test
|
||||||
|
tp=$(echo "$server_params" | jq -r '.tensor_parallel_size')
|
||||||
|
if [[ $gpu_count -lt $tp ]]; then
|
||||||
|
echo "Required tensor-parallel-size $tp but only $gpu_count GPU found. Skip testcase $testname."
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
|
||||||
|
# check if server model and client model is aligned
|
||||||
|
server_model=$(echo "$server_params" | jq -r '.model')
|
||||||
|
client_model=$(echo "$client_params" | jq -r '.model')
|
||||||
|
if [[ $server_model != "$client_model" ]]; then
|
||||||
|
echo "Server model and client model must be the same. Skip testcase $testname."
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
|
||||||
|
server_command="python3 \
|
||||||
|
-m vllm.entrypoints.openai.api_server \
|
||||||
|
$server_args"
|
||||||
|
|
||||||
|
# run the server
|
||||||
|
echo "Running test case $test_name"
|
||||||
|
echo "Server command: $server_command"
|
||||||
|
eval "$server_command" &
|
||||||
|
|
||||||
|
# wait until the server is alive
|
||||||
|
wait_for_server
|
||||||
|
if [ $? -eq 0 ]; then
|
||||||
|
echo ""
|
||||||
|
echo "vllm server is up and running."
|
||||||
|
else
|
||||||
|
echo ""
|
||||||
|
echo "vllm failed to start within the timeout period."
|
||||||
|
fi
|
||||||
|
|
||||||
|
# iterate over different QPS
|
||||||
|
for qps in $qps_list; do
|
||||||
|
# remove the surrounding single quote from qps
|
||||||
|
if [[ "$qps" == *"inf"* ]]; then
|
||||||
|
echo "qps was $qps"
|
||||||
|
qps="inf"
|
||||||
|
echo "now qps is $qps"
|
||||||
|
fi
|
||||||
|
|
||||||
|
new_test_name=$test_name"_qps_"$qps
|
||||||
|
|
||||||
|
client_command="python3 benchmark_serving.py \
|
||||||
|
--save-result \
|
||||||
|
--result-dir $RESULTS_FOLDER \
|
||||||
|
--result-filename ${new_test_name}.json \
|
||||||
|
--request-rate $qps \
|
||||||
|
$client_args"
|
||||||
|
|
||||||
|
echo "Running test case $test_name with qps $qps"
|
||||||
|
echo "Client command: $client_command"
|
||||||
|
|
||||||
|
eval "$client_command"
|
||||||
|
|
||||||
|
# record the benchmarking commands
|
||||||
|
jq_output=$(jq -n \
|
||||||
|
--arg server "$server_command" \
|
||||||
|
--arg client "$client_command" \
|
||||||
|
--arg gpu "$gpu_type" \
|
||||||
|
'{
|
||||||
|
server_command: $server,
|
||||||
|
client_command: $client,
|
||||||
|
gpu_type: $gpu
|
||||||
|
}')
|
||||||
|
echo "$jq_output" > "$RESULTS_FOLDER/${new_test_name}.commands"
|
||||||
|
|
||||||
|
done
|
||||||
|
|
||||||
|
# clean up
|
||||||
|
kill_gpu_processes
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
main() {
|
||||||
|
check_gpus
|
||||||
|
check_hf_token
|
||||||
|
|
||||||
|
# dependencies
|
||||||
|
(which wget && which curl) || (apt-get update && apt-get install -y wget curl)
|
||||||
|
(which jq) || (apt-get update && apt-get -y install jq)
|
||||||
|
|
||||||
|
# get the current IP address, required by benchmark_serving.py
|
||||||
|
export VLLM_HOST_IP=$(hostname -I | awk '{print $1}')
|
||||||
|
# turn of the reporting of the status of each request, to clean up the terminal output
|
||||||
|
export VLLM_LOG_LEVEL="WARNING"
|
||||||
|
|
||||||
|
# prepare for benchmarking
|
||||||
|
cd benchmarks || exit 1
|
||||||
|
wget https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered/resolve/main/ShareGPT_V3_unfiltered_cleaned_split.json
|
||||||
|
declare -g RESULTS_FOLDER=results/
|
||||||
|
mkdir -p $RESULTS_FOLDER
|
||||||
|
QUICK_BENCHMARK_ROOT=../.buildkite/nightly-benchmarks/
|
||||||
|
|
||||||
|
# benchmarking
|
||||||
|
run_serving_tests $QUICK_BENCHMARK_ROOT/tests/serving-tests.json
|
||||||
|
run_latency_tests $QUICK_BENCHMARK_ROOT/tests/latency-tests.json
|
||||||
|
run_throughput_tests $QUICK_BENCHMARK_ROOT/tests/throughput-tests.json
|
||||||
|
|
||||||
|
|
||||||
|
# postprocess benchmarking results
|
||||||
|
pip install tabulate pandas
|
||||||
|
python3 $QUICK_BENCHMARK_ROOT/scripts/convert-results-json-to-markdown.py
|
||||||
|
|
||||||
|
upload_to_buildkite
|
||||||
|
}
|
||||||
|
|
||||||
|
main "$@"
|
||||||
@ -0,0 +1,192 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
from tabulate import tabulate
|
||||||
|
|
||||||
|
results_folder = Path("results/")
|
||||||
|
|
||||||
|
# latency results and the keys that will be printed into markdown
|
||||||
|
latency_results = []
|
||||||
|
latency_column_mapping = {
|
||||||
|
"test_name": "Test name",
|
||||||
|
"gpu_type": "GPU",
|
||||||
|
"avg_latency": "Mean latency (ms)",
|
||||||
|
# "P10": "P10 (s)",
|
||||||
|
# "P25": "P25 (s)",
|
||||||
|
"P50": "Median latency (ms)",
|
||||||
|
# "P75": "P75 (s)",
|
||||||
|
# "P90": "P90 (s)",
|
||||||
|
"P99": "P99 latency (ms)",
|
||||||
|
}
|
||||||
|
|
||||||
|
# throughput tests and the keys that will be printed into markdown
|
||||||
|
throughput_results = []
|
||||||
|
throughput_results_column_mapping = {
|
||||||
|
"test_name": "Test name",
|
||||||
|
"gpu_type": "GPU",
|
||||||
|
# "num_requests": "# of req.",
|
||||||
|
# "total_num_tokens": "Total # of tokens",
|
||||||
|
# "elapsed_time": "Elapsed time (s)",
|
||||||
|
"requests_per_second": "Tput (req/s)",
|
||||||
|
# "tokens_per_second": "Tput (tok/s)",
|
||||||
|
}
|
||||||
|
|
||||||
|
# serving results and the keys that will be printed into markdown
|
||||||
|
serving_results = []
|
||||||
|
serving_column_mapping = {
|
||||||
|
"test_name": "Test name",
|
||||||
|
"gpu_type": "GPU",
|
||||||
|
# "completed": "# of req.",
|
||||||
|
"request_throughput": "Tput (req/s)",
|
||||||
|
# "input_throughput": "Input Tput (tok/s)",
|
||||||
|
# "output_throughput": "Output Tput (tok/s)",
|
||||||
|
"mean_ttft_ms": "Mean TTFT (ms)",
|
||||||
|
"median_ttft_ms": "Median TTFT (ms)",
|
||||||
|
"p99_ttft_ms": "P99 TTFT (ms)",
|
||||||
|
# "mean_tpot_ms": "Mean TPOT (ms)",
|
||||||
|
# "median_tpot_ms": "Median",
|
||||||
|
# "p99_tpot_ms": "P99",
|
||||||
|
"mean_itl_ms": "Mean ITL (ms)",
|
||||||
|
"median_itl_ms": "Median ITL (ms)",
|
||||||
|
"p99_itl_ms": "P99 ITL (ms)",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def read_markdown(file):
|
||||||
|
if os.path.exists(file):
|
||||||
|
with open(file, "r") as f:
|
||||||
|
return f.read() + "\n"
|
||||||
|
else:
|
||||||
|
return f"{file} not found.\n"
|
||||||
|
|
||||||
|
|
||||||
|
def results_to_json(latency, throughput, serving):
|
||||||
|
return json.dumps({
|
||||||
|
'latency': latency.to_dict(),
|
||||||
|
'throughput': throughput.to_dict(),
|
||||||
|
'serving': serving.to_dict()
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
# collect results
|
||||||
|
for test_file in results_folder.glob("*.json"):
|
||||||
|
|
||||||
|
with open(test_file, "r") as f:
|
||||||
|
raw_result = json.loads(f.read())
|
||||||
|
|
||||||
|
if "serving" in str(test_file):
|
||||||
|
# this result is generated via `benchmark_serving.py`
|
||||||
|
|
||||||
|
# attach the benchmarking command to raw_result
|
||||||
|
with open(test_file.with_suffix(".commands"), "r") as f:
|
||||||
|
command = json.loads(f.read())
|
||||||
|
raw_result.update(command)
|
||||||
|
|
||||||
|
# update the test name of this result
|
||||||
|
raw_result.update({"test_name": test_file.stem})
|
||||||
|
|
||||||
|
# add the result to raw_result
|
||||||
|
serving_results.append(raw_result)
|
||||||
|
continue
|
||||||
|
|
||||||
|
elif "latency" in f.name:
|
||||||
|
# this result is generated via `benchmark_latency.py`
|
||||||
|
|
||||||
|
# attach the benchmarking command to raw_result
|
||||||
|
with open(test_file.with_suffix(".commands"), "r") as f:
|
||||||
|
command = json.loads(f.read())
|
||||||
|
raw_result.update(command)
|
||||||
|
|
||||||
|
# update the test name of this result
|
||||||
|
raw_result.update({"test_name": test_file.stem})
|
||||||
|
|
||||||
|
# get different percentiles
|
||||||
|
for perc in [10, 25, 50, 75, 90, 99]:
|
||||||
|
# Multiply 1000 to convert the time unit from s to ms
|
||||||
|
raw_result.update(
|
||||||
|
{f"P{perc}": 1000 * raw_result["percentiles"][str(perc)]})
|
||||||
|
raw_result["avg_latency"] = raw_result["avg_latency"] * 1000
|
||||||
|
|
||||||
|
# add the result to raw_result
|
||||||
|
latency_results.append(raw_result)
|
||||||
|
continue
|
||||||
|
|
||||||
|
elif "throughput" in f.name:
|
||||||
|
# this result is generated via `benchmark_throughput.py`
|
||||||
|
|
||||||
|
# attach the benchmarking command to raw_result
|
||||||
|
with open(test_file.with_suffix(".commands"), "r") as f:
|
||||||
|
command = json.loads(f.read())
|
||||||
|
raw_result.update(command)
|
||||||
|
|
||||||
|
# update the test name of this result
|
||||||
|
raw_result.update({"test_name": test_file.stem})
|
||||||
|
|
||||||
|
# add the result to raw_result
|
||||||
|
throughput_results.append(raw_result)
|
||||||
|
continue
|
||||||
|
|
||||||
|
print(f"Skipping {test_file}")
|
||||||
|
|
||||||
|
latency_results = pd.DataFrame.from_dict(latency_results)
|
||||||
|
serving_results = pd.DataFrame.from_dict(serving_results)
|
||||||
|
throughput_results = pd.DataFrame.from_dict(throughput_results)
|
||||||
|
|
||||||
|
raw_results_json = results_to_json(latency_results, throughput_results,
|
||||||
|
serving_results)
|
||||||
|
|
||||||
|
# remapping the key, for visualization purpose
|
||||||
|
if not latency_results.empty:
|
||||||
|
latency_results = latency_results[list(
|
||||||
|
latency_column_mapping.keys())].rename(
|
||||||
|
columns=latency_column_mapping)
|
||||||
|
if not serving_results.empty:
|
||||||
|
serving_results = serving_results[list(
|
||||||
|
serving_column_mapping.keys())].rename(
|
||||||
|
columns=serving_column_mapping)
|
||||||
|
if not throughput_results.empty:
|
||||||
|
throughput_results = throughput_results[list(
|
||||||
|
throughput_results_column_mapping.keys())].rename(
|
||||||
|
columns=throughput_results_column_mapping)
|
||||||
|
|
||||||
|
processed_results_json = results_to_json(latency_results,
|
||||||
|
throughput_results,
|
||||||
|
serving_results)
|
||||||
|
|
||||||
|
# get markdown tables
|
||||||
|
latency_md_table = tabulate(latency_results,
|
||||||
|
headers='keys',
|
||||||
|
tablefmt='pipe',
|
||||||
|
showindex=False)
|
||||||
|
serving_md_table = tabulate(serving_results,
|
||||||
|
headers='keys',
|
||||||
|
tablefmt='pipe',
|
||||||
|
showindex=False)
|
||||||
|
throughput_md_table = tabulate(throughput_results,
|
||||||
|
headers='keys',
|
||||||
|
tablefmt='pipe',
|
||||||
|
showindex=False)
|
||||||
|
|
||||||
|
# document the result
|
||||||
|
with open(results_folder / "benchmark_results.md", "w") as f:
|
||||||
|
|
||||||
|
results = read_markdown(
|
||||||
|
"../.buildkite/nightly-benchmarks/tests/descriptions.md")
|
||||||
|
results = results.format(
|
||||||
|
latency_tests_markdown_table=latency_md_table,
|
||||||
|
throughput_tests_markdown_table=throughput_md_table,
|
||||||
|
serving_tests_markdown_table=serving_md_table,
|
||||||
|
benchmarking_results_in_json_string=processed_results_json)
|
||||||
|
f.write(results)
|
||||||
|
|
||||||
|
# document benchmarking results in json
|
||||||
|
with open(results_folder / "benchmark_results.json", "w") as f:
|
||||||
|
|
||||||
|
results = latency_results.to_dict(
|
||||||
|
orient='records') + throughput_results.to_dict(
|
||||||
|
orient='records') + serving_results.to_dict(orient='records')
|
||||||
|
f.write(json.dumps(results))
|
||||||
17
.buildkite/nightly-benchmarks/scripts/wait-for-image.sh
Normal file
17
.buildkite/nightly-benchmarks/scripts/wait-for-image.sh
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
TOKEN=$(curl -s -L "https://public.ecr.aws/token?service=public.ecr.aws&scope=repository:q9t5s3a7/vllm-ci-test-repo:pull" | jq -r .token)
|
||||||
|
URL="https://public.ecr.aws/v2/q9t5s3a7/vllm-ci-test-repo/manifests/$BUILDKITE_COMMIT"
|
||||||
|
|
||||||
|
retries=0
|
||||||
|
while [ $retries -lt 1000 ]; do
|
||||||
|
if [ $(curl -s -L -H "Authorization: Bearer $TOKEN" -o /dev/null -w "%{http_code}" $URL) -eq 200 ]; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Waiting for image to be available..."
|
||||||
|
|
||||||
|
retries=$((retries + 1))
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
|
||||||
|
exit 1
|
||||||
67
.buildkite/nightly-benchmarks/tests/descriptions.md
Normal file
67
.buildkite/nightly-benchmarks/tests/descriptions.md
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
|
||||||
|
## Latency tests
|
||||||
|
|
||||||
|
This test suite aims to test vllm's end-to-end latency under a controlled setup.
|
||||||
|
|
||||||
|
- Input length: 32 tokens.
|
||||||
|
- Output length: 128 tokens.
|
||||||
|
- Batch size: fixed (8).
|
||||||
|
- Models: llama-3 8B, llama-3 70B, mixtral 8x7B.
|
||||||
|
- Evaluation metrics: end-to-end latency (mean, median, p99).
|
||||||
|
|
||||||
|
### Latency benchmarking results
|
||||||
|
|
||||||
|
{latency_tests_markdown_table}
|
||||||
|
|
||||||
|
## Throughput tests
|
||||||
|
|
||||||
|
This test suite aims to test vllm's throughput.
|
||||||
|
|
||||||
|
- Input length: randomly sample 200 prompts from ShareGPT dataset (with fixed random seed).
|
||||||
|
- Output length: the corresponding output length of these 200 prompts.
|
||||||
|
- Batch size: dynamically determined by vllm to achieve maximum throughput.
|
||||||
|
- Models: llama-3 8B, llama-3 70B, mixtral 8x7B.
|
||||||
|
- Evaluation metrics: throughput.
|
||||||
|
|
||||||
|
### Throughput benchmarking results
|
||||||
|
|
||||||
|
{throughput_tests_markdown_table}
|
||||||
|
|
||||||
|
## Serving tests
|
||||||
|
|
||||||
|
This test suite aims to test vllm's real serving metrics.
|
||||||
|
|
||||||
|
- Input length: randomly sample 200 prompts from ShareGPT dataset (with fixed random seed).
|
||||||
|
- Output length: the corresponding output length of these 200 prompts.
|
||||||
|
- Batch size: dynamically determined by vllm and the arrival pattern of the requests.
|
||||||
|
- **Average QPS (query per second)**: 1, 4, 16 and inf. QPS = inf means all requests come at once. For other QPS values, the arrival time of each query is determined using a random Poisson process (with fixed random seed).
|
||||||
|
- Models: llama-3 8B, llama-3 70B, mixtral 8x7B.
|
||||||
|
- Evaluation metrics: throughput, TTFT (time to the first token, with mean, median and p99), ITL (inter-token latency, with mean, median and p99).
|
||||||
|
|
||||||
|
### Serving benchmarking results
|
||||||
|
|
||||||
|
{serving_tests_markdown_table}
|
||||||
|
|
||||||
|
## json version of the benchmarking tables
|
||||||
|
|
||||||
|
This section contains the data of the markdown tables above in JSON format.
|
||||||
|
You can load the benchmarking tables into pandas dataframes as follows:
|
||||||
|
|
||||||
|
```python
|
||||||
|
import json
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
benchmarking_results_json = """The json string"""
|
||||||
|
benchmarking_results = json.loads(benchmarking_results_json)
|
||||||
|
latency_results = pd.DataFrame.from_dict(benchmarking_results["latency"])
|
||||||
|
throughput_results = pd.DataFrame.from_dict(benchmarking_results["throughput"])
|
||||||
|
serving_results = pd.DataFrame.from_dict(benchmarking_results["serving"])
|
||||||
|
```
|
||||||
|
|
||||||
|
The json string for all benchmarking tables:
|
||||||
|
```json
|
||||||
|
{benchmarking_results_in_json_string}
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also check the raw experiment data in the Artifact tab of the Buildkite page.
|
||||||
|
|
||||||
32
.buildkite/nightly-benchmarks/tests/latency-tests.json
Normal file
32
.buildkite/nightly-benchmarks/tests/latency-tests.json
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"test_name": "latency_llama8B_tp1",
|
||||||
|
"parameters": {
|
||||||
|
"model": "meta-llama/Meta-Llama-3-8B",
|
||||||
|
"tensor_parallel_size": 1,
|
||||||
|
"load_format": "dummy",
|
||||||
|
"num_iters_warmup": 5,
|
||||||
|
"num_iters": 15
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"test_name": "latency_llama70B_tp4",
|
||||||
|
"parameters": {
|
||||||
|
"model": "meta-llama/Meta-Llama-3-70B-Instruct",
|
||||||
|
"tensor_parallel_size": 4,
|
||||||
|
"load_format": "dummy",
|
||||||
|
"num-iters-warmup": 5,
|
||||||
|
"num-iters": 15
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"test_name": "latency_mixtral8x7B_tp2",
|
||||||
|
"parameters": {
|
||||||
|
"model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
||||||
|
"tensor_parallel_size": 2,
|
||||||
|
"load_format": "dummy",
|
||||||
|
"num-iters-warmup": 5,
|
||||||
|
"num-iters": 15
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
59
.buildkite/nightly-benchmarks/tests/serving-tests.json
Normal file
59
.buildkite/nightly-benchmarks/tests/serving-tests.json
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"test_name": "serving_llama8B_tp1_sharegpt",
|
||||||
|
"qps_list": [1, 4, 16, "inf"],
|
||||||
|
"server_parameters": {
|
||||||
|
"model": "meta-llama/Meta-Llama-3-8B",
|
||||||
|
"tensor_parallel_size": 1,
|
||||||
|
"swap_space": 16,
|
||||||
|
"disable_log_stats": "",
|
||||||
|
"disable_log_requests": "",
|
||||||
|
"load_format": "dummy"
|
||||||
|
},
|
||||||
|
"client_parameters": {
|
||||||
|
"model": "meta-llama/Meta-Llama-3-8B",
|
||||||
|
"backend": "vllm",
|
||||||
|
"dataset_name": "sharegpt",
|
||||||
|
"dataset_path": "./ShareGPT_V3_unfiltered_cleaned_split.json",
|
||||||
|
"num_prompts": 200
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"test_name": "serving_llama70B_tp4_sharegpt",
|
||||||
|
"qps_list": [1, 4, 16, "inf"],
|
||||||
|
"server_parameters": {
|
||||||
|
"model": "meta-llama/Meta-Llama-3-70B-Instruct",
|
||||||
|
"tensor_parallel_size": 4,
|
||||||
|
"swap_space": 16,
|
||||||
|
"disable_log_stats": "",
|
||||||
|
"disable_log_requests": "",
|
||||||
|
"load_format": "dummy"
|
||||||
|
},
|
||||||
|
"client_parameters": {
|
||||||
|
"model": "meta-llama/Meta-Llama-3-70B-Instruct",
|
||||||
|
"backend": "vllm",
|
||||||
|
"dataset_name": "sharegpt",
|
||||||
|
"dataset_path": "./ShareGPT_V3_unfiltered_cleaned_split.json",
|
||||||
|
"num_prompts": 200
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"test_name": "serving_mixtral8x7B_tp2_sharegpt",
|
||||||
|
"qps_list": [1, 4, 16, "inf"],
|
||||||
|
"server_parameters": {
|
||||||
|
"model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
||||||
|
"tensor_parallel_size": 2,
|
||||||
|
"swap_space": 16,
|
||||||
|
"disable_log_stats": "",
|
||||||
|
"disable_log_requests": "",
|
||||||
|
"load_format": "dummy"
|
||||||
|
},
|
||||||
|
"client_parameters": {
|
||||||
|
"model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
||||||
|
"backend": "vllm",
|
||||||
|
"dataset_name": "sharegpt",
|
||||||
|
"dataset_path": "./ShareGPT_V3_unfiltered_cleaned_split.json",
|
||||||
|
"num_prompts": 200
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
35
.buildkite/nightly-benchmarks/tests/throughput-tests.json
Normal file
35
.buildkite/nightly-benchmarks/tests/throughput-tests.json
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"test_name": "throughput_llama8B_tp1",
|
||||||
|
"parameters": {
|
||||||
|
"model": "meta-llama/Meta-Llama-3-8B",
|
||||||
|
"tensor_parallel_size": 1,
|
||||||
|
"load_format": "dummy",
|
||||||
|
"dataset": "./ShareGPT_V3_unfiltered_cleaned_split.json",
|
||||||
|
"num_prompts": 200,
|
||||||
|
"backend": "vllm"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"test_name": "throughput_llama70B_tp4",
|
||||||
|
"parameters": {
|
||||||
|
"model": "meta-llama/Meta-Llama-3-70B-Instruct",
|
||||||
|
"tensor_parallel_size": 4,
|
||||||
|
"load_format": "dummy",
|
||||||
|
"dataset": "./ShareGPT_V3_unfiltered_cleaned_split.json",
|
||||||
|
"num_prompts": 200,
|
||||||
|
"backend": "vllm"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"test_name": "throughput_mixtral8x7B_tp2",
|
||||||
|
"parameters": {
|
||||||
|
"model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
||||||
|
"tensor_parallel_size": 2,
|
||||||
|
"load_format": "dummy",
|
||||||
|
"dataset": "./ShareGPT_V3_unfiltered_cleaned_split.json",
|
||||||
|
"num_prompts": 200,
|
||||||
|
"backend": "vllm"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
21
.buildkite/release-pipeline.yaml
Normal file
21
.buildkite/release-pipeline.yaml
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
steps:
|
||||||
|
- block: "Build wheels"
|
||||||
|
|
||||||
|
- label: "Build wheel - Python {{matrix.python_version}}, CUDA {{matrix.cuda_version}}"
|
||||||
|
agents:
|
||||||
|
queue: cpu_queue
|
||||||
|
commands:
|
||||||
|
- "DOCKER_BUILDKIT=1 docker build --build-arg max_jobs=16 --build-arg USE_SCCACHE=1 --build-arg CUDA_VERSION={{matrix.cuda_version}} --build-arg PYTHON_VERSION={{matrix.python_version}} --tag vllm-ci:build-image --target build --progress plain ."
|
||||||
|
- "mkdir artifacts"
|
||||||
|
- "docker run --rm -v $(pwd)/artifacts:/artifacts_host vllm-ci:build-image cp -r dist /artifacts_host"
|
||||||
|
- "aws s3 cp --recursive artifacts/dist s3://vllm-wheels/$BUILDKITE_COMMIT/"
|
||||||
|
matrix:
|
||||||
|
setup:
|
||||||
|
cuda_version:
|
||||||
|
- "11.8.0"
|
||||||
|
- "12.1.0"
|
||||||
|
python_version:
|
||||||
|
- "3.8"
|
||||||
|
- "3.9"
|
||||||
|
- "3.10"
|
||||||
|
- "3.11"
|
||||||
73
.buildkite/run-amd-test.sh
Normal file
73
.buildkite/run-amd-test.sh
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
# This script runs test inside the corresponding ROCm docker container.
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
# Print ROCm version
|
||||||
|
echo "--- ROCm info"
|
||||||
|
rocminfo
|
||||||
|
|
||||||
|
# cleanup older docker images
|
||||||
|
cleanup_docker() {
|
||||||
|
# Get Docker's root directory
|
||||||
|
docker_root=$(docker info -f '{{.DockerRootDir}}')
|
||||||
|
if [ -z "$docker_root" ]; then
|
||||||
|
echo "Failed to determine Docker root directory."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Docker root directory: $docker_root"
|
||||||
|
# Check disk usage of the filesystem where Docker's root directory is located
|
||||||
|
disk_usage=$(df "$docker_root" | tail -1 | awk '{print $5}' | sed 's/%//')
|
||||||
|
# Define the threshold
|
||||||
|
threshold=70
|
||||||
|
if [ "$disk_usage" -gt "$threshold" ]; then
|
||||||
|
echo "Disk usage is above $threshold%. Cleaning up Docker images and volumes..."
|
||||||
|
# Remove dangling images (those that are not tagged and not used by any container)
|
||||||
|
docker image prune -f
|
||||||
|
# Remove unused volumes
|
||||||
|
docker volume prune -f
|
||||||
|
echo "Docker images and volumes cleanup completed."
|
||||||
|
else
|
||||||
|
echo "Disk usage is below $threshold%. No cleanup needed."
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Call the cleanup docker function
|
||||||
|
cleanup_docker
|
||||||
|
|
||||||
|
echo "--- Resetting GPUs"
|
||||||
|
|
||||||
|
echo "reset" > /opt/amdgpu/etc/gpu_state
|
||||||
|
|
||||||
|
while true; do
|
||||||
|
sleep 3
|
||||||
|
if grep -q clean /opt/amdgpu/etc/gpu_state; then
|
||||||
|
echo "GPUs state is \"clean\""
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "--- Building container"
|
||||||
|
sha=$(git rev-parse --short HEAD)
|
||||||
|
image_name=rocm_${sha}
|
||||||
|
container_name=rocm_${sha}_$(tr -dc A-Za-z0-9 < /dev/urandom | head -c 10; echo)
|
||||||
|
docker build \
|
||||||
|
-t ${image_name} \
|
||||||
|
-f Dockerfile.rocm \
|
||||||
|
--progress plain \
|
||||||
|
.
|
||||||
|
|
||||||
|
remove_docker_container() {
|
||||||
|
docker rm -f ${container_name} || docker image rm -f ${image_name} || true
|
||||||
|
}
|
||||||
|
trap remove_docker_container EXIT
|
||||||
|
|
||||||
|
echo "--- Running container"
|
||||||
|
|
||||||
|
docker run \
|
||||||
|
--device /dev/kfd --device /dev/dri \
|
||||||
|
--network host \
|
||||||
|
--rm \
|
||||||
|
-e HF_TOKEN \
|
||||||
|
--name ${container_name} \
|
||||||
|
${image_name} \
|
||||||
|
/bin/bash -c "${@}"
|
||||||
|
|
||||||
@ -9,10 +9,10 @@ cd "$(dirname "${BASH_SOURCE[0]}")/.."
|
|||||||
(which wget && which curl) || (apt-get update && apt-get install -y wget curl)
|
(which wget && which curl) || (apt-get update && apt-get install -y wget curl)
|
||||||
|
|
||||||
# run python-based benchmarks and upload the result to buildkite
|
# run python-based benchmarks and upload the result to buildkite
|
||||||
python3 benchmarks/benchmark_latency.py 2>&1 | tee benchmark_latency.txt
|
python3 benchmarks/benchmark_latency.py --output-json latency_results.json 2>&1 | tee benchmark_latency.txt
|
||||||
bench_latency_exit_code=$?
|
bench_latency_exit_code=$?
|
||||||
|
|
||||||
python3 benchmarks/benchmark_throughput.py --input-len 256 --output-len 256 2>&1 | tee benchmark_throughput.txt
|
python3 benchmarks/benchmark_throughput.py --input-len 256 --output-len 256 --output-json throughput_results.json 2>&1 | tee benchmark_throughput.txt
|
||||||
bench_throughput_exit_code=$?
|
bench_throughput_exit_code=$?
|
||||||
|
|
||||||
# run server-based benchmarks and upload the result to buildkite
|
# run server-based benchmarks and upload the result to buildkite
|
||||||
@ -23,8 +23,9 @@ wget https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered/r
|
|||||||
# wait for server to start, timeout after 600 seconds
|
# wait for server to start, timeout after 600 seconds
|
||||||
timeout 600 bash -c 'until curl localhost:8000/v1/models; do sleep 1; done' || exit 1
|
timeout 600 bash -c 'until curl localhost:8000/v1/models; do sleep 1; done' || exit 1
|
||||||
python3 benchmarks/benchmark_serving.py \
|
python3 benchmarks/benchmark_serving.py \
|
||||||
--backend openai \
|
--backend vllm \
|
||||||
--dataset ./ShareGPT_V3_unfiltered_cleaned_split.json \
|
--dataset-name sharegpt \
|
||||||
|
--dataset-path ./ShareGPT_V3_unfiltered_cleaned_split.json \
|
||||||
--model meta-llama/Llama-2-7b-chat-hf \
|
--model meta-llama/Llama-2-7b-chat-hf \
|
||||||
--num-prompts 20 \
|
--num-prompts 20 \
|
||||||
--endpoint /v1/completions \
|
--endpoint /v1/completions \
|
||||||
@ -48,10 +49,17 @@ sed -n '$p' benchmark_throughput.txt >> benchmark_results.md # last line
|
|||||||
echo "### Serving Benchmarks" >> benchmark_results.md
|
echo "### Serving Benchmarks" >> benchmark_results.md
|
||||||
sed -n '1p' benchmark_serving.txt >> benchmark_results.md # first line
|
sed -n '1p' benchmark_serving.txt >> benchmark_results.md # first line
|
||||||
echo "" >> benchmark_results.md
|
echo "" >> benchmark_results.md
|
||||||
tail -n 13 benchmark_serving.txt >> benchmark_results.md # last 13 lines
|
echo '```' >> benchmark_results.md
|
||||||
|
tail -n 24 benchmark_serving.txt >> benchmark_results.md # last 24 lines
|
||||||
|
echo '```' >> benchmark_results.md
|
||||||
|
|
||||||
|
# if the agent binary is not found, skip uploading the results, exit 0
|
||||||
|
if [ ! -f /usr/bin/buildkite-agent ]; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
# upload the results to buildkite
|
# upload the results to buildkite
|
||||||
/workspace/buildkite-agent annotate --style "info" --context "benchmark-results" < benchmark_results.md
|
buildkite-agent annotate --style "info" --context "benchmark-results" < benchmark_results.md
|
||||||
|
|
||||||
# exit with the exit code of the benchmarks
|
# exit with the exit code of the benchmarks
|
||||||
if [ $bench_latency_exit_code -ne 0 ]; then
|
if [ $bench_latency_exit_code -ne 0 ]; then
|
||||||
@ -66,4 +74,5 @@ if [ $bench_serving_exit_code -ne 0 ]; then
|
|||||||
exit $bench_serving_exit_code
|
exit $bench_serving_exit_code
|
||||||
fi
|
fi
|
||||||
|
|
||||||
/workspace/buildkite-agent artifact upload openai-*.json
|
rm ShareGPT_V3_unfiltered_cleaned_split.json
|
||||||
|
buildkite-agent artifact upload "*.json"
|
||||||
|
|||||||
28
.buildkite/run-cpu-test.sh
Normal file
28
.buildkite/run-cpu-test.sh
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
# This script build the CPU docker image and run the offline inference inside the container.
|
||||||
|
# It serves a sanity check for compilation and basic model usage.
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
# Try building the docker image
|
||||||
|
docker build -t cpu-test -f Dockerfile.cpu .
|
||||||
|
docker build --build-arg VLLM_CPU_DISABLE_AVX512="true" -t cpu-test-avx2 -f Dockerfile.cpu .
|
||||||
|
|
||||||
|
# Setup cleanup
|
||||||
|
remove_docker_container() { docker rm -f cpu-test cpu-test-avx2 || true; }
|
||||||
|
trap remove_docker_container EXIT
|
||||||
|
remove_docker_container
|
||||||
|
|
||||||
|
# Run the image
|
||||||
|
docker run -itd --entrypoint /bin/bash -v ~/.cache/huggingface:/root/.cache/huggingface --cpuset-cpus=48-95 \
|
||||||
|
--cpuset-mems=1 --network host -e HF_TOKEN --env VLLM_CPU_KVCACHE_SPACE=4 --name cpu-test cpu-test
|
||||||
|
docker run -itd --entrypoint /bin/bash -v ~/.cache/huggingface:/root/.cache/huggingface --cpuset-cpus=48-95 \
|
||||||
|
--cpuset-mems=1 --network host -e HF_TOKEN --env VLLM_CPU_KVCACHE_SPACE=4 --name cpu-test-avx2 cpu-test-avx2
|
||||||
|
|
||||||
|
# offline inference
|
||||||
|
docker exec cpu-test bash -c "python3 examples/offline_inference.py"
|
||||||
|
docker exec cpu-test-avx2 bash -c "python3 examples/offline_inference.py"
|
||||||
|
|
||||||
|
# Run basic model test
|
||||||
|
docker exec cpu-test bash -c "cd tests;
|
||||||
|
pip install pytest Pillow protobuf
|
||||||
|
cd ../
|
||||||
|
pytest -v -s tests/models -m \"not vlm\" --ignore=tests/models/test_embedding.py --ignore=tests/models/test_registry.py --ignore=tests/models/test_jamba.py" # Mamba on CPU is not supported
|
||||||
51
.buildkite/run-neuron-test.sh
Normal file
51
.buildkite/run-neuron-test.sh
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
# This script build the Neuron docker image and run the API server inside the container.
|
||||||
|
# It serves a sanity check for compilation and basic model usage.
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Try building the docker image
|
||||||
|
aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin 763104351884.dkr.ecr.us-west-2.amazonaws.com
|
||||||
|
|
||||||
|
# prune old image and containers to save disk space, and only once a day
|
||||||
|
# by using a timestamp file in tmp.
|
||||||
|
if [ -f /tmp/neuron-docker-build-timestamp ]; then
|
||||||
|
last_build=$(cat /tmp/neuron-docker-build-timestamp)
|
||||||
|
current_time=$(date +%s)
|
||||||
|
if [ $((current_time - last_build)) -gt 86400 ]; then
|
||||||
|
docker system prune -f
|
||||||
|
echo $current_time > /tmp/neuron-docker-build-timestamp
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo $(date +%s) > /tmp/neuron-docker-build-timestamp
|
||||||
|
fi
|
||||||
|
|
||||||
|
docker build -t neuron -f Dockerfile.neuron .
|
||||||
|
|
||||||
|
# Setup cleanup
|
||||||
|
remove_docker_container() { docker rm -f neuron || true; }
|
||||||
|
trap remove_docker_container EXIT
|
||||||
|
remove_docker_container
|
||||||
|
|
||||||
|
# Run the image
|
||||||
|
docker run --device=/dev/neuron0 --device=/dev/neuron1 --network host --name neuron neuron python3 -m vllm.entrypoints.api_server \
|
||||||
|
--model TinyLlama/TinyLlama-1.1B-Chat-v1.0 --max-num-seqs 8 --max-model-len 128 --block-size 128 --device neuron --tensor-parallel-size 2 &
|
||||||
|
|
||||||
|
# Wait for the server to start
|
||||||
|
wait_for_server_to_start() {
|
||||||
|
timeout=300
|
||||||
|
counter=0
|
||||||
|
|
||||||
|
while [ "$(curl -s -o /dev/null -w ''%{http_code}'' localhost:8000/health)" != "200" ]; do
|
||||||
|
sleep 1
|
||||||
|
counter=$((counter + 1))
|
||||||
|
if [ $counter -ge $timeout ]; then
|
||||||
|
echo "Timeout after $timeout seconds"
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
}
|
||||||
|
wait_for_server_to_start
|
||||||
|
|
||||||
|
# Test a simple prompt
|
||||||
|
curl -X POST -H "Content-Type: application/json" \
|
||||||
|
localhost:8000/generate \
|
||||||
|
-d '{"prompt": "San Francisco is a"}'
|
||||||
14
.buildkite/run-openvino-test.sh
Executable file
14
.buildkite/run-openvino-test.sh
Executable file
@ -0,0 +1,14 @@
|
|||||||
|
# This script build the OpenVINO docker image and run the offline inference inside the container.
|
||||||
|
# It serves a sanity check for compilation and basic model usage.
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
# Try building the docker image
|
||||||
|
docker build -t openvino-test -f Dockerfile.openvino .
|
||||||
|
|
||||||
|
# Setup cleanup
|
||||||
|
remove_docker_container() { docker rm -f openvino-test || true; }
|
||||||
|
trap remove_docker_container EXIT
|
||||||
|
remove_docker_container
|
||||||
|
|
||||||
|
# Run the image and launch offline inference
|
||||||
|
docker run --network host --env VLLM_OPENVINO_KVCACHE_SPACE=1 --name openvino-test openvino-test python3 /workspace/vllm/examples/offline_inference.py
|
||||||
14
.buildkite/run-xpu-test.sh
Normal file
14
.buildkite/run-xpu-test.sh
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
# This script build the CPU docker image and run the offline inference inside the container.
|
||||||
|
# It serves a sanity check for compilation and basic model usage.
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
# Try building the docker image
|
||||||
|
docker build -t xpu-test -f Dockerfile.xpu .
|
||||||
|
|
||||||
|
# Setup cleanup
|
||||||
|
remove_docker_container() { docker rm -f xpu-test || true; }
|
||||||
|
trap remove_docker_container EXIT
|
||||||
|
remove_docker_container
|
||||||
|
|
||||||
|
# Run the image and launch offline inference
|
||||||
|
docker run --network host --name xpu-test --device /dev/dri -v /dev/dri/by-path:/dev/dri/by-path xpu-test python3 examples/offline_inference.py
|
||||||
@ -1,69 +1,243 @@
|
|||||||
# In this file, you can add more tests to run either by adding a new step or
|
# In this file, you can add more tests to run either by adding a new step or
|
||||||
# adding a new command to an existing step. See different options here for examples.
|
# adding a new command to an existing step. See different options here for examples.
|
||||||
# This script will be feed into Jinja template in `test-template.j2` to generate
|
|
||||||
# the final pipeline yaml file.
|
# This script will be feed into Jinja template in `test-template-aws.j2` at
|
||||||
|
# https://github.com/vllm-project/buildkite-ci/blob/main/scripts/test-template-aws.j2
|
||||||
|
# to generate the final pipeline yaml file.
|
||||||
|
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- label: Regression Test
|
- label: Regression Test
|
||||||
|
mirror_hardwares: [amd]
|
||||||
command: pytest -v -s test_regression.py
|
command: pytest -v -s test_regression.py
|
||||||
working_dir: "/vllm-workspace/tests" # optional
|
working_dir: "/vllm-workspace/tests" # optional
|
||||||
|
|
||||||
- label: AsyncEngine Test
|
- label: AsyncEngine Test
|
||||||
|
#mirror_hardwares: [amd]
|
||||||
command: pytest -v -s async_engine
|
command: pytest -v -s async_engine
|
||||||
|
|
||||||
- label: Basic Correctness Test
|
- label: Basic Correctness Test
|
||||||
command: pytest -v -s --forked basic_correctness
|
mirror_hardwares: [amd]
|
||||||
|
commands:
|
||||||
|
- VLLM_ATTENTION_BACKEND=XFORMERS pytest -v -s basic_correctness/test_basic_correctness.py
|
||||||
|
- VLLM_ATTENTION_BACKEND=FLASH_ATTN pytest -v -s basic_correctness/test_basic_correctness.py
|
||||||
|
- VLLM_ATTENTION_BACKEND=XFORMERS pytest -v -s basic_correctness/test_chunked_prefill.py
|
||||||
|
- VLLM_ATTENTION_BACKEND=FLASH_ATTN pytest -v -s basic_correctness/test_chunked_prefill.py
|
||||||
|
- VLLM_TEST_ENABLE_ARTIFICIAL_PREEMPT=1 pytest -v -s basic_correctness/test_preemption.py
|
||||||
|
|
||||||
|
- label: Core Test
|
||||||
|
mirror_hardwares: [amd]
|
||||||
|
commands:
|
||||||
|
- pytest -v -s core
|
||||||
|
- pytest -v -s distributed/test_parallel_state.py
|
||||||
|
|
||||||
- label: Distributed Comm Ops Test
|
- label: Distributed Comm Ops Test
|
||||||
command: pytest -v -s --forked test_comm_ops.py
|
#mirror_hardwares: [amd]
|
||||||
working_dir: "/vllm-workspace/tests/distributed"
|
working_dir: "/vllm-workspace/tests"
|
||||||
num_gpus: 2 # only support 1 or 2 for now.
|
num_gpus: 2
|
||||||
|
commands:
|
||||||
|
- pytest -v -s distributed/test_comm_ops.py
|
||||||
|
- pytest -v -s distributed/test_shm_broadcast.py
|
||||||
|
|
||||||
|
- label: Distributed Tests (2 GPUs)
|
||||||
|
mirror_hardwares: [amd]
|
||||||
|
working_dir: "/vllm-workspace/tests"
|
||||||
|
num_gpus: 2
|
||||||
|
commands:
|
||||||
|
- bash ../.buildkite/download-images.sh
|
||||||
|
- VLLM_TEST_SAME_HOST=1 torchrun --nproc-per-node=4 distributed/test_same_node.py
|
||||||
|
- TEST_DIST_MODEL=facebook/opt-125m DISTRIBUTED_EXECUTOR_BACKEND=ray pytest -v -s distributed/test_basic_distributed_correctness.py
|
||||||
|
- TEST_DIST_MODEL=meta-llama/Llama-2-7b-hf DISTRIBUTED_EXECUTOR_BACKEND=ray pytest -v -s distributed/test_basic_distributed_correctness.py
|
||||||
|
- TEST_DIST_MODEL=facebook/opt-125m DISTRIBUTED_EXECUTOR_BACKEND=ray pytest -v -s distributed/test_chunked_prefill_distributed.py
|
||||||
|
- TEST_DIST_MODEL=meta-llama/Llama-2-7b-hf DISTRIBUTED_EXECUTOR_BACKEND=ray pytest -v -s distributed/test_chunked_prefill_distributed.py
|
||||||
|
- TEST_DIST_MODEL=llava-hf/llava-1.5-7b-hf DISTRIBUTED_EXECUTOR_BACKEND=ray pytest -v -s distributed/test_multimodal_broadcast.py
|
||||||
|
- TEST_DIST_MODEL=microsoft/Phi-3-vision-128k-instruct DISTRIBUTED_EXECUTOR_BACKEND=ray pytest -v -s distributed/test_multimodal_broadcast.py
|
||||||
|
- TEST_DIST_MODEL=facebook/opt-125m DISTRIBUTED_EXECUTOR_BACKEND=mp pytest -v -s distributed/test_basic_distributed_correctness.py
|
||||||
|
- TEST_DIST_MODEL=meta-llama/Llama-2-7b-hf DISTRIBUTED_EXECUTOR_BACKEND=mp pytest -v -s distributed/test_basic_distributed_correctness.py
|
||||||
|
- TEST_DIST_MODEL=facebook/opt-125m DISTRIBUTED_EXECUTOR_BACKEND=mp pytest -v -s distributed/test_chunked_prefill_distributed.py
|
||||||
|
- TEST_DIST_MODEL=meta-llama/Llama-2-7b-hf DISTRIBUTED_EXECUTOR_BACKEND=mp pytest -v -s distributed/test_chunked_prefill_distributed.py
|
||||||
|
- TEST_DIST_MODEL=llava-hf/llava-1.5-7b-hf DISTRIBUTED_EXECUTOR_BACKEND=mp pytest -v -s distributed/test_multimodal_broadcast.py
|
||||||
|
- TEST_DIST_MODEL=microsoft/Phi-3-vision-128k-instruct DISTRIBUTED_EXECUTOR_BACKEND=mp pytest -v -s distributed/test_multimodal_broadcast.py
|
||||||
|
- pytest -v -s spec_decode/e2e/test_integration_dist_tp2.py
|
||||||
|
- CUDA_VISIBLE_DEVICES=0,1 pytest -v -s test_sharded_state_loader.py
|
||||||
|
- CUDA_VISIBLE_DEVICES=0,1 pytest -v -s distributed/test_utils.py
|
||||||
|
|
||||||
|
- label: Distributed Tests (4 GPUs)
|
||||||
|
#mirror_hardwares: [amd]
|
||||||
|
working_dir: "/vllm-workspace/tests"
|
||||||
|
num_gpus: 4
|
||||||
|
commands:
|
||||||
|
- pytest -v -s distributed/test_pynccl.py
|
||||||
|
# We want to test that models which use 2 GPUs work with 4 GPUs, which is why we duplicate them here.
|
||||||
|
# See https://github.com/vllm-project/vllm/pull/5473#issuecomment-2166601837 for context.
|
||||||
|
- TEST_DIST_MODEL=facebook/opt-125m DISTRIBUTED_EXECUTOR_BACKEND=ray pytest -v -s distributed/test_basic_distributed_correctness.py
|
||||||
|
- TEST_DIST_MODEL=facebook/opt-125m DISTRIBUTED_EXECUTOR_BACKEND=mp pytest -v -s distributed/test_basic_distributed_correctness.py
|
||||||
|
- pytest -v -s spec_decode/e2e/test_integration_dist_tp4.py
|
||||||
|
|
||||||
|
- label: Pipeline Parallelism Test
|
||||||
|
working_dir: "/vllm-workspace/tests"
|
||||||
|
num_gpus: 4
|
||||||
|
commands:
|
||||||
|
- TP_SIZE=2 PP_SIZE=2 EAGER_MODE=1 CHUNKED_PREFILL=1 pytest -v -s distributed/test_pipeline_parallel.py
|
||||||
|
- TP_SIZE=2 PP_SIZE=2 EAGER_MODE=1 CHUNKED_PREFILL=0 pytest -v -s distributed/test_pipeline_parallel.py
|
||||||
|
- TP_SIZE=1 PP_SIZE=3 EAGER_MODE=1 CHUNKED_PREFILL=0 pytest -v -s distributed/test_pipeline_parallel.py
|
||||||
|
- PP_SIZE=4 EAGER_MODE=1 CHUNKED_PREFILL=1 pytest -v -s distributed/test_pipeline_parallel.py
|
||||||
|
- PP_SIZE=4 EAGER_MODE=1 CHUNKED_PREFILL=0 pytest -v -s distributed/test_pipeline_parallel.py
|
||||||
|
|
||||||
- label: Distributed Correctness Test
|
|
||||||
command: pytest -v -s --forked test_basic_distributed_correctness.py
|
|
||||||
working_dir: "/vllm-workspace/tests/distributed"
|
|
||||||
num_gpus: 2 # only support 1 or 2 for now.
|
|
||||||
|
|
||||||
- label: Engine Test
|
- label: Engine Test
|
||||||
command: pytest -v -s engine
|
mirror_hardwares: [amd]
|
||||||
|
command: pytest -v -s engine tokenization test_sequence.py test_config.py test_logger.py
|
||||||
|
|
||||||
- label: Entrypoints Test
|
- label: Entrypoints Test
|
||||||
command: pytest -v -s entrypoints
|
mirror_hardwares: [amd]
|
||||||
|
|
||||||
- label: Kernels Test
|
commands:
|
||||||
command: pytest -v -s kernels
|
- pytest -v -s entrypoints/llm
|
||||||
soft_fail: true
|
- pytest -v -s entrypoints/openai
|
||||||
|
|
||||||
|
- label: Examples Test
|
||||||
|
working_dir: "/vllm-workspace/examples"
|
||||||
|
mirror_hardwares: [amd]
|
||||||
|
commands:
|
||||||
|
# install aws cli for llava_example.py
|
||||||
|
# install tensorizer for tensorize_vllm_model.py
|
||||||
|
- pip install awscli tensorizer
|
||||||
|
- python3 offline_inference.py
|
||||||
|
- python3 offline_inference_with_prefix.py
|
||||||
|
- python3 llm_engine_example.py
|
||||||
|
- python3 llava_example.py
|
||||||
|
- python3 tensorize_vllm_model.py --model facebook/opt-125m serialize --serialized-directory /tmp/ --suffix v1 && python3 tensorize_vllm_model.py --model facebook/opt-125m deserialize --path-to-tensors /tmp/vllm/facebook/opt-125m/v1/model.tensors
|
||||||
|
|
||||||
|
- label: Inputs Test
|
||||||
|
#mirror_hardwares: [amd]
|
||||||
|
commands:
|
||||||
|
- bash ../.buildkite/download-images.sh
|
||||||
|
- pytest -v -s test_inputs.py
|
||||||
|
- pytest -v -s multimodal
|
||||||
|
|
||||||
|
- label: Kernels Test %N
|
||||||
|
#mirror_hardwares: [amd]
|
||||||
|
commands:
|
||||||
|
- pip install https://github.com/flashinfer-ai/flashinfer/releases/download/v0.0.7/flashinfer-0.0.7+cu121torch2.3-cp310-cp310-linux_x86_64.whl
|
||||||
|
- pytest -v -s kernels --shard-id=$$BUILDKITE_PARALLEL_JOB --num-shards=$$BUILDKITE_PARALLEL_JOB_COUNT
|
||||||
|
parallelism: 4
|
||||||
|
|
||||||
- label: Models Test
|
- label: Models Test
|
||||||
|
#mirror_hardwares: [amd]
|
||||||
commands:
|
commands:
|
||||||
- pytest -v -s models --forked
|
- pip install https://github.com/flashinfer-ai/flashinfer/releases/download/v0.0.7/flashinfer-0.0.7+cu121torch2.3-cp310-cp310-linux_x86_64.whl
|
||||||
soft_fail: true
|
- pytest -v -s models -m \"not vlm\"
|
||||||
|
|
||||||
|
- label: Vision Language Models Test
|
||||||
|
mirror_hardwares: [amd]
|
||||||
|
commands:
|
||||||
|
- bash ../.buildkite/download-images.sh
|
||||||
|
- pytest -v -s models -m vlm
|
||||||
|
|
||||||
- label: Prefix Caching Test
|
- label: Prefix Caching Test
|
||||||
|
mirror_hardwares: [amd]
|
||||||
commands:
|
commands:
|
||||||
- pytest -v -s prefix_caching
|
- pytest -v -s prefix_caching
|
||||||
|
|
||||||
- label: Samplers Test
|
- label: Samplers Test
|
||||||
command: pytest -v -s samplers --forked
|
#mirror_hardwares: [amd]
|
||||||
|
command: pytest -v -s samplers
|
||||||
|
|
||||||
|
- label: LogitsProcessor Test
|
||||||
|
mirror_hardwares: [amd]
|
||||||
|
command: pytest -v -s test_logits_processor.py
|
||||||
|
|
||||||
|
- label: Utils Test
|
||||||
|
command: pytest -v -s test_utils.py
|
||||||
|
|
||||||
- label: Worker Test
|
- label: Worker Test
|
||||||
|
mirror_hardwares: [amd]
|
||||||
command: pytest -v -s worker
|
command: pytest -v -s worker
|
||||||
|
|
||||||
- label: LoRA Test
|
- label: Speculative decoding tests
|
||||||
command: pytest -v -s lora --forked
|
#mirror_hardwares: [amd]
|
||||||
|
commands:
|
||||||
|
# See https://github.com/vllm-project/vllm/issues/5152
|
||||||
|
- export VLLM_ATTENTION_BACKEND=XFORMERS
|
||||||
|
- pytest -v -s spec_decode
|
||||||
|
|
||||||
|
- label: LoRA Test %N
|
||||||
|
#mirror_hardwares: [amd]
|
||||||
|
command: pytest -v -s lora --shard-id=$$BUILDKITE_PARALLEL_JOB --num-shards=$$BUILDKITE_PARALLEL_JOB_COUNT --ignore=lora/test_long_context.py
|
||||||
|
parallelism: 4
|
||||||
|
|
||||||
|
- label: LoRA Long Context (Distributed)
|
||||||
|
#mirror_hardwares: [amd]
|
||||||
|
num_gpus: 4
|
||||||
|
# This test runs llama 13B, so it is required to run on 4 GPUs.
|
||||||
|
commands:
|
||||||
|
# FIXIT: find out which code initialize cuda before running the test
|
||||||
|
# before the fix, we need to use spawn to test it
|
||||||
|
- export VLLM_WORKER_MULTIPROC_METHOD=spawn
|
||||||
|
- pytest -v -s -x lora/test_long_context.py
|
||||||
|
|
||||||
|
- label: Tensorizer Test
|
||||||
|
#mirror_hardwares: [amd]
|
||||||
|
command: apt-get install curl libsodium23 && pytest -v -s tensorizer_loader
|
||||||
|
|
||||||
- label: Metrics Test
|
- label: Metrics Test
|
||||||
|
mirror_hardwares: [amd]
|
||||||
command: pytest -v -s metrics
|
command: pytest -v -s metrics
|
||||||
|
|
||||||
|
- label: Quantization Test
|
||||||
|
#mirror_hardwares: [amd]
|
||||||
|
command: pytest -v -s quantization
|
||||||
|
|
||||||
|
- label: Tracing Test
|
||||||
|
commands:
|
||||||
|
- "pip install \
|
||||||
|
opentelemetry-sdk \
|
||||||
|
opentelemetry-api \
|
||||||
|
opentelemetry-exporter-otlp \
|
||||||
|
opentelemetry-semantic-conventions-ai"
|
||||||
|
- pytest -v -s tracing
|
||||||
|
|
||||||
- label: Benchmarks
|
- label: Benchmarks
|
||||||
working_dir: "/vllm-workspace/.buildkite"
|
working_dir: "/vllm-workspace/.buildkite"
|
||||||
|
mirror_hardwares: [amd]
|
||||||
commands:
|
commands:
|
||||||
- pip install aiohttp
|
- pip install aiohttp
|
||||||
- bash run-benchmarks.sh
|
- bash run-benchmarks.sh
|
||||||
|
|
||||||
|
- label: LM Eval Small Models
|
||||||
|
working_dir: "/vllm-workspace/.buildkite/lm-eval-harness"
|
||||||
|
commands:
|
||||||
|
- pip install lm-eval
|
||||||
|
- export VLLM_WORKER_MULTIPROC_METHOD=spawn
|
||||||
|
- bash ./run-tests.sh -c configs/models-small.txt -t 1
|
||||||
|
|
||||||
|
- label: LM Eval Large Models
|
||||||
|
gpu: a100
|
||||||
|
num_gpus: 4
|
||||||
|
working_dir: "/vllm-workspace/.buildkite/lm-eval-harness"
|
||||||
|
commands:
|
||||||
|
- pip install lm-eval
|
||||||
|
- export VLLM_WORKER_MULTIPROC_METHOD=spawn
|
||||||
|
- bash ./run-tests.sh -c configs/models-large.txt -t 4
|
||||||
|
|
||||||
- label: Documentation Build
|
- label: Documentation Build
|
||||||
working_dir: "/vllm-workspace/docs"
|
working_dir: "/vllm-workspace/test_docs/docs"
|
||||||
no_gpu: True
|
no_gpu: True
|
||||||
commands:
|
commands:
|
||||||
- pip install -r requirements-docs.txt
|
- pip install -r requirements-docs.txt
|
||||||
- SPHINXOPTS=\"-W\" make html
|
- SPHINXOPTS=\"-W\" make html
|
||||||
|
|
||||||
|
- label: Distributed Tests (A100)
|
||||||
|
gpu: a100
|
||||||
|
num_gpus: 4
|
||||||
|
commands:
|
||||||
|
# NOTE: don't test llama model here, it seems hf implementation is buggy
|
||||||
|
# see https://github.com/vllm-project/vllm/pull/5689 for details
|
||||||
|
- pytest -v -s distributed/test_custom_all_reduce.py
|
||||||
|
- TEST_DIST_MODEL=facebook/opt-125m DISTRIBUTED_EXECUTOR_BACKEND=ray pytest -v -s distributed/test_basic_distributed_correctness.py
|
||||||
|
- TEST_DIST_MODEL=facebook/opt-125m DISTRIBUTED_EXECUTOR_BACKEND=mp pytest -v -s distributed/test_basic_distributed_correctness.py
|
||||||
|
- pip install https://github.com/flashinfer-ai/flashinfer/releases/download/v0.0.7/flashinfer-0.0.7+cu121torch2.3-cp310-cp310-linux_x86_64.whl
|
||||||
|
- VLLM_ATTENTION_BACKEND=FLASHINFER TEST_DIST_MODEL=facebook/opt-125m DISTRIBUTED_EXECUTOR_BACKEND=ray pytest -v -s distributed/test_basic_distributed_correctness.py
|
||||||
|
- VLLM_ATTENTION_BACKEND=FLASHINFER TEST_DIST_MODEL=meta-llama/Meta-Llama-3-8B DISTRIBUTED_EXECUTOR_BACKEND=ray pytest -v -s distributed/test_basic_distributed_correctness.py
|
||||||
|
- pytest -v -s -x lora/test_mixtral.py
|
||||||
|
|||||||
@ -1,56 +0,0 @@
|
|||||||
{% set docker_image = "us-central1-docker.pkg.dev/vllm-405802/vllm-ci-test-repo/vllm-test:$BUILDKITE_COMMIT" %}
|
|
||||||
{% set default_num_gpu = 1 %}
|
|
||||||
{% set default_working_dir = "/vllm-workspace/tests" %}
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- label: ":docker: build image"
|
|
||||||
commands:
|
|
||||||
- "docker build --build-arg max_jobs=16 --tag {{ docker_image }} --target test --progress plain ."
|
|
||||||
- "docker push {{ docker_image }}"
|
|
||||||
env:
|
|
||||||
DOCKER_BUILDKIT: "1"
|
|
||||||
retry:
|
|
||||||
automatic:
|
|
||||||
- exit_status: -1 # Agent was lost
|
|
||||||
limit: 5
|
|
||||||
- wait
|
|
||||||
|
|
||||||
{% for step in steps %}
|
|
||||||
- label: "{{ step.label }}"
|
|
||||||
agents:
|
|
||||||
queue: kubernetes
|
|
||||||
soft_fail: {{ step.soft_fail or false }}
|
|
||||||
retry:
|
|
||||||
automatic:
|
|
||||||
- exit_status: -1 # Agent was lost
|
|
||||||
limit: 5
|
|
||||||
plugins:
|
|
||||||
- kubernetes:
|
|
||||||
podSpec:
|
|
||||||
volumes:
|
|
||||||
- name: dshm
|
|
||||||
emptyDir:
|
|
||||||
medium: Memory
|
|
||||||
containers:
|
|
||||||
- image: "{{ docker_image }}"
|
|
||||||
command: ["bash"]
|
|
||||||
args:
|
|
||||||
- '-c'
|
|
||||||
- "'cd {{ (step.working_dir or default_working_dir) | safe }} && {{ step.command or (step.commands | join(' && ')) | safe }}'"
|
|
||||||
{% if not step.no_gpu %}
|
|
||||||
resources:
|
|
||||||
requests:
|
|
||||||
nvidia.com/gpu: "{{ step.num_gpus or default_num_gpu }}"
|
|
||||||
limits:
|
|
||||||
nvidia.com/gpu: "{{ step.num_gpus or default_num_gpu }}"
|
|
||||||
{% endif %}
|
|
||||||
env:
|
|
||||||
- name: HF_TOKEN
|
|
||||||
valueFrom:
|
|
||||||
secretKeyRef:
|
|
||||||
name: hf-token-secret
|
|
||||||
key: token
|
|
||||||
volumeMounts:
|
|
||||||
- mountPath: /dev/shm
|
|
||||||
name: dshm
|
|
||||||
{% endfor %}
|
|
||||||
26
.clang-format
Normal file
26
.clang-format
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
BasedOnStyle: Google
|
||||||
|
UseTab: Never
|
||||||
|
IndentWidth: 2
|
||||||
|
ColumnLimit: 80
|
||||||
|
|
||||||
|
# Force pointers to the type for C++.
|
||||||
|
DerivePointerAlignment: false
|
||||||
|
PointerAlignment: Left
|
||||||
|
|
||||||
|
# Reordering #include statements can (and currently will) introduce errors
|
||||||
|
SortIncludes: false
|
||||||
|
|
||||||
|
# Style choices
|
||||||
|
AlignConsecutiveAssignments: false
|
||||||
|
AlignConsecutiveDeclarations: false
|
||||||
|
IndentPPDirectives: BeforeHash
|
||||||
|
|
||||||
|
IncludeCategories:
|
||||||
|
- Regex: '^<'
|
||||||
|
Priority: 4
|
||||||
|
- Regex: '^"(llvm|llvm-c|clang|clang-c|mlir|mlir-c)/'
|
||||||
|
Priority: 3
|
||||||
|
- Regex: '^"(qoda|\.\.)/'
|
||||||
|
Priority: 2
|
||||||
|
- Regex: '.*'
|
||||||
|
Priority: 1
|
||||||
22
.github/ISSUE_TEMPLATE/100-documentation.yml
vendored
Normal file
22
.github/ISSUE_TEMPLATE/100-documentation.yml
vendored
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
name: 📚 Documentation
|
||||||
|
description: Report an issue related to https://docs.vllm.ai/
|
||||||
|
title: "[Doc]: "
|
||||||
|
labels: ["documentation"]
|
||||||
|
|
||||||
|
body:
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: 📚 The doc issue
|
||||||
|
description: >
|
||||||
|
A clear and concise description of what content in https://docs.vllm.ai/ is an issue.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Suggest a potential alternative/fix
|
||||||
|
description: >
|
||||||
|
Tell us how we could improve the documentation in this regard.
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: >
|
||||||
|
Thanks for contributing 🎉!
|
||||||
40
.github/ISSUE_TEMPLATE/200-installation.yml
vendored
Normal file
40
.github/ISSUE_TEMPLATE/200-installation.yml
vendored
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
name: 🛠️ Installation
|
||||||
|
description: Report an issue here when you hit errors during installation.
|
||||||
|
title: "[Installation]: "
|
||||||
|
labels: ["installation"]
|
||||||
|
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: >
|
||||||
|
#### Before submitting an issue, please make sure the issue hasn't been already addressed by searching through [the existing and past issues](https://github.com/vllm-project/vllm/issues?q=is%3Aissue+sort%3Acreated-desc+).
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Your current environment
|
||||||
|
description: |
|
||||||
|
Please run the following and paste the output below.
|
||||||
|
```sh
|
||||||
|
wget https://raw.githubusercontent.com/vllm-project/vllm/main/collect_env.py
|
||||||
|
# For security purposes, please feel free to check the contents of collect_env.py before running it.
|
||||||
|
python collect_env.py
|
||||||
|
```
|
||||||
|
It is suggested to download and execute the latest script, as vllm might frequently update the diagnosis information needed for accurately and quickly responding to issues.
|
||||||
|
value: |
|
||||||
|
```text
|
||||||
|
The output of `python collect_env.py`
|
||||||
|
```
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: How you are installing vllm
|
||||||
|
description: |
|
||||||
|
Paste the full command you are trying to execute.
|
||||||
|
value: |
|
||||||
|
```sh
|
||||||
|
pip install -vvv vllm
|
||||||
|
```
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: >
|
||||||
|
Thanks for contributing 🎉!
|
||||||
38
.github/ISSUE_TEMPLATE/300-usage.yml
vendored
Normal file
38
.github/ISSUE_TEMPLATE/300-usage.yml
vendored
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
name: 💻 Usage
|
||||||
|
description: Raise an issue here if you don't know how to use vllm.
|
||||||
|
title: "[Usage]: "
|
||||||
|
labels: ["usage"]
|
||||||
|
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: >
|
||||||
|
#### Before submitting an issue, please make sure the issue hasn't been already addressed by searching through [the existing and past issues](https://github.com/vllm-project/vllm/issues?q=is%3Aissue+sort%3Acreated-desc+).
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Your current environment
|
||||||
|
description: |
|
||||||
|
Please run the following and paste the output below.
|
||||||
|
```sh
|
||||||
|
wget https://raw.githubusercontent.com/vllm-project/vllm/main/collect_env.py
|
||||||
|
# For security purposes, please feel free to check the contents of collect_env.py before running it.
|
||||||
|
python collect_env.py
|
||||||
|
```
|
||||||
|
It is suggested to download and execute the latest script, as vllm might frequently update the diagnosis information needed for accurately and quickly responding to issues.
|
||||||
|
value: |
|
||||||
|
```text
|
||||||
|
The output of `python collect_env.py`
|
||||||
|
```
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: How would you like to use vllm
|
||||||
|
description: |
|
||||||
|
A detailed description of how you want to use vllm.
|
||||||
|
value: |
|
||||||
|
I want to run inference of a [specific model](put link here). I don't know how to integrate it with vllm.
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: >
|
||||||
|
Thanks for contributing 🎉!
|
||||||
86
.github/ISSUE_TEMPLATE/400-bug report.yml
vendored
Normal file
86
.github/ISSUE_TEMPLATE/400-bug report.yml
vendored
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
name: 🐛 Bug report
|
||||||
|
description: Raise an issue here if you find a bug.
|
||||||
|
title: "[Bug]: "
|
||||||
|
labels: ["bug"]
|
||||||
|
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: >
|
||||||
|
#### Before submitting an issue, please make sure the issue hasn't been already addressed by searching through [the existing and past issues](https://github.com/vllm-project/vllm/issues?q=is%3Aissue+sort%3Acreated-desc+).
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Your current environment
|
||||||
|
description: |
|
||||||
|
Please run the following and paste the output below.
|
||||||
|
```sh
|
||||||
|
wget https://raw.githubusercontent.com/vllm-project/vllm/main/collect_env.py
|
||||||
|
# For security purposes, please feel free to check the contents of collect_env.py before running it.
|
||||||
|
python collect_env.py
|
||||||
|
```
|
||||||
|
It is suggested to download and execute the latest script, as vllm might frequently update the diagnosis information needed for accurately and quickly responding to issues.
|
||||||
|
value: |
|
||||||
|
```text
|
||||||
|
The output of `python collect_env.py`
|
||||||
|
```
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: 🐛 Describe the bug
|
||||||
|
description: |
|
||||||
|
Please provide a clear and concise description of what the bug is.
|
||||||
|
|
||||||
|
If relevant, add a minimal example so that we can reproduce the error by running the code. It is very important for the snippet to be as succinct (minimal) as possible, so please take time to trim down any irrelevant code to help us debug efficiently. We are going to copy-paste your code and we expect to get the same result as you did: avoid any external data, and include the relevant imports, etc. For example:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from vllm import LLM, SamplingParams
|
||||||
|
|
||||||
|
prompts = [
|
||||||
|
"Hello, my name is",
|
||||||
|
"The president of the United States is",
|
||||||
|
"The capital of France is",
|
||||||
|
"The future of AI is",
|
||||||
|
]
|
||||||
|
sampling_params = SamplingParams(temperature=0.8, top_p=0.95)
|
||||||
|
|
||||||
|
llm = LLM(model="facebook/opt-125m")
|
||||||
|
|
||||||
|
outputs = llm.generate(prompts, sampling_params)
|
||||||
|
|
||||||
|
# Print the outputs.
|
||||||
|
for output in outputs:
|
||||||
|
prompt = output.prompt
|
||||||
|
generated_text = output.outputs[0].text
|
||||||
|
print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")
|
||||||
|
```
|
||||||
|
|
||||||
|
If the code is too long (hopefully, it isn't), feel free to put it in a public gist and link it in the issue: https://gist.github.com.
|
||||||
|
|
||||||
|
Please also paste or describe the results you observe instead of the expected results. If you observe an error, please paste the error message including the **full** traceback of the exception. It may be relevant to wrap error messages in ```` ```triple quotes blocks``` ````.
|
||||||
|
|
||||||
|
Please set the environment variable `export VLLM_LOGGING_LEVEL=DEBUG` to turn on more logging to help debugging potential issues.
|
||||||
|
|
||||||
|
If you experienced crashes or hangs, it would be helpful to run vllm with `export VLLM_TRACE_FUNCTION=1` . All the function calls in vllm will be recorded. Inspect these log files, and tell which function crashes or hangs.
|
||||||
|
placeholder: |
|
||||||
|
A clear and concise description of what the bug is.
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Sample code to reproduce the problem
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
|
The error message you got, with the full traceback.
|
||||||
|
```
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: >
|
||||||
|
⚠️ Please separate bugs of `transformers` implementation or usage from bugs of `vllm`. If you think anything is wrong with the models' output:
|
||||||
|
|
||||||
|
- Try the counterpart of `transformers` first. If the error appears, please go to [their issues](https://github.com/huggingface/transformers/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc).
|
||||||
|
|
||||||
|
- If the error only appears in vllm, please provide the detailed script of how you run `transformers` and `vllm`, also highlight the difference and what you expect.
|
||||||
|
|
||||||
|
Thanks for contributing 🎉!
|
||||||
31
.github/ISSUE_TEMPLATE/500-feature request.yml
vendored
Normal file
31
.github/ISSUE_TEMPLATE/500-feature request.yml
vendored
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
name: 🚀 Feature request
|
||||||
|
description: Submit a proposal/request for a new vllm feature
|
||||||
|
title: "[Feature]: "
|
||||||
|
labels: ["feature request"]
|
||||||
|
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: >
|
||||||
|
#### Before submitting an issue, please make sure the issue hasn't been already addressed by searching through [the existing and past issues](https://github.com/vllm-project/vllm/issues?q=is%3Aissue+sort%3Acreated-desc+).
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: 🚀 The feature, motivation and pitch
|
||||||
|
description: >
|
||||||
|
A clear and concise description of the feature proposal. Please outline the motivation for the proposal. Is your feature request related to a specific problem? e.g., *"I'm working on X and would like Y to be possible"*. If this is related to another GitHub issue, please link here too.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Alternatives
|
||||||
|
description: >
|
||||||
|
A description of any alternative solutions or features you've considered, if any.
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Additional context
|
||||||
|
description: >
|
||||||
|
Add any other context or screenshots about the feature request.
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: >
|
||||||
|
Thanks for contributing 🎉!
|
||||||
33
.github/ISSUE_TEMPLATE/600-new model.yml
vendored
Normal file
33
.github/ISSUE_TEMPLATE/600-new model.yml
vendored
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
name: 🤗 Support request for a new model from huggingface
|
||||||
|
description: Submit a proposal/request for a new model from huggingface
|
||||||
|
title: "[New Model]: "
|
||||||
|
labels: ["new model"]
|
||||||
|
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: >
|
||||||
|
#### Before submitting an issue, please make sure the issue hasn't been already addressed by searching through [the existing and past issues](https://github.com/vllm-project/vllm/issues?q=is%3Aissue+sort%3Acreated-desc+).
|
||||||
|
|
||||||
|
#### We also highly recommend you read https://docs.vllm.ai/en/latest/models/adding_model.html first to understand how to add a new model.
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: The model to consider.
|
||||||
|
description: >
|
||||||
|
A huggingface url, pointing to the model, e.g. https://huggingface.co/openai-community/gpt2 .
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: The closest model vllm already supports.
|
||||||
|
description: >
|
||||||
|
Here is the list of models already supported by vllm: https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/models . Which model is the most similar to the model you want to add support for?
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: What's your difficulty of supporting the model you want?
|
||||||
|
description: >
|
||||||
|
For example, any new operators or new architecture?
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: >
|
||||||
|
Thanks for contributing 🎉!
|
||||||
52
.github/ISSUE_TEMPLATE/700-performance discussion.yml
vendored
Normal file
52
.github/ISSUE_TEMPLATE/700-performance discussion.yml
vendored
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
name: ⚡ Discussion on the performance of vllm
|
||||||
|
description: Submit a proposal/discussion about the performance of vllm
|
||||||
|
title: "[Performance]: "
|
||||||
|
labels: ["performance"]
|
||||||
|
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: >
|
||||||
|
#### Before submitting an issue, please make sure the issue hasn't been already addressed by searching through [the existing and past issues](https://github.com/vllm-project/vllm/issues?q=is%3Aissue+sort%3Acreated-desc+).
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Proposal to improve performance
|
||||||
|
description: >
|
||||||
|
How do you plan to improve vllm's performance?
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Report of performance regression
|
||||||
|
description: >
|
||||||
|
Please provide detailed description of performance comparison to confirm the regression. You may want to run the benchmark script at https://github.com/vllm-project/vllm/tree/main/benchmarks .
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Misc discussion on performance
|
||||||
|
description: >
|
||||||
|
Anything about the performance.
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Your current environment (if you think it is necessary)
|
||||||
|
description: |
|
||||||
|
Please run the following and paste the output below.
|
||||||
|
```sh
|
||||||
|
wget https://raw.githubusercontent.com/vllm-project/vllm/main/collect_env.py
|
||||||
|
# For security purposes, please feel free to check the contents of collect_env.py before running it.
|
||||||
|
python collect_env.py
|
||||||
|
```
|
||||||
|
It is suggested to download and execute the latest script, as vllm might frequently update the diagnosis information needed for accurately and quickly responding to issues.
|
||||||
|
value: |
|
||||||
|
```text
|
||||||
|
The output of `python collect_env.py`
|
||||||
|
```
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: >
|
||||||
|
Thanks for contributing 🎉!
|
||||||
49
.github/ISSUE_TEMPLATE/750-RFC.yml
vendored
Normal file
49
.github/ISSUE_TEMPLATE/750-RFC.yml
vendored
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
name: 💬 Request for comments (RFC).
|
||||||
|
description: Ask for feedback on major architectural changes or design choices.
|
||||||
|
title: "[RFC]: "
|
||||||
|
labels: ["RFC"]
|
||||||
|
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: >
|
||||||
|
#### Please take a look at previous [RFCs](https://github.com/vllm-project/vllm/issues?q=label%3ARFC+sort%3Aupdated-desc) for reference.
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Motivation.
|
||||||
|
description: >
|
||||||
|
The motivation of the RFC.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Proposed Change.
|
||||||
|
description: >
|
||||||
|
The proposed change of the RFC.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Feedback Period.
|
||||||
|
description: >
|
||||||
|
The feedback period of the RFC. Usually at least one week.
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: CC List.
|
||||||
|
description: >
|
||||||
|
The list of people you want to CC.
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Any Other Things.
|
||||||
|
description: >
|
||||||
|
Any other things you would like to mention.
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: >
|
||||||
|
Thanks for contributing 🎉!
|
||||||
21
.github/ISSUE_TEMPLATE/800-misc discussion.yml
vendored
Normal file
21
.github/ISSUE_TEMPLATE/800-misc discussion.yml
vendored
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
name: 🎲 Misc/random discussions that do not fit into the above categories.
|
||||||
|
description: Submit a discussion as you like. Note that developers are heavily overloaded and we mainly rely on community users to answer these issues.
|
||||||
|
title: "[Misc]: "
|
||||||
|
labels: ["misc"]
|
||||||
|
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: >
|
||||||
|
#### Before submitting an issue, please make sure the issue hasn't been already addressed by searching through [the existing and past issues](https://github.com/vllm-project/vllm/issues?q=is%3Aissue+sort%3Acreated-desc+).
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Anything you want to discuss about vllm.
|
||||||
|
description: >
|
||||||
|
Anything you want to discuss about vllm.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: >
|
||||||
|
Thanks for contributing 🎉!
|
||||||
1
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
1
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
blank_issues_enabled: false
|
||||||
64
.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
64
.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
FILL IN THE PR DESCRIPTION HERE
|
||||||
|
|
||||||
|
FIX #xxxx (*link existing issues this PR will resolve*)
|
||||||
|
|
||||||
|
**BEFORE SUBMITTING, PLEASE READ THE CHECKLIST BELOW AND FILL IN THE DESCRIPTION ABOVE**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<!-- inside this <details> section, markdown rendering does not work, so we use raw html here. -->
|
||||||
|
<summary><b> PR Checklist (Click to Expand) </b></summary>
|
||||||
|
|
||||||
|
<p>Thank you for your contribution to vLLM! Before submitting the pull request, please ensure the PR meets the following criteria. This helps vLLM maintain the code quality and improve the efficiency of the review process.</p>
|
||||||
|
|
||||||
|
<h3>PR Title and Classification</h3>
|
||||||
|
<p>Only specific types of PRs will be reviewed. The PR title is prefixed appropriately to indicate the type of change. Please use one of the following:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>[Bugfix]</code> for bug fixes.</li>
|
||||||
|
<li><code>[CI/Build]</code> for build or continuous integration improvements.</li>
|
||||||
|
<li><code>[Doc]</code> for documentation fixes and improvements.</li>
|
||||||
|
<li><code>[Model]</code> for adding a new model or improving an existing model. Model name should appear in the title.</li>
|
||||||
|
<li><code>[Frontend]</code> For changes on the vLLM frontend (e.g., OpenAI API server, <code>LLM</code> class, etc.) </li>
|
||||||
|
<li><code>[Kernel]</code> for changes affecting CUDA kernels or other compute kernels.</li>
|
||||||
|
<li><code>[Core]</code> for changes in the core vLLM logic (e.g., <code>LLMEngine</code>, <code>AsyncLLMEngine</code>, <code>Scheduler</code>, etc.)</li>
|
||||||
|
<li><code>[Hardware][Vendor]</code> for hardware-specific changes. Vendor name should appear in the prefix (e.g., <code>[Hardware][AMD]</code>).</li>
|
||||||
|
<li><code>[Misc]</code> for PRs that do not fit the above categories. Please use this sparingly.</li>
|
||||||
|
</ul>
|
||||||
|
<p><strong>Note:</strong> If the PR spans more than one category, please include all relevant prefixes.</p>
|
||||||
|
|
||||||
|
<h3>Code Quality</h3>
|
||||||
|
|
||||||
|
<p>The PR need to meet the following code quality standards:</p>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li>We adhere to <a href="https://google.github.io/styleguide/pyguide.html">Google Python style guide</a> and <a href="https://google.github.io/styleguide/cppguide.html">Google C++ style guide</a>.</li>
|
||||||
|
<li>Pass all linter checks. Please use <a href="https://github.com/vllm-project/vllm/blob/main/format.sh"><code>format.sh</code></a> to format your code.</li>
|
||||||
|
<li>The code need to be well-documented to ensure future contributors can easily understand the code.</li>
|
||||||
|
<li>Include sufficient tests to ensure the project to stay correct and robust. This includes both unit tests and integration tests.</li>
|
||||||
|
<li>Please add documentation to <code>docs/source/</code> if the PR modifies the user-facing behaviors of vLLM. It helps vLLM user understand and utilize the new features or changes.</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<h3>Notes for Large Changes</h3>
|
||||||
|
<p>Please keep the changes as concise as possible. For major architectural changes (>500 LOC excluding kernel/data/config/test), we would expect a GitHub issue (RFC) discussing the technical design and justification. Otherwise, we will tag it with <code>rfc-required</code> and might not go through the PR.</p>
|
||||||
|
|
||||||
|
<h3>What to Expect for the Reviews</h3>
|
||||||
|
|
||||||
|
<p>The goal of the vLLM team is to be a <i>transparent reviewing machine</i>. We would like to make the review process transparent and efficient and make sure no contributor feel confused or frustrated. However, the vLLM team is small, so we need to prioritize some PRs over others. Here is what you can expect from the review process: </p>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li> After the PR is submitted, the PR will be assigned to a reviewer. Every reviewer will pick up the PRs based on their expertise and availability.</li>
|
||||||
|
<li> After the PR is assigned, the reviewer will provide status update every 2-3 days. If the PR is not reviewed within 7 days, please feel free to ping the reviewer or the vLLM team.</li>
|
||||||
|
<li> After the review, the reviewer will put an <code> action-required</code> label on the PR if there are changes required. The contributor should address the comments and ping the reviewer to re-review the PR.</li>
|
||||||
|
<li> Please respond to all comments within a reasonable time frame. If a comment isn't clear or you disagree with a suggestion, feel free to ask for clarification or discuss the suggestion.
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<h3>Thank You</h3>
|
||||||
|
|
||||||
|
<p> Finally, thank you for taking the time to read these guidelines and for your interest in contributing to vLLM. Your contributions make vLLM a great tool for everyone! </p>
|
||||||
|
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
|
||||||
42
.github/workflows/clang-format.yml
vendored
Normal file
42
.github/workflows/clang-format.yml
vendored
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
name: clang-format
|
||||||
|
|
||||||
|
on:
|
||||||
|
# Trigger the workflow on push or pull request,
|
||||||
|
# but only for the main branch
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
clang-format:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
python-version: ["3.11"]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
- name: Set up Python ${{ matrix.python-version }}
|
||||||
|
uses: actions/setup-python@v2
|
||||||
|
with:
|
||||||
|
python-version: ${{ matrix.python-version }}
|
||||||
|
- name: Install dependencies
|
||||||
|
run: |
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
pip install clang-format==18.1.5
|
||||||
|
- name: Running clang-format
|
||||||
|
run: |
|
||||||
|
EXCLUDES=(
|
||||||
|
'csrc/moe/topk_softmax_kernels.cu'
|
||||||
|
'csrc/punica/bgmv/bgmv_bf16_bf16_bf16.cu'
|
||||||
|
'csrc/punica/bgmv/bgmv_config.h'
|
||||||
|
'csrc/punica/bgmv/bgmv_impl.cuh'
|
||||||
|
'csrc/punica/bgmv/vec_dtypes.cuh'
|
||||||
|
'csrc/punica/punica_ops.cu'
|
||||||
|
'csrc/punica/type_convert.h'
|
||||||
|
)
|
||||||
|
find csrc/ \( -name '*.h' -o -name '*.cpp' -o -name '*.cu' -o -name '*.cuh' \) -print \
|
||||||
|
| grep -vFf <(printf "%s\n" "${EXCLUDES[@]}") \
|
||||||
|
| xargs clang-format --dry-run --Werror
|
||||||
51
.github/workflows/mypy.yaml
vendored
Normal file
51
.github/workflows/mypy.yaml
vendored
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
name: mypy
|
||||||
|
|
||||||
|
on:
|
||||||
|
# Trigger the workflow on push or pull request,
|
||||||
|
# but only for the main branch
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
ruff:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
python-version: ["3.8", "3.9", "3.10", "3.11"]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
- name: Set up Python ${{ matrix.python-version }}
|
||||||
|
uses: actions/setup-python@v2
|
||||||
|
with:
|
||||||
|
python-version: ${{ matrix.python-version }}
|
||||||
|
- name: Install dependencies
|
||||||
|
run: |
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
pip install mypy==1.9.0
|
||||||
|
pip install types-setuptools
|
||||||
|
pip install types-PyYAML
|
||||||
|
pip install types-requests
|
||||||
|
pip install types-setuptools
|
||||||
|
- name: Mypy
|
||||||
|
run: |
|
||||||
|
mypy vllm/attention --config-file pyproject.toml
|
||||||
|
mypy vllm/core --config-file pyproject.toml
|
||||||
|
mypy vllm/distributed --config-file pyproject.toml
|
||||||
|
mypy vllm/entrypoints --config-file pyproject.toml
|
||||||
|
mypy vllm/executor --config-file pyproject.toml
|
||||||
|
mypy vllm/multimodal --config-file pyproject.toml
|
||||||
|
mypy vllm/usage --config-file pyproject.toml
|
||||||
|
mypy vllm/*.py --config-file pyproject.toml
|
||||||
|
mypy vllm/transformers_utils --config-file pyproject.toml
|
||||||
|
mypy vllm/engine --config-file pyproject.toml
|
||||||
|
mypy vllm/worker --config-file pyproject.toml
|
||||||
|
mypy vllm/spec_decode --config-file pyproject.toml
|
||||||
|
mypy vllm/model_executor --config-file pyproject.toml
|
||||||
|
mypy vllm/lora --config-file pyproject.toml
|
||||||
|
mypy vllm/logging --config-file pyproject.toml
|
||||||
|
mypy tests --config-file pyproject.toml
|
||||||
|
|
||||||
10
.github/workflows/publish.yml
vendored
10
.github/workflows/publish.yml
vendored
@ -49,13 +49,19 @@ jobs:
|
|||||||
matrix:
|
matrix:
|
||||||
os: ['ubuntu-20.04']
|
os: ['ubuntu-20.04']
|
||||||
python-version: ['3.8', '3.9', '3.10', '3.11']
|
python-version: ['3.8', '3.9', '3.10', '3.11']
|
||||||
pytorch-version: ['2.1.2'] # Must be the most recent version that meets requirements.txt.
|
pytorch-version: ['2.3.0'] # Must be the most recent version that meets requirements-cuda.txt.
|
||||||
cuda-version: ['11.8', '12.1']
|
cuda-version: ['11.8', '12.1']
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Setup ccache
|
||||||
|
uses: hendrikmuhs/ccache-action@v1.2
|
||||||
|
with:
|
||||||
|
create-symlink: true
|
||||||
|
key: ${{ github.job }}-${{ matrix.python-version }}-${{ matrix.cuda-version }}
|
||||||
|
|
||||||
- name: Set up Linux Env
|
- name: Set up Linux Env
|
||||||
if: ${{ runner.os == 'Linux' }}
|
if: ${{ runner.os == 'Linux' }}
|
||||||
run: |
|
run: |
|
||||||
@ -76,6 +82,8 @@ jobs:
|
|||||||
|
|
||||||
- name: Build wheel
|
- name: Build wheel
|
||||||
shell: bash
|
shell: bash
|
||||||
|
env:
|
||||||
|
CMAKE_BUILD_TYPE: Release # do not compile with debug symbol to reduce wheel size
|
||||||
run: |
|
run: |
|
||||||
bash -x .github/workflows/scripts/build.sh ${{ matrix.python-version }} ${{ matrix.cuda-version }}
|
bash -x .github/workflows/scripts/build.sh ${{ matrix.python-version }} ${{ matrix.cuda-version }}
|
||||||
wheel_name=$(ls dist/*whl | xargs -n 1 basename)
|
wheel_name=$(ls dist/*whl | xargs -n 1 basename)
|
||||||
|
|||||||
11
.github/workflows/ruff.yml
vendored
11
.github/workflows/ruff.yml
vendored
@ -15,7 +15,7 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
python-version: ["3.10"]
|
python-version: ["3.8", "3.9", "3.10", "3.11"]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
- name: Set up Python ${{ matrix.python-version }}
|
- name: Set up Python ${{ matrix.python-version }}
|
||||||
@ -25,10 +25,13 @@ jobs:
|
|||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: |
|
run: |
|
||||||
python -m pip install --upgrade pip
|
python -m pip install --upgrade pip
|
||||||
pip install ruff==0.1.5 codespell==2.2.6 tomli==2.0.1
|
pip install ruff==0.1.5 codespell==2.3.0 tomli==2.0.1 isort==5.13.2
|
||||||
- name: Analysing the code with ruff
|
- name: Analysing the code with ruff
|
||||||
run: |
|
run: |
|
||||||
ruff vllm tests
|
ruff .
|
||||||
- name: Spelling check with codespell
|
- name: Spelling check with codespell
|
||||||
run: |
|
run: |
|
||||||
codespell --toml pyproject.toml
|
codespell --toml pyproject.toml
|
||||||
|
- name: Run isort
|
||||||
|
run: |
|
||||||
|
isort . --check-only
|
||||||
|
|||||||
5
.github/workflows/scripts/build.sh
vendored
5
.github/workflows/scripts/build.sh
vendored
@ -9,12 +9,13 @@ LD_LIBRARY_PATH=${cuda_home}/lib64:$LD_LIBRARY_PATH
|
|||||||
|
|
||||||
# Install requirements
|
# Install requirements
|
||||||
$python_executable -m pip install wheel packaging
|
$python_executable -m pip install wheel packaging
|
||||||
$python_executable -m pip install -r requirements.txt
|
$python_executable -m pip install -r requirements-cuda.txt
|
||||||
|
|
||||||
# Limit the number of parallel jobs to avoid OOM
|
# Limit the number of parallel jobs to avoid OOM
|
||||||
export MAX_JOBS=1
|
export MAX_JOBS=1
|
||||||
# Make sure punica is built for the release (for LoRA)
|
# Make sure punica is built for the release (for LoRA)
|
||||||
export VLLM_INSTALL_PUNICA_KERNELS=1
|
export VLLM_INSTALL_PUNICA_KERNELS=1
|
||||||
|
# Make sure release wheels are built for the following architectures
|
||||||
|
export TORCH_CUDA_ARCH_LIST="7.0 7.5 8.0 8.6 8.9 9.0+PTX"
|
||||||
# Build
|
# Build
|
||||||
$python_executable setup.py bdist_wheel --dist-dir=dist
|
$python_executable setup.py bdist_wheel --dist-dir=dist
|
||||||
|
|||||||
2
.github/workflows/scripts/create_release.js
vendored
2
.github/workflows/scripts/create_release.js
vendored
@ -8,7 +8,7 @@ module.exports = async (github, context, core) => {
|
|||||||
generate_release_notes: true,
|
generate_release_notes: true,
|
||||||
name: process.env.RELEASE_TAG,
|
name: process.env.RELEASE_TAG,
|
||||||
owner: context.repo.owner,
|
owner: context.repo.owner,
|
||||||
prerelease: false,
|
prerelease: true,
|
||||||
repo: context.repo.repo,
|
repo: context.repo.repo,
|
||||||
tag_name: process.env.RELEASE_TAG,
|
tag_name: process.env.RELEASE_TAG,
|
||||||
});
|
});
|
||||||
|
|||||||
2
.github/workflows/yapf.yml
vendored
2
.github/workflows/yapf.yml
vendored
@ -14,7 +14,7 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
python-version: ["3.10"]
|
python-version: ["3.8", "3.9", "3.10", "3.11"]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
- name: Set up Python ${{ matrix.python-version }}
|
- name: Set up Python ${{ matrix.python-version }}
|
||||||
|
|||||||
3
.gitignore
vendored
3
.gitignore
vendored
@ -70,6 +70,8 @@ instance/
|
|||||||
|
|
||||||
# Sphinx documentation
|
# Sphinx documentation
|
||||||
docs/_build/
|
docs/_build/
|
||||||
|
docs/source/getting_started/examples/*.rst
|
||||||
|
!**/*.template.rst
|
||||||
|
|
||||||
# PyBuilder
|
# PyBuilder
|
||||||
.pybuilder/
|
.pybuilder/
|
||||||
@ -181,6 +183,7 @@ _build/
|
|||||||
# hip files generated by PyTorch
|
# hip files generated by PyTorch
|
||||||
*.hip
|
*.hip
|
||||||
*_hip*
|
*_hip*
|
||||||
|
hip_compat.h
|
||||||
|
|
||||||
# Benchmark dataset
|
# Benchmark dataset
|
||||||
*.json
|
*.json
|
||||||
|
|||||||
1
.yapfignore
Normal file
1
.yapfignore
Normal file
@ -0,0 +1 @@
|
|||||||
|
collect_env.py
|
||||||
309
CMakeLists.txt
Normal file
309
CMakeLists.txt
Normal file
@ -0,0 +1,309 @@
|
|||||||
|
cmake_minimum_required(VERSION 3.21)
|
||||||
|
|
||||||
|
project(vllm_extensions LANGUAGES CXX)
|
||||||
|
|
||||||
|
# CUDA by default, can be overridden by using -DVLLM_TARGET_DEVICE=... (used by setup.py)
|
||||||
|
set(VLLM_TARGET_DEVICE "cuda" CACHE STRING "Target device backend for vLLM")
|
||||||
|
|
||||||
|
message(STATUS "Build type: ${CMAKE_BUILD_TYPE}")
|
||||||
|
message(STATUS "Target device: ${VLLM_TARGET_DEVICE}")
|
||||||
|
|
||||||
|
include(${CMAKE_CURRENT_LIST_DIR}/cmake/utils.cmake)
|
||||||
|
|
||||||
|
#
|
||||||
|
# Supported python versions. These versions will be searched in order, the
|
||||||
|
# first match will be selected. These should be kept in sync with setup.py.
|
||||||
|
#
|
||||||
|
set(PYTHON_SUPPORTED_VERSIONS "3.8" "3.9" "3.10" "3.11")
|
||||||
|
|
||||||
|
# Supported NVIDIA architectures.
|
||||||
|
set(CUDA_SUPPORTED_ARCHS "7.0;7.5;8.0;8.6;8.9;9.0")
|
||||||
|
|
||||||
|
# Supported AMD GPU architectures.
|
||||||
|
set(HIP_SUPPORTED_ARCHS "gfx906;gfx908;gfx90a;gfx940;gfx941;gfx942;gfx1030;gfx1100")
|
||||||
|
|
||||||
|
#
|
||||||
|
# Supported/expected torch versions for CUDA/ROCm.
|
||||||
|
#
|
||||||
|
# Currently, having an incorrect pytorch version results in a warning
|
||||||
|
# rather than an error.
|
||||||
|
#
|
||||||
|
# Note: the CUDA torch version is derived from pyproject.toml and various
|
||||||
|
# requirements.txt files and should be kept consistent. The ROCm torch
|
||||||
|
# versions are derived from Dockerfile.rocm
|
||||||
|
#
|
||||||
|
set(TORCH_SUPPORTED_VERSION_CUDA "2.3.0")
|
||||||
|
set(TORCH_SUPPORTED_VERSION_ROCM "2.4.0")
|
||||||
|
|
||||||
|
#
|
||||||
|
# Try to find python package with an executable that exactly matches
|
||||||
|
# `VLLM_PYTHON_EXECUTABLE` and is one of the supported versions.
|
||||||
|
#
|
||||||
|
if (VLLM_PYTHON_EXECUTABLE)
|
||||||
|
find_python_from_executable(${VLLM_PYTHON_EXECUTABLE} "${PYTHON_SUPPORTED_VERSIONS}")
|
||||||
|
else()
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"Please set VLLM_PYTHON_EXECUTABLE to the path of the desired python version"
|
||||||
|
" before running cmake configure.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
#
|
||||||
|
# Update cmake's `CMAKE_PREFIX_PATH` with torch location.
|
||||||
|
#
|
||||||
|
append_cmake_prefix_path("torch" "torch.utils.cmake_prefix_path")
|
||||||
|
|
||||||
|
# Ensure the 'nvcc' command is in the PATH
|
||||||
|
find_program(NVCC_EXECUTABLE nvcc)
|
||||||
|
if (CUDA_FOUND AND NOT NVCC_EXECUTABLE)
|
||||||
|
message(FATAL_ERROR "nvcc not found")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
#
|
||||||
|
# Import torch cmake configuration.
|
||||||
|
# Torch also imports CUDA (and partially HIP) languages with some customizations,
|
||||||
|
# so there is no need to do this explicitly with check_language/enable_language,
|
||||||
|
# etc.
|
||||||
|
#
|
||||||
|
find_package(Torch REQUIRED)
|
||||||
|
|
||||||
|
#
|
||||||
|
# Forward the non-CUDA device extensions to external CMake scripts.
|
||||||
|
#
|
||||||
|
if (NOT VLLM_TARGET_DEVICE STREQUAL "cuda" AND
|
||||||
|
NOT VLLM_TARGET_DEVICE STREQUAL "rocm")
|
||||||
|
if (VLLM_TARGET_DEVICE STREQUAL "cpu")
|
||||||
|
include(${CMAKE_CURRENT_LIST_DIR}/cmake/cpu_extension.cmake)
|
||||||
|
else()
|
||||||
|
message(FATAL_ERROR "Unsupported vLLM target device: ${VLLM_TARGET_DEVICE}")
|
||||||
|
endif()
|
||||||
|
return()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
#
|
||||||
|
# Set up GPU language and check the torch version and warn if it isn't
|
||||||
|
# what is expected.
|
||||||
|
#
|
||||||
|
if (NOT HIP_FOUND AND CUDA_FOUND)
|
||||||
|
set(VLLM_GPU_LANG "CUDA")
|
||||||
|
|
||||||
|
if (NOT Torch_VERSION VERSION_EQUAL ${TORCH_SUPPORTED_VERSION_CUDA})
|
||||||
|
message(WARNING "Pytorch version ${TORCH_SUPPORTED_VERSION_CUDA} "
|
||||||
|
"expected for CUDA build, saw ${Torch_VERSION} instead.")
|
||||||
|
endif()
|
||||||
|
elseif(HIP_FOUND)
|
||||||
|
set(VLLM_GPU_LANG "HIP")
|
||||||
|
|
||||||
|
# Importing torch recognizes and sets up some HIP/ROCm configuration but does
|
||||||
|
# not let cmake recognize .hip files. In order to get cmake to understand the
|
||||||
|
# .hip extension automatically, HIP must be enabled explicitly.
|
||||||
|
enable_language(HIP)
|
||||||
|
|
||||||
|
# ROCm 5.X and 6.X
|
||||||
|
if (ROCM_VERSION_DEV_MAJOR GREATER_EQUAL 5 AND
|
||||||
|
NOT Torch_VERSION VERSION_EQUAL ${TORCH_SUPPORTED_VERSION_ROCM})
|
||||||
|
message(WARNING "Pytorch version ${TORCH_SUPPORTED_VERSION_ROCM} "
|
||||||
|
"expected for ROCm build, saw ${Torch_VERSION} instead.")
|
||||||
|
endif()
|
||||||
|
else()
|
||||||
|
message(FATAL_ERROR "Can't find CUDA or HIP installation.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
#
|
||||||
|
# Override the GPU architectures detected by cmake/torch and filter them by
|
||||||
|
# the supported versions for the current language.
|
||||||
|
# The final set of arches is stored in `VLLM_GPU_ARCHES`.
|
||||||
|
#
|
||||||
|
override_gpu_arches(VLLM_GPU_ARCHES
|
||||||
|
${VLLM_GPU_LANG}
|
||||||
|
"${${VLLM_GPU_LANG}_SUPPORTED_ARCHS}")
|
||||||
|
|
||||||
|
#
|
||||||
|
# Query torch for additional GPU compilation flags for the given
|
||||||
|
# `VLLM_GPU_LANG`.
|
||||||
|
# The final set of arches is stored in `VLLM_GPU_FLAGS`.
|
||||||
|
#
|
||||||
|
get_torch_gpu_compiler_flags(VLLM_GPU_FLAGS ${VLLM_GPU_LANG})
|
||||||
|
|
||||||
|
#
|
||||||
|
# Set nvcc parallelism.
|
||||||
|
#
|
||||||
|
if(NVCC_THREADS AND VLLM_GPU_LANG STREQUAL "CUDA")
|
||||||
|
list(APPEND VLLM_GPU_FLAGS "--threads=${NVCC_THREADS}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
#
|
||||||
|
# Define extension targets
|
||||||
|
#
|
||||||
|
|
||||||
|
#
|
||||||
|
# _C extension
|
||||||
|
#
|
||||||
|
|
||||||
|
set(VLLM_EXT_SRC
|
||||||
|
"csrc/cache_kernels.cu"
|
||||||
|
"csrc/attention/attention_kernels.cu"
|
||||||
|
"csrc/pos_encoding_kernels.cu"
|
||||||
|
"csrc/activation_kernels.cu"
|
||||||
|
"csrc/layernorm_kernels.cu"
|
||||||
|
"csrc/quantization/squeezellm/quant_cuda_kernel.cu"
|
||||||
|
"csrc/quantization/gptq/q_gemm.cu"
|
||||||
|
"csrc/quantization/compressed_tensors/int8_quant_kernels.cu"
|
||||||
|
"csrc/quantization/fp8/common.cu"
|
||||||
|
"csrc/cuda_utils_kernels.cu"
|
||||||
|
"csrc/moe_align_block_size_kernels.cu"
|
||||||
|
"csrc/torch_bindings.cpp")
|
||||||
|
|
||||||
|
if(VLLM_GPU_LANG STREQUAL "CUDA")
|
||||||
|
include(FetchContent)
|
||||||
|
SET(CUTLASS_ENABLE_HEADERS_ONLY=ON)
|
||||||
|
FetchContent_Declare(
|
||||||
|
cutlass
|
||||||
|
GIT_REPOSITORY https://github.com/nvidia/cutlass.git
|
||||||
|
# CUTLASS 3.5.0
|
||||||
|
GIT_TAG 7d49e6c7e2f8896c47f586706e67e1fb215529dc
|
||||||
|
)
|
||||||
|
FetchContent_MakeAvailable(cutlass)
|
||||||
|
|
||||||
|
list(APPEND VLLM_EXT_SRC
|
||||||
|
"csrc/quantization/aqlm/gemm_kernels.cu"
|
||||||
|
"csrc/quantization/awq/gemm_kernels.cu"
|
||||||
|
"csrc/quantization/marlin/dense/marlin_cuda_kernel.cu"
|
||||||
|
"csrc/quantization/marlin/sparse/marlin_24_cuda_kernel.cu"
|
||||||
|
"csrc/quantization/gptq_marlin/gptq_marlin.cu"
|
||||||
|
"csrc/quantization/gptq_marlin/gptq_marlin_repack.cu"
|
||||||
|
"csrc/quantization/fp8/fp8_marlin.cu"
|
||||||
|
"csrc/custom_all_reduce.cu"
|
||||||
|
"csrc/quantization/cutlass_w8a8/scaled_mm_entry.cu"
|
||||||
|
"csrc/quantization/cutlass_w8a8/scaled_mm_c2x.cu"
|
||||||
|
"csrc/quantization/cutlass_w8a8/scaled_mm_c3x.cu")
|
||||||
|
|
||||||
|
#
|
||||||
|
# The CUTLASS kernels for Hopper require sm90a to be enabled.
|
||||||
|
# This is done via the below gencode option, BUT that creates kernels for both sm90 and sm90a.
|
||||||
|
# That adds an extra 17MB to compiled binary, so instead we selectively enable it.
|
||||||
|
if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER 12.0)
|
||||||
|
set_source_files_properties(
|
||||||
|
"csrc/quantization/cutlass_w8a8/scaled_mm_c3x.cu"
|
||||||
|
PROPERTIES
|
||||||
|
COMPILE_FLAGS
|
||||||
|
"-gencode arch=compute_90a,code=sm_90a")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
endif()
|
||||||
|
|
||||||
|
define_gpu_extension_target(
|
||||||
|
_C
|
||||||
|
DESTINATION vllm
|
||||||
|
LANGUAGE ${VLLM_GPU_LANG}
|
||||||
|
SOURCES ${VLLM_EXT_SRC}
|
||||||
|
COMPILE_FLAGS ${VLLM_GPU_FLAGS}
|
||||||
|
ARCHITECTURES ${VLLM_GPU_ARCHES}
|
||||||
|
INCLUDE_DIRECTORIES ${CUTLASS_INCLUDE_DIR};${CUTLASS_TOOLS_UTIL_INCLUDE_DIR}
|
||||||
|
USE_SABI 3
|
||||||
|
WITH_SOABI)
|
||||||
|
|
||||||
|
#
|
||||||
|
# _moe_C extension
|
||||||
|
#
|
||||||
|
|
||||||
|
set(VLLM_MOE_EXT_SRC
|
||||||
|
"csrc/moe/torch_bindings.cpp"
|
||||||
|
"csrc/moe/topk_softmax_kernels.cu")
|
||||||
|
|
||||||
|
define_gpu_extension_target(
|
||||||
|
_moe_C
|
||||||
|
DESTINATION vllm
|
||||||
|
LANGUAGE ${VLLM_GPU_LANG}
|
||||||
|
SOURCES ${VLLM_MOE_EXT_SRC}
|
||||||
|
COMPILE_FLAGS ${VLLM_GPU_FLAGS}
|
||||||
|
ARCHITECTURES ${VLLM_GPU_ARCHES}
|
||||||
|
USE_SABI 3
|
||||||
|
WITH_SOABI)
|
||||||
|
|
||||||
|
#
|
||||||
|
# _punica_C extension
|
||||||
|
#
|
||||||
|
|
||||||
|
set(VLLM_PUNICA_EXT_SRC
|
||||||
|
"csrc/punica/bgmv/bgmv_bf16_bf16_bf16.cu"
|
||||||
|
"csrc/punica/bgmv/bgmv_bf16_fp32_bf16.cu"
|
||||||
|
"csrc/punica/bgmv/bgmv_fp16_fp16_fp16.cu"
|
||||||
|
"csrc/punica/bgmv/bgmv_fp16_fp32_fp16.cu"
|
||||||
|
"csrc/punica/bgmv/bgmv_fp32_bf16_bf16.cu"
|
||||||
|
"csrc/punica/bgmv/bgmv_fp32_fp16_fp16.cu"
|
||||||
|
"csrc/punica/punica_ops.cu"
|
||||||
|
"csrc/punica/torch_bindings.cpp")
|
||||||
|
|
||||||
|
#
|
||||||
|
# Copy GPU compilation flags+update for punica
|
||||||
|
#
|
||||||
|
set(VLLM_PUNICA_GPU_FLAGS ${VLLM_GPU_FLAGS})
|
||||||
|
list(REMOVE_ITEM VLLM_PUNICA_GPU_FLAGS
|
||||||
|
"-D__CUDA_NO_HALF_OPERATORS__"
|
||||||
|
"-D__CUDA_NO_HALF_CONVERSIONS__"
|
||||||
|
"-D__CUDA_NO_BFLOAT16_CONVERSIONS__"
|
||||||
|
"-D__CUDA_NO_HALF2_OPERATORS__")
|
||||||
|
|
||||||
|
#
|
||||||
|
# Filter out CUDA architectures < 8.0 for punica.
|
||||||
|
#
|
||||||
|
if (${VLLM_GPU_LANG} STREQUAL "CUDA")
|
||||||
|
set(VLLM_PUNICA_GPU_ARCHES)
|
||||||
|
foreach(ARCH ${VLLM_GPU_ARCHES})
|
||||||
|
string_to_ver(CODE_VER ${ARCH})
|
||||||
|
if (CODE_VER GREATER_EQUAL 8.0)
|
||||||
|
list(APPEND VLLM_PUNICA_GPU_ARCHES ${ARCH})
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
message(STATUS "Punica target arches: ${VLLM_PUNICA_GPU_ARCHES}")
|
||||||
|
elseif(${VLLM_GPU_LANG} STREQUAL "HIP")
|
||||||
|
set(VLLM_PUNICA_GPU_ARCHES ${VLLM_GPU_ARCHES})
|
||||||
|
message(STATUS "Punica target arches: ${VLLM_PUNICA_GPU_ARCHES}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (VLLM_PUNICA_GPU_ARCHES)
|
||||||
|
define_gpu_extension_target(
|
||||||
|
_punica_C
|
||||||
|
DESTINATION vllm
|
||||||
|
LANGUAGE ${VLLM_GPU_LANG}
|
||||||
|
SOURCES ${VLLM_PUNICA_EXT_SRC}
|
||||||
|
COMPILE_FLAGS ${VLLM_PUNICA_GPU_FLAGS}
|
||||||
|
ARCHITECTURES ${VLLM_PUNICA_GPU_ARCHES}
|
||||||
|
USE_SABI 3
|
||||||
|
WITH_SOABI)
|
||||||
|
else()
|
||||||
|
message(WARNING "Unable to create _punica_C target because none of the "
|
||||||
|
"requested architectures (${VLLM_GPU_ARCHES}) are supported, i.e. >= 8.0")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
#
|
||||||
|
# Add the `default` target which detects which extensions should be
|
||||||
|
# built based on platform/architecture. This is the same logic that
|
||||||
|
# setup.py uses to select which extensions should be built and should
|
||||||
|
# be kept in sync.
|
||||||
|
#
|
||||||
|
# The `default` target makes direct use of cmake easier since knowledge
|
||||||
|
# of which extensions are supported has been factored in, e.g.
|
||||||
|
#
|
||||||
|
# mkdir build && cd build
|
||||||
|
# cmake -G Ninja -DVLLM_PYTHON_EXECUTABLE=`which python3` -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=../vllm ..
|
||||||
|
# cmake --build . --target default
|
||||||
|
#
|
||||||
|
add_custom_target(default)
|
||||||
|
|
||||||
|
if(VLLM_GPU_LANG STREQUAL "CUDA" OR VLLM_GPU_LANG STREQUAL "HIP")
|
||||||
|
message(STATUS "Enabling C extension.")
|
||||||
|
add_dependencies(default _C)
|
||||||
|
|
||||||
|
message(STATUS "Enabling moe extension.")
|
||||||
|
add_dependencies(default _moe_C)
|
||||||
|
|
||||||
|
# Enable punica if -DVLLM_INSTALL_PUNICA_KERNELS=ON or
|
||||||
|
# VLLM_INSTALL_PUNICA_KERNELS is set in the environment and
|
||||||
|
# there are supported target arches.
|
||||||
|
if (VLLM_PUNICA_GPU_ARCHES AND
|
||||||
|
(ENV{VLLM_INSTALL_PUNICA_KERNELS} OR VLLM_INSTALL_PUNICA_KERNELS))
|
||||||
|
message(STATUS "Enabling punica extension.")
|
||||||
|
add_dependencies(default _punica_C)
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
@ -21,7 +21,6 @@ Express your support on Twitter if vLLM aids you, or simply offer your appreciat
|
|||||||
### Build from source
|
### Build from source
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pip install -r requirements.txt
|
|
||||||
pip install -e . # This may take several minutes.
|
pip install -e . # This may take several minutes.
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -30,6 +29,8 @@ pip install -e . # This may take several minutes.
|
|||||||
```bash
|
```bash
|
||||||
pip install -r requirements-dev.txt
|
pip install -r requirements-dev.txt
|
||||||
|
|
||||||
|
# linting and formatting
|
||||||
|
bash format.sh
|
||||||
# Static type checking
|
# Static type checking
|
||||||
mypy
|
mypy
|
||||||
# Unit tests
|
# Unit tests
|
||||||
@ -45,31 +46,9 @@ pytest tests/
|
|||||||
If you encounter a bug or have a feature request, please check our issues page first to see if someone else has already reported it.
|
If you encounter a bug or have a feature request, please check our issues page first to see if someone else has already reported it.
|
||||||
If not, please file a new issue, providing as much relevant information as possible.
|
If not, please file a new issue, providing as much relevant information as possible.
|
||||||
|
|
||||||
### Coding Style Guide
|
### Pull Requests & Code Reviews
|
||||||
|
|
||||||
In general, we adhere to [Google Python style guide](https://google.github.io/styleguide/pyguide.html) and [Google C++ style guide](https://google.github.io/styleguide/cppguide.html).
|
Please check the PR checklist in the [PR template](.github/PULL_REQUEST_TEMPLATE.md) for detailed guide for contribution.
|
||||||
|
|
||||||
We include a formatting script [`format.sh`](./format.sh) to format the code.
|
|
||||||
|
|
||||||
### Pull Requests
|
|
||||||
|
|
||||||
When submitting a pull request:
|
|
||||||
|
|
||||||
1. Make sure your code has been rebased on top of the latest commit on the main branch.
|
|
||||||
2. Ensure code is properly formatted by running [`format.sh`](./format.sh).
|
|
||||||
3. Include a detailed description of the changes in the pull request.
|
|
||||||
Explain why you made the changes you did.
|
|
||||||
If your pull request fixes an open issue, please include a reference to it in the description.
|
|
||||||
|
|
||||||
### Code Reviews
|
|
||||||
|
|
||||||
All submissions, including submissions by project members, require a code review.
|
|
||||||
To make the review process as smooth as possible, please:
|
|
||||||
|
|
||||||
1. Keep your changes as concise as possible.
|
|
||||||
If your pull request involves multiple unrelated changes, consider splitting it into separate pull requests.
|
|
||||||
2. Respond to all comments within a reasonable time frame.
|
|
||||||
If a comment isn't clear or you disagree with a suggestion, feel free to ask for clarification or discuss the suggestion.
|
|
||||||
|
|
||||||
### Thank You
|
### Thank You
|
||||||
|
|
||||||
|
|||||||
194
Dockerfile
194
Dockerfile
@ -1,50 +1,84 @@
|
|||||||
# The vLLM Dockerfile is used to construct vLLM image that can be directly used
|
# The vLLM Dockerfile is used to construct vLLM image that can be directly used
|
||||||
# to run the OpenAI compatible server.
|
# to run the OpenAI compatible server.
|
||||||
|
|
||||||
|
# Please update any changes made here to
|
||||||
|
# docs/source/dev/dockerfile/dockerfile.rst and
|
||||||
|
# docs/source/assets/dev/dockerfile-stages-dependency.png
|
||||||
|
|
||||||
|
ARG CUDA_VERSION=12.4.1
|
||||||
#################### BASE BUILD IMAGE ####################
|
#################### BASE BUILD IMAGE ####################
|
||||||
FROM nvidia/cuda:12.1.0-devel-ubuntu22.04 AS dev
|
# prepare basic build environment
|
||||||
|
FROM nvidia/cuda:${CUDA_VERSION}-devel-ubuntu22.04 AS base
|
||||||
|
|
||||||
|
ARG CUDA_VERSION=12.4.1
|
||||||
|
ARG PYTHON_VERSION=3
|
||||||
|
|
||||||
|
ENV DEBIAN_FRONTEND=noninteractive
|
||||||
|
|
||||||
|
RUN echo 'tzdata tzdata/Areas select America' | debconf-set-selections \
|
||||||
|
&& echo 'tzdata tzdata/Zones/America select Los_Angeles' | debconf-set-selections \
|
||||||
|
&& apt-get update -y \
|
||||||
|
&& apt-get install -y ccache software-properties-common \
|
||||||
|
&& add-apt-repository ppa:deadsnakes/ppa \
|
||||||
|
&& apt-get update -y \
|
||||||
|
&& apt-get install -y python${PYTHON_VERSION} python${PYTHON_VERSION}-dev python${PYTHON_VERSION}-venv python3-pip \
|
||||||
|
&& if [ "${PYTHON_VERSION}" != "3" ]; then update-alternatives --install /usr/bin/python3 python3 /usr/bin/python${PYTHON_VERSION} 1; fi \
|
||||||
|
&& python3 --version \
|
||||||
|
&& python3 -m pip --version
|
||||||
|
|
||||||
RUN apt-get update -y \
|
RUN apt-get update -y \
|
||||||
&& apt-get install -y python3-pip git
|
&& apt-get install -y python3-pip git curl sudo
|
||||||
|
|
||||||
# Workaround for https://github.com/openai/triton/issues/2507 and
|
# Workaround for https://github.com/openai/triton/issues/2507 and
|
||||||
# https://github.com/pytorch/pytorch/issues/107960 -- hopefully
|
# https://github.com/pytorch/pytorch/issues/107960 -- hopefully
|
||||||
# this won't be needed for future versions of this docker image
|
# this won't be needed for future versions of this docker image
|
||||||
# or future versions of triton.
|
# or future versions of triton.
|
||||||
RUN ldconfig /usr/local/cuda-12.1/compat/
|
RUN ldconfig /usr/local/cuda-$(echo $CUDA_VERSION | cut -d. -f1,2)/compat/
|
||||||
|
|
||||||
WORKDIR /workspace
|
WORKDIR /workspace
|
||||||
|
|
||||||
# install build and runtime dependencies
|
# install build and runtime dependencies
|
||||||
COPY requirements.txt requirements.txt
|
COPY requirements-common.txt requirements-common.txt
|
||||||
|
COPY requirements-cuda.txt requirements-cuda.txt
|
||||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||||
pip install -r requirements.txt
|
python3 -m pip install -r requirements-cuda.txt
|
||||||
|
|
||||||
# install development dependencies
|
COPY requirements-mamba.txt requirements-mamba.txt
|
||||||
COPY requirements-dev.txt requirements-dev.txt
|
RUN python3 -m pip install packaging
|
||||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
RUN python3 -m pip install -r requirements-mamba.txt
|
||||||
pip install -r requirements-dev.txt
|
|
||||||
|
# cuda arch list used by torch
|
||||||
|
# can be useful for both `dev` and `test`
|
||||||
|
# explicitly set the list to avoid issues with torch 2.2
|
||||||
|
# see https://github.com/pytorch/pytorch/pull/123243
|
||||||
|
ARG torch_cuda_arch_list='7.0 7.5 8.0 8.6 8.9 9.0+PTX'
|
||||||
|
ENV TORCH_CUDA_ARCH_LIST=${torch_cuda_arch_list}
|
||||||
#################### BASE BUILD IMAGE ####################
|
#################### BASE BUILD IMAGE ####################
|
||||||
|
|
||||||
|
#################### WHEEL BUILD IMAGE ####################
|
||||||
|
FROM base AS build
|
||||||
|
|
||||||
#################### EXTENSION BUILD IMAGE ####################
|
ARG PYTHON_VERSION=3
|
||||||
FROM dev AS build
|
|
||||||
|
|
||||||
# install build dependencies
|
# install build dependencies
|
||||||
COPY requirements-build.txt requirements-build.txt
|
COPY requirements-build.txt requirements-build.txt
|
||||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
|
||||||
pip install -r requirements-build.txt
|
|
||||||
|
|
||||||
# copy input files
|
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||||
|
python3 -m pip install -r requirements-build.txt
|
||||||
|
|
||||||
|
# install compiler cache to speed up compilation leveraging local or remote caching
|
||||||
|
RUN apt-get update -y && apt-get install -y ccache
|
||||||
|
|
||||||
|
# files and directories related to build wheels
|
||||||
COPY csrc csrc
|
COPY csrc csrc
|
||||||
COPY setup.py setup.py
|
COPY setup.py setup.py
|
||||||
COPY requirements.txt requirements.txt
|
COPY cmake cmake
|
||||||
|
COPY CMakeLists.txt CMakeLists.txt
|
||||||
|
COPY requirements-common.txt requirements-common.txt
|
||||||
|
COPY requirements-cuda.txt requirements-cuda.txt
|
||||||
COPY pyproject.toml pyproject.toml
|
COPY pyproject.toml pyproject.toml
|
||||||
COPY vllm/__init__.py vllm/__init__.py
|
COPY vllm vllm
|
||||||
|
|
||||||
# cuda arch list used by torch
|
|
||||||
ARG torch_cuda_arch_list='7.0 7.5 8.0 8.6 8.9 9.0+PTX'
|
|
||||||
ENV TORCH_CUDA_ARCH_LIST=${torch_cuda_arch_list}
|
|
||||||
# max jobs used by Ninja to build extensions
|
# max jobs used by Ninja to build extensions
|
||||||
ARG max_jobs=2
|
ARG max_jobs=2
|
||||||
ENV MAX_JOBS=${max_jobs}
|
ENV MAX_JOBS=${max_jobs}
|
||||||
@ -54,52 +88,116 @@ ENV NVCC_THREADS=$nvcc_threads
|
|||||||
# make sure punica kernels are built (for LoRA)
|
# make sure punica kernels are built (for LoRA)
|
||||||
ENV VLLM_INSTALL_PUNICA_KERNELS=1
|
ENV VLLM_INSTALL_PUNICA_KERNELS=1
|
||||||
|
|
||||||
RUN python3 setup.py build_ext --inplace
|
ARG USE_SCCACHE
|
||||||
|
# if USE_SCCACHE is set, use sccache to speed up compilation
|
||||||
|
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||||
|
if [ "$USE_SCCACHE" = "1" ]; then \
|
||||||
|
echo "Installing sccache..." \
|
||||||
|
&& curl -L -o sccache.tar.gz https://github.com/mozilla/sccache/releases/download/v0.8.1/sccache-v0.8.1-x86_64-unknown-linux-musl.tar.gz \
|
||||||
|
&& tar -xzf sccache.tar.gz \
|
||||||
|
&& sudo mv sccache-v0.8.1-x86_64-unknown-linux-musl/sccache /usr/bin/sccache \
|
||||||
|
&& rm -rf sccache.tar.gz sccache-v0.8.1-x86_64-unknown-linux-musl \
|
||||||
|
&& export SCCACHE_BUCKET=vllm-build-sccache \
|
||||||
|
&& export SCCACHE_REGION=us-west-2 \
|
||||||
|
&& sccache --show-stats \
|
||||||
|
&& python3 setup.py bdist_wheel --dist-dir=dist \
|
||||||
|
&& sccache --show-stats; \
|
||||||
|
fi
|
||||||
|
|
||||||
|
ENV CCACHE_DIR=/root/.cache/ccache
|
||||||
|
RUN --mount=type=cache,target=/root/.cache/ccache \
|
||||||
|
--mount=type=cache,target=/root/.cache/pip \
|
||||||
|
if [ "$USE_SCCACHE" != "1" ]; then \
|
||||||
|
python3 setup.py bdist_wheel --dist-dir=dist; \
|
||||||
|
fi
|
||||||
|
|
||||||
|
# check the size of the wheel, we cannot upload wheels larger than 100MB
|
||||||
|
COPY .buildkite/check-wheel-size.py check-wheel-size.py
|
||||||
|
RUN python3 check-wheel-size.py dist
|
||||||
|
|
||||||
#################### EXTENSION Build IMAGE ####################
|
#################### EXTENSION Build IMAGE ####################
|
||||||
|
|
||||||
|
#################### DEV IMAGE ####################
|
||||||
|
FROM base as dev
|
||||||
|
|
||||||
|
COPY requirements-lint.txt requirements-lint.txt
|
||||||
|
COPY requirements-test.txt requirements-test.txt
|
||||||
|
COPY requirements-dev.txt requirements-dev.txt
|
||||||
|
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||||
|
python3 -m pip install -r requirements-dev.txt
|
||||||
|
|
||||||
|
#################### DEV IMAGE ####################
|
||||||
|
#################### MAMBA Build IMAGE ####################
|
||||||
|
FROM dev as mamba-builder
|
||||||
|
# max jobs used for build
|
||||||
|
ARG max_jobs=2
|
||||||
|
ENV MAX_JOBS=${max_jobs}
|
||||||
|
|
||||||
|
WORKDIR /usr/src/mamba
|
||||||
|
|
||||||
|
COPY requirements-mamba.txt requirements-mamba.txt
|
||||||
|
|
||||||
|
# Download the wheel or build it if a pre-compiled release doesn't exist
|
||||||
|
RUN pip --verbose wheel -r requirements-mamba.txt \
|
||||||
|
--no-build-isolation --no-deps --no-cache-dir
|
||||||
|
|
||||||
|
#################### MAMBA Build IMAGE ####################
|
||||||
|
|
||||||
|
#################### vLLM installation IMAGE ####################
|
||||||
|
# image with vLLM installed
|
||||||
|
FROM nvidia/cuda:${CUDA_VERSION}-base-ubuntu22.04 AS vllm-base
|
||||||
|
ARG CUDA_VERSION=12.4.1
|
||||||
|
WORKDIR /vllm-workspace
|
||||||
|
|
||||||
|
RUN apt-get update -y \
|
||||||
|
&& apt-get install -y python3-pip git vim
|
||||||
|
|
||||||
|
# Workaround for https://github.com/openai/triton/issues/2507 and
|
||||||
|
# https://github.com/pytorch/pytorch/issues/107960 -- hopefully
|
||||||
|
# this won't be needed for future versions of this docker image
|
||||||
|
# or future versions of triton.
|
||||||
|
RUN ldconfig /usr/local/cuda-$(echo $CUDA_VERSION | cut -d. -f1,2)/compat/
|
||||||
|
|
||||||
|
# install vllm wheel first, so that torch etc will be installed
|
||||||
|
RUN --mount=type=bind,from=build,src=/workspace/dist,target=/vllm-workspace/dist \
|
||||||
|
--mount=type=cache,target=/root/.cache/pip \
|
||||||
|
python3 -m pip install dist/*.whl --verbose
|
||||||
|
|
||||||
|
RUN --mount=type=bind,from=mamba-builder,src=/usr/src/mamba,target=/usr/src/mamba \
|
||||||
|
--mount=type=cache,target=/root/.cache/pip \
|
||||||
|
python3 -m pip install /usr/src/mamba/*.whl --no-cache-dir
|
||||||
|
#################### vLLM installation IMAGE ####################
|
||||||
|
|
||||||
|
|
||||||
#################### TEST IMAGE ####################
|
#################### TEST IMAGE ####################
|
||||||
# image to run unit testing suite
|
# image to run unit testing suite
|
||||||
FROM dev AS test
|
# note that this uses vllm installed by `pip`
|
||||||
|
FROM vllm-base AS test
|
||||||
|
|
||||||
# copy pytorch extensions separately to avoid having to rebuild
|
|
||||||
# when python code changes
|
|
||||||
WORKDIR /vllm-workspace
|
|
||||||
# ADD is used to preserve directory structure
|
|
||||||
ADD . /vllm-workspace/
|
ADD . /vllm-workspace/
|
||||||
COPY --from=build /workspace/vllm/*.so /vllm-workspace/vllm/
|
|
||||||
# ignore build dependencies installation because we are using pre-complied extensions
|
|
||||||
RUN rm pyproject.toml
|
|
||||||
RUN --mount=type=cache,target=/root/.cache/pip VLLM_USE_PRECOMPILED=1 pip install . --verbose
|
|
||||||
#################### TEST IMAGE ####################
|
|
||||||
|
|
||||||
|
# install development dependencies (for testing)
|
||||||
#################### RUNTIME BASE IMAGE ####################
|
|
||||||
# We used base cuda image because pytorch installs its own cuda libraries.
|
|
||||||
# However cupy depends on cuda libraries so we had to switch to the runtime image
|
|
||||||
# In the future it would be nice to get a container with pytorch and cuda without duplicating cuda
|
|
||||||
FROM nvidia/cuda:12.1.0-runtime-ubuntu22.04 AS vllm-base
|
|
||||||
|
|
||||||
# libnccl required for ray
|
|
||||||
RUN apt-get update -y \
|
|
||||||
&& apt-get install -y python3-pip
|
|
||||||
|
|
||||||
WORKDIR /workspace
|
|
||||||
COPY requirements.txt requirements.txt
|
|
||||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||||
pip install -r requirements.txt
|
python3 -m pip install -r requirements-dev.txt
|
||||||
#################### RUNTIME BASE IMAGE ####################
|
|
||||||
|
|
||||||
|
# doc requires source code
|
||||||
|
# we hide them inside `test_docs/` , so that this source code
|
||||||
|
# will not be imported by other tests
|
||||||
|
RUN mkdir test_docs
|
||||||
|
RUN mv docs test_docs/
|
||||||
|
RUN mv vllm test_docs/
|
||||||
|
|
||||||
|
#################### TEST IMAGE ####################
|
||||||
|
|
||||||
#################### OPENAI API SERVER ####################
|
#################### OPENAI API SERVER ####################
|
||||||
# openai api server alternative
|
# openai api server alternative
|
||||||
FROM vllm-base AS vllm-openai
|
FROM vllm-base AS vllm-openai
|
||||||
|
|
||||||
# install additional dependencies for openai api server
|
# install additional dependencies for openai api server
|
||||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||||
pip install accelerate
|
pip install accelerate hf_transfer 'modelscope!=1.15.0'
|
||||||
|
|
||||||
COPY --from=build /workspace/vllm/*.so /workspace/vllm/
|
ENV VLLM_USAGE_SOURCE production-docker-image
|
||||||
COPY vllm vllm
|
|
||||||
|
|
||||||
ENTRYPOINT ["python3", "-m", "vllm.entrypoints.openai.api_server"]
|
ENTRYPOINT ["python3", "-m", "vllm.entrypoints.openai.api_server"]
|
||||||
#################### OPENAI API SERVER ####################
|
#################### OPENAI API SERVER ####################
|
||||||
|
|||||||
40
Dockerfile.cpu
Normal file
40
Dockerfile.cpu
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
# This vLLM Dockerfile is used to construct image that can build and run vLLM on x86 CPU platform.
|
||||||
|
|
||||||
|
FROM ubuntu:22.04 AS cpu-test-1
|
||||||
|
|
||||||
|
RUN apt-get update -y \
|
||||||
|
&& apt-get install -y git wget vim numactl gcc-12 g++-12 python3 python3-pip libtcmalloc-minimal4 \
|
||||||
|
&& update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-12 10 --slave /usr/bin/g++ g++ /usr/bin/g++-12
|
||||||
|
|
||||||
|
# https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/performance_tuning/tuning_guide.html
|
||||||
|
# intel-openmp provides additional performance improvement vs. openmp
|
||||||
|
# tcmalloc provides better memory allocation efficiency, e.g, holding memory in caches to speed up access of commonly-used objects.
|
||||||
|
RUN pip install intel-openmp
|
||||||
|
|
||||||
|
ENV LD_PRELOAD="/usr/lib/x86_64-linux-gnu/libtcmalloc_minimal.so.4:/usr/local/lib/libiomp5.so:$LD_PRELOAD"
|
||||||
|
|
||||||
|
|
||||||
|
RUN pip install https://intel-extension-for-pytorch.s3.amazonaws.com/ipex_dev/cpu/intel_extension_for_pytorch-2.3.100%2Bgit0eb3473-cp310-cp310-linux_x86_64.whl
|
||||||
|
|
||||||
|
RUN pip install --upgrade pip \
|
||||||
|
&& pip install wheel packaging ninja "setuptools>=49.4.0" numpy
|
||||||
|
|
||||||
|
FROM cpu-test-1 AS build
|
||||||
|
|
||||||
|
COPY ./ /workspace/vllm
|
||||||
|
|
||||||
|
WORKDIR /workspace/vllm
|
||||||
|
|
||||||
|
RUN pip install -v -r requirements-cpu.txt --extra-index-url https://download.pytorch.org/whl/cpu
|
||||||
|
|
||||||
|
# Support for building with non-AVX512 vLLM: docker build --build-arg VLLM_CPU_DISABLE_AVX512="true" ...
|
||||||
|
ARG VLLM_CPU_DISABLE_AVX512
|
||||||
|
ENV VLLM_CPU_DISABLE_AVX512=${VLLM_CPU_DISABLE_AVX512}
|
||||||
|
|
||||||
|
RUN VLLM_TARGET_DEVICE=cpu python3 setup.py install
|
||||||
|
|
||||||
|
WORKDIR /workspace/
|
||||||
|
|
||||||
|
RUN ln -s /workspace/vllm/tests && ln -s /workspace/vllm/examples && ln -s /workspace/vllm/benchmarks
|
||||||
|
|
||||||
|
ENTRYPOINT ["python3", "-m", "vllm.entrypoints.openai.api_server"]
|
||||||
36
Dockerfile.neuron
Normal file
36
Dockerfile.neuron
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
# default base image
|
||||||
|
ARG BASE_IMAGE="763104351884.dkr.ecr.us-west-2.amazonaws.com/pytorch-inference-neuronx:2.1.1-neuronx-py310-sdk2.17.0-ubuntu20.04"
|
||||||
|
|
||||||
|
FROM $BASE_IMAGE
|
||||||
|
|
||||||
|
RUN echo "Base image is $BASE_IMAGE"
|
||||||
|
|
||||||
|
# Install some basic utilities
|
||||||
|
RUN apt-get update && apt-get install python3 python3-pip -y
|
||||||
|
|
||||||
|
### Mount Point ###
|
||||||
|
# When launching the container, mount the code directory to /app
|
||||||
|
ARG APP_MOUNT=/app
|
||||||
|
VOLUME [ ${APP_MOUNT} ]
|
||||||
|
WORKDIR ${APP_MOUNT}
|
||||||
|
|
||||||
|
RUN python3 -m pip install --upgrade pip
|
||||||
|
RUN python3 -m pip install --no-cache-dir fastapi ninja tokenizers pandas
|
||||||
|
RUN python3 -m pip install sentencepiece transformers==4.36.2 -U
|
||||||
|
RUN python3 -m pip install transformers-neuronx --extra-index-url=https://pip.repos.neuron.amazonaws.com -U
|
||||||
|
RUN python3 -m pip install --pre neuronx-cc==2.12.* --extra-index-url=https://pip.repos.neuron.amazonaws.com -U
|
||||||
|
|
||||||
|
COPY ./vllm /app/vllm/vllm
|
||||||
|
COPY ./setup.py /app/vllm/setup.py
|
||||||
|
COPY ./requirements-common.txt /app/vllm/requirements-common.txt
|
||||||
|
COPY ./requirements-neuron.txt /app/vllm/requirements-neuron.txt
|
||||||
|
|
||||||
|
RUN cd /app/vllm \
|
||||||
|
&& python3 -m pip install -U -r requirements-neuron.txt
|
||||||
|
|
||||||
|
ENV VLLM_TARGET_DEVICE neuron
|
||||||
|
RUN cd /app/vllm \
|
||||||
|
&& pip install -e . \
|
||||||
|
&& cd ..
|
||||||
|
|
||||||
|
CMD ["/bin/bash"]
|
||||||
26
Dockerfile.openvino
Normal file
26
Dockerfile.openvino
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
# The vLLM Dockerfile is used to construct vLLM image that can be directly used
|
||||||
|
# to run the OpenAI compatible server.
|
||||||
|
|
||||||
|
FROM ubuntu:22.04 AS dev
|
||||||
|
|
||||||
|
RUN apt-get update -y && \
|
||||||
|
apt-get install -y python3-pip git
|
||||||
|
WORKDIR /workspace
|
||||||
|
|
||||||
|
# copy requirements
|
||||||
|
COPY requirements-build.txt /workspace/vllm/
|
||||||
|
COPY requirements-common.txt /workspace/vllm/
|
||||||
|
COPY requirements-openvino.txt /workspace/vllm/
|
||||||
|
|
||||||
|
COPY vllm/ /workspace/vllm/vllm
|
||||||
|
COPY setup.py /workspace/vllm/
|
||||||
|
|
||||||
|
# install build requirements
|
||||||
|
RUN PIP_EXTRA_INDEX_URL="https://download.pytorch.org/whl/cpu" python3 -m pip install -r /workspace/vllm/requirements-build.txt
|
||||||
|
# build vLLM with OpenVINO backend
|
||||||
|
RUN PIP_PRE=1 PIP_EXTRA_INDEX_URL="https://download.pytorch.org/whl/cpu https://storage.openvinotoolkit.org/simple/wheels/nightly/" VLLM_TARGET_DEVICE="openvino" python3 -m pip install /workspace/vllm/
|
||||||
|
|
||||||
|
COPY examples/ /workspace/vllm/examples
|
||||||
|
COPY benchmarks/ /workspace/vllm/benchmarks
|
||||||
|
|
||||||
|
CMD ["/bin/bash"]
|
||||||
22
Dockerfile.ppc64le
Normal file
22
Dockerfile.ppc64le
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
FROM mambaorg/micromamba
|
||||||
|
ARG MAMBA_DOCKERFILE_ACTIVATE=1
|
||||||
|
USER root
|
||||||
|
|
||||||
|
RUN apt-get update -y && apt-get install -y git wget vim numactl gcc-12 g++-12 protobuf-compiler libprotobuf-dev && update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-12 10 --slave /usr/bin/g++ g++ /usr/bin/g++-12
|
||||||
|
|
||||||
|
# Some packages in requirements-cpu are installed here
|
||||||
|
# IBM provides optimized packages for ppc64le processors in the open-ce project for mamba
|
||||||
|
# Currently these may not be available for venv or pip directly
|
||||||
|
RUN micromamba install -y -n base -c https://ftp.osuosl.org/pub/open-ce/1.11.0-p10/ -c defaults python=3.10 pytorch-cpu=2.1.2 torchvision-cpu=0.16.2 && micromamba clean --all --yes
|
||||||
|
|
||||||
|
COPY ./ /workspace/vllm
|
||||||
|
|
||||||
|
WORKDIR /workspace/vllm
|
||||||
|
|
||||||
|
# These packages will be in rocketce eventually
|
||||||
|
RUN pip install -v -r requirements-cpu.txt --prefer-binary --extra-index-url https://repo.fury.io/mgiessing
|
||||||
|
|
||||||
|
RUN VLLM_TARGET_DEVICE=cpu python3 setup.py install
|
||||||
|
|
||||||
|
WORKDIR /vllm-workspace
|
||||||
|
ENTRYPOINT ["/opt/conda/bin/python3", "-m", "vllm.entrypoints.openai.api_server"]
|
||||||
217
Dockerfile.rocm
217
Dockerfile.rocm
@ -1,32 +1,35 @@
|
|||||||
# default base image
|
# Default ROCm 6.1 base image
|
||||||
ARG BASE_IMAGE="rocm/pytorch:rocm6.0_ubuntu20.04_py3.9_pytorch_2.1.1"
|
ARG BASE_IMAGE="rocm/pytorch:rocm6.1.2_ubuntu20.04_py3.9_pytorch_staging"
|
||||||
|
|
||||||
FROM $BASE_IMAGE
|
# Tested and supported base rocm/pytorch images
|
||||||
|
ARG ROCm_5_7_BASE="rocm/pytorch:rocm5.7_ubuntu20.04_py3.9_pytorch_2.0.1" \
|
||||||
|
ROCm_6_0_BASE="rocm/pytorch:rocm6.0_ubuntu20.04_py3.9_pytorch_2.1.1" \
|
||||||
|
ROCM_6_1_BASE="rocm/pytorch:rocm6.1.2_ubuntu20.04_py3.9_pytorch_staging"
|
||||||
|
|
||||||
ARG BASE_IMAGE="rocm/pytorch:rocm6.0_ubuntu20.04_py3.9_pytorch_2.1.1"
|
# Default ROCm ARCHes to build vLLM for.
|
||||||
|
ARG PYTORCH_ROCM_ARCH="gfx908;gfx90a;gfx942;gfx1100"
|
||||||
|
|
||||||
RUN echo "Base image is $BASE_IMAGE"
|
# Whether to build CK-based flash-attention
|
||||||
|
# If 0, will not build flash attention
|
||||||
# BASE_IMAGE for ROCm_5.7: "rocm/pytorch:rocm5.7_ubuntu22.04_py3.10_pytorch_2.0.1"
|
# This is useful for gfx target where flash-attention is not supported
|
||||||
# BASE_IMAGE for ROCm_6.0: "rocm/pytorch:rocm6.0_ubuntu20.04_py3.9_pytorch_2.1.1"
|
# (i.e. those that do not appear in `FA_GFX_ARCHS`)
|
||||||
|
# Triton FA is used by default on ROCm now so this is unnecessary.
|
||||||
|
|
||||||
ARG FA_GFX_ARCHS="gfx90a;gfx942"
|
|
||||||
RUN echo "FA_GFX_ARCHS is $FA_GFX_ARCHS"
|
|
||||||
|
|
||||||
ARG FA_BRANCH="3d2b6f5"
|
|
||||||
RUN echo "FA_BRANCH is $FA_BRANCH"
|
|
||||||
|
|
||||||
# whether to build flash-attention
|
|
||||||
# if 0, will not build flash attention
|
|
||||||
# this is useful for gfx target where flash-attention is not supported
|
|
||||||
# In that case, we need to use the python reference attention implementation in vllm
|
|
||||||
ARG BUILD_FA="1"
|
ARG BUILD_FA="1"
|
||||||
|
ARG FA_GFX_ARCHS="gfx90a;gfx942"
|
||||||
|
ARG FA_BRANCH="ae7928c"
|
||||||
|
|
||||||
|
# Whether to build triton on rocm
|
||||||
|
ARG BUILD_TRITON="1"
|
||||||
|
ARG TRITON_BRANCH="0ef1848"
|
||||||
|
|
||||||
|
### Base image build stage
|
||||||
|
FROM $BASE_IMAGE AS base
|
||||||
|
|
||||||
|
# Import arg(s) defined before this build stage
|
||||||
|
ARG PYTORCH_ROCM_ARCH
|
||||||
|
|
||||||
# Install some basic utilities
|
# Install some basic utilities
|
||||||
RUN apt-get update && apt-get install python3 python3-pip -y
|
RUN apt-get update && apt-get install python3 python3-pip -y
|
||||||
|
|
||||||
# Install some basic utilities
|
|
||||||
RUN apt-get update && apt-get install -y \
|
RUN apt-get update && apt-get install -y \
|
||||||
curl \
|
curl \
|
||||||
ca-certificates \
|
ca-certificates \
|
||||||
@ -37,59 +40,165 @@ RUN apt-get update && apt-get install -y \
|
|||||||
build-essential \
|
build-essential \
|
||||||
wget \
|
wget \
|
||||||
unzip \
|
unzip \
|
||||||
nvidia-cuda-toolkit \
|
|
||||||
tmux \
|
tmux \
|
||||||
|
ccache \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
### Mount Point ###
|
# When launching the container, mount the code directory to /vllm-workspace
|
||||||
# When launching the container, mount the code directory to /app
|
ARG APP_MOUNT=/vllm-workspace
|
||||||
ARG APP_MOUNT=/app
|
|
||||||
VOLUME [ ${APP_MOUNT} ]
|
|
||||||
WORKDIR ${APP_MOUNT}
|
WORKDIR ${APP_MOUNT}
|
||||||
|
|
||||||
RUN python3 -m pip install --upgrade pip
|
RUN pip install --upgrade pip
|
||||||
RUN python3 -m pip install --no-cache-dir fastapi ninja tokenizers pandas
|
# Remove sccache so it doesn't interfere with ccache
|
||||||
|
# TODO: implement sccache support across components
|
||||||
|
RUN apt-get purge -y sccache; pip uninstall -y sccache; rm -f "$(which sccache)"
|
||||||
|
# Install torch == 2.4.0 on ROCm
|
||||||
|
RUN case "$(ls /opt | grep -Po 'rocm-[0-9]\.[0-9]')" in \
|
||||||
|
*"rocm-5.7"*) \
|
||||||
|
pip uninstall -y torch torchaudio torchvision \
|
||||||
|
&& pip install --no-cache-dir --pre \
|
||||||
|
torch==2.4.0.dev20240612 torchaudio==2.4.0.dev20240612 \
|
||||||
|
torchvision==0.19.0.dev20240612 \
|
||||||
|
--index-url https://download.pytorch.org/whl/nightly/rocm5.7;; \
|
||||||
|
*"rocm-6.0"*) \
|
||||||
|
pip uninstall -y torch torchaudio torchvision \
|
||||||
|
&& pip install --no-cache-dir --pre \
|
||||||
|
torch==2.4.0.dev20240612 torchaudio==2.4.0.dev20240612 \
|
||||||
|
torchvision==0.19.0.dev20240612 \
|
||||||
|
--index-url https://download.pytorch.org/whl/nightly/rocm6.0;; \
|
||||||
|
*"rocm-6.1"*) \
|
||||||
|
pip uninstall -y torch torchaudio torchvision \
|
||||||
|
&& pip install --no-cache-dir --pre \
|
||||||
|
torch==2.4.0.dev20240612 torchaudio==2.4.0.dev20240612 \
|
||||||
|
torchvision==0.19.0.dev20240612 \
|
||||||
|
--index-url https://download.pytorch.org/whl/nightly/rocm6.1;; \
|
||||||
|
*) ;; esac
|
||||||
|
|
||||||
ENV LLVM_SYMBOLIZER_PATH=/opt/rocm/llvm/bin/llvm-symbolizer
|
ENV LLVM_SYMBOLIZER_PATH=/opt/rocm/llvm/bin/llvm-symbolizer
|
||||||
ENV PATH=$PATH:/opt/rocm/bin:/libtorch/bin:
|
ENV PATH=$PATH:/opt/rocm/bin:/libtorch/bin:
|
||||||
ENV LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/rocm/lib/:/libtorch/lib:
|
ENV LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/rocm/lib/:/libtorch/lib:
|
||||||
ENV CPLUS_INCLUDE_PATH=$CPLUS_INCLUDE_PATH:/libtorch/include:/libtorch/include/torch/csrc/api/include/:/opt/rocm/include/:
|
ENV CPLUS_INCLUDE_PATH=$CPLUS_INCLUDE_PATH:/libtorch/include:/libtorch/include/torch/csrc/api/include/:/opt/rocm/include/:
|
||||||
|
|
||||||
# Install ROCm flash-attention
|
ENV PYTORCH_ROCM_ARCH=${PYTORCH_ROCM_ARCH}
|
||||||
RUN if [ "$BUILD_FA" = "1" ]; then \
|
ENV CCACHE_DIR=/root/.cache/ccache
|
||||||
mkdir libs \
|
|
||||||
|
|
||||||
|
### AMD-SMI build stage
|
||||||
|
FROM base AS build_amdsmi
|
||||||
|
# Build amdsmi wheel always
|
||||||
|
RUN cd /opt/rocm/share/amd_smi \
|
||||||
|
&& pip wheel . --wheel-dir=/install
|
||||||
|
|
||||||
|
|
||||||
|
### Flash-Attention wheel build stage
|
||||||
|
FROM base AS build_fa
|
||||||
|
ARG BUILD_FA
|
||||||
|
ARG FA_GFX_ARCHS
|
||||||
|
ARG FA_BRANCH
|
||||||
|
# Build ROCm flash-attention wheel if `BUILD_FA = 1`
|
||||||
|
RUN --mount=type=cache,target=${CCACHE_DIR} \
|
||||||
|
if [ "$BUILD_FA" = "1" ]; then \
|
||||||
|
mkdir -p libs \
|
||||||
&& cd libs \
|
&& cd libs \
|
||||||
&& git clone https://github.com/ROCm/flash-attention.git \
|
&& git clone https://github.com/ROCm/flash-attention.git \
|
||||||
&& cd flash-attention \
|
&& cd flash-attention \
|
||||||
&& git checkout ${FA_BRANCH} \
|
&& git checkout "${FA_BRANCH}" \
|
||||||
&& git submodule update --init \
|
&& git submodule update --init \
|
||||||
&& export GPU_ARCHS=${FA_GFX_ARCHS} \
|
&& case "$(ls /opt | grep -Po 'rocm-[0-9]\.[0-9]')" in \
|
||||||
&& if [ "$BASE_IMAGE" = "rocm/pytorch:rocm5.7_ubuntu22.04_py3.10_pytorch_2.0.1" ]; then \
|
*"rocm-5.7"*) \
|
||||||
patch /opt/conda/envs/py_3.10/lib/python3.10/site-packages/torch/utils/hipify/hipify_python.py hipify_patch.patch; fi \
|
export VLLM_TORCH_PATH="$(python3 -c 'import torch; print(torch.__path__[0])')" \
|
||||||
&& python3 setup.py install \
|
&& patch "${VLLM_TORCH_PATH}"/utils/hipify/hipify_python.py hipify_patch.patch;; \
|
||||||
&& cd ..; \
|
*) ;; esac \
|
||||||
|
&& GPU_ARCHS="${FA_GFX_ARCHS}" python3 setup.py bdist_wheel --dist-dir=/install; \
|
||||||
|
# Create an empty directory otherwise as later build stages expect one
|
||||||
|
else mkdir -p /install; \
|
||||||
fi
|
fi
|
||||||
|
|
||||||
COPY ./ /app/vllm
|
|
||||||
|
|
||||||
RUN python3 -m pip install --upgrade pip
|
### Triton wheel build stage
|
||||||
RUN python3 -m pip install xformers==0.0.23 --no-deps
|
FROM base AS build_triton
|
||||||
|
ARG BUILD_TRITON
|
||||||
|
ARG TRITON_BRANCH
|
||||||
|
# Build triton wheel if `BUILD_TRITON = 1`
|
||||||
|
RUN --mount=type=cache,target=${CCACHE_DIR} \
|
||||||
|
if [ "$BUILD_TRITON" = "1" ]; then \
|
||||||
|
mkdir -p libs \
|
||||||
|
&& cd libs \
|
||||||
|
&& git clone https://github.com/OpenAI/triton.git \
|
||||||
|
&& cd triton \
|
||||||
|
&& git checkout "${TRITON_BRANCH}" \
|
||||||
|
&& cd python \
|
||||||
|
&& python3 setup.py bdist_wheel --dist-dir=/install; \
|
||||||
|
# Create an empty directory otherwise as later build stages expect one
|
||||||
|
else mkdir -p /install; \
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
|
### Final vLLM build stage
|
||||||
|
FROM base AS final
|
||||||
|
# Import the vLLM development directory from the build context
|
||||||
|
COPY . .
|
||||||
|
|
||||||
# Error related to odd state for numpy 1.20.3 where there is no METADATA etc, but an extra LICENSES_bundled.txt.
|
# Error related to odd state for numpy 1.20.3 where there is no METADATA etc, but an extra LICENSES_bundled.txt.
|
||||||
# Manually removed it so that later steps of numpy upgrade can continue
|
# Manually remove it so that later steps of numpy upgrade can continue
|
||||||
RUN if [ "$BASE_IMAGE" = "rocm/pytorch:rocm6.0_ubuntu20.04_py3.9_pytorch_2.1.1" ]; then \
|
RUN case "$(which python3)" in \
|
||||||
rm -rf /opt/conda/envs/py_3.9/lib/python3.9/site-packages/numpy-1.20.3.dist-info/; fi
|
*"/opt/conda/envs/py_3.9"*) \
|
||||||
|
rm -rf /opt/conda/envs/py_3.9/lib/python3.9/site-packages/numpy-1.20.3.dist-info/;; \
|
||||||
|
*) ;; esac
|
||||||
|
|
||||||
RUN cd /app \
|
# Package upgrades for useful functionality or to avoid dependency issues
|
||||||
&& cd vllm \
|
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||||
&& pip install -U -r requirements-rocm.txt \
|
pip install --upgrade numba scipy huggingface-hub[cli]
|
||||||
&& if [ "$BUILD_FA" = "1" ]; then \
|
|
||||||
bash patch_xformers.rocm.sh; fi \
|
|
||||||
&& patch /opt/rocm/include/hip/amd_detail/amd_hip_bf16.h /app/vllm/rocm_patch/rocm_bf16.patch \
|
|
||||||
&& python3 setup.py install \
|
|
||||||
&& cd ..
|
|
||||||
|
|
||||||
RUN python3 -m pip install --upgrade pip
|
# Make sure punica kernels are built (for LoRA)
|
||||||
RUN python3 -m pip install --no-cache-dir ray[all]
|
ENV VLLM_INSTALL_PUNICA_KERNELS=1
|
||||||
|
# Workaround for ray >= 2.10.0
|
||||||
|
ENV RAY_EXPERIMENTAL_NOSET_ROCR_VISIBLE_DEVICES=1
|
||||||
|
# Silences the HF Tokenizers warning
|
||||||
|
ENV TOKENIZERS_PARALLELISM=false
|
||||||
|
|
||||||
|
RUN --mount=type=cache,target=${CCACHE_DIR} \
|
||||||
|
--mount=type=cache,target=/root/.cache/pip \
|
||||||
|
pip install -U -r requirements-rocm.txt \
|
||||||
|
&& case "$(ls /opt | grep -Po 'rocm-[0-9]\.[0-9]')" in \
|
||||||
|
*"rocm-6.0"*) \
|
||||||
|
patch /opt/rocm/include/hip/amd_detail/amd_hip_bf16.h rocm_patch/rocm_bf16.patch;; \
|
||||||
|
*"rocm-6.1"*) \
|
||||||
|
# Bring in upgrades to HIP graph earlier than ROCm 6.2 for vLLM
|
||||||
|
wget -N https://github.com/ROCm/vllm/raw/fa78403/rocm_patch/libamdhip64.so.6 -P rocm_patch \
|
||||||
|
&& cp rocm_patch/libamdhip64.so.6 /opt/rocm/lib/libamdhip64.so.6 \
|
||||||
|
# Prevent interference if torch bundles its own HIP runtime
|
||||||
|
&& rm -f "$(python3 -c 'import torch; print(torch.__path__[0])')"/lib/libamdhip64.so* || true;; \
|
||||||
|
*) ;; esac \
|
||||||
|
&& python3 setup.py clean --all \
|
||||||
|
&& python3 setup.py develop
|
||||||
|
|
||||||
|
# Copy amdsmi wheel into final image
|
||||||
|
RUN --mount=type=bind,from=build_amdsmi,src=/install,target=/install \
|
||||||
|
mkdir -p libs \
|
||||||
|
&& cp /install/*.whl libs \
|
||||||
|
# Preemptively uninstall to avoid same-version no-installs
|
||||||
|
&& pip uninstall -y amdsmi;
|
||||||
|
|
||||||
|
# Copy triton wheel(s) into final image if they were built
|
||||||
|
RUN --mount=type=bind,from=build_triton,src=/install,target=/install \
|
||||||
|
mkdir -p libs \
|
||||||
|
&& if ls /install/*.whl; then \
|
||||||
|
cp /install/*.whl libs \
|
||||||
|
# Preemptively uninstall to avoid same-version no-installs
|
||||||
|
&& pip uninstall -y triton; fi
|
||||||
|
|
||||||
|
# Copy flash-attn wheel(s) into final image if they were built
|
||||||
|
RUN --mount=type=bind,from=build_fa,src=/install,target=/install \
|
||||||
|
mkdir -p libs \
|
||||||
|
&& if ls /install/*.whl; then \
|
||||||
|
cp /install/*.whl libs \
|
||||||
|
# Preemptively uninstall to avoid same-version no-installs
|
||||||
|
&& pip uninstall -y flash-attn; fi
|
||||||
|
|
||||||
|
# Install wheels that were built to the final image
|
||||||
|
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||||
|
if ls libs/*.whl; then \
|
||||||
|
pip install libs/*.whl; fi
|
||||||
|
|
||||||
CMD ["/bin/bash"]
|
CMD ["/bin/bash"]
|
||||||
|
|||||||
19
Dockerfile.tpu
Normal file
19
Dockerfile.tpu
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
ARG NIGHTLY_DATE="20240601"
|
||||||
|
ARG BASE_IMAGE="us-central1-docker.pkg.dev/tpu-pytorch-releases/docker/xla:nightly_3.10_tpuvm_$NIGHTLY_DATE"
|
||||||
|
|
||||||
|
FROM $BASE_IMAGE
|
||||||
|
|
||||||
|
WORKDIR /workspace
|
||||||
|
COPY . /workspace/vllm
|
||||||
|
|
||||||
|
ENV VLLM_TARGET_DEVICE="tpu"
|
||||||
|
# Install aiohttp separately to avoid build errors.
|
||||||
|
RUN pip install aiohttp
|
||||||
|
# Install the TPU and Pallas dependencies.
|
||||||
|
RUN pip install torch_xla[tpu] -f https://storage.googleapis.com/libtpu-releases/index.html
|
||||||
|
RUN pip install torch_xla[pallas] -f https://storage.googleapis.com/jax-releases/jax_nightly_releases.html -f https://storage.googleapis.com/jax-releases/jaxlib_nightly_releases.html
|
||||||
|
|
||||||
|
# Build vLLM.
|
||||||
|
RUN cd /workspace/vllm && python setup.py develop
|
||||||
|
|
||||||
|
CMD ["/bin/bash"]
|
||||||
22
Dockerfile.xpu
Normal file
22
Dockerfile.xpu
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
FROM intel/oneapi-basekit:2024.1.0-devel-ubuntu22.04
|
||||||
|
|
||||||
|
RUN wget -O- https://apt.repos.intel.com/intel-gpg-keys/GPG-PUB-KEY-INTEL-SW-PRODUCTS.PUB | gpg --dearmor | tee /usr/share/keyrings/intel-oneapi-archive-keyring.gpg > /dev/null && \
|
||||||
|
echo "deb [signed-by=/usr/share/keyrings/intel-oneapi-archive-keyring.gpg] https://apt.repos.intel.com/oneapi all main " | tee /etc/apt/sources.list.d/oneAPI.list && \
|
||||||
|
chmod 644 /usr/share/keyrings/intel-oneapi-archive-keyring.gpg && \
|
||||||
|
rm /etc/apt/sources.list.d/intel-graphics.list && \
|
||||||
|
wget -O- https://repositories.intel.com/graphics/intel-graphics.key | gpg --dearmor | tee /usr/share/keyrings/intel-graphics.gpg > /dev/null && \
|
||||||
|
echo "deb [arch=amd64,i386 signed-by=/usr/share/keyrings/intel-graphics.gpg] https://repositories.intel.com/graphics/ubuntu jammy arc" | tee /etc/apt/sources.list.d/intel.gpu.jammy.list && \
|
||||||
|
chmod 644 /usr/share/keyrings/intel-graphics.gpg
|
||||||
|
|
||||||
|
RUN apt-get update -y \
|
||||||
|
&& apt-get install -y curl libicu70 lsb-release git wget vim numactl python3 python3-pip
|
||||||
|
|
||||||
|
COPY ./ /workspace/vllm
|
||||||
|
|
||||||
|
WORKDIR /workspace/vllm
|
||||||
|
|
||||||
|
RUN pip install -v -r requirements-xpu.txt
|
||||||
|
|
||||||
|
RUN VLLM_TARGET_DEVICE=xpu python3 setup.py install
|
||||||
|
|
||||||
|
CMD ["/bin/bash"]
|
||||||
@ -1,4 +1,10 @@
|
|||||||
include LICENSE
|
include LICENSE
|
||||||
include requirements.txt
|
include requirements-common.txt
|
||||||
|
include requirements-cuda.txt
|
||||||
|
include requirements-rocm.txt
|
||||||
|
include requirements-neuron.txt
|
||||||
|
include requirements-cpu.txt
|
||||||
|
include CMakeLists.txt
|
||||||
|
|
||||||
|
recursive-include cmake *
|
||||||
recursive-include csrc *
|
recursive-include csrc *
|
||||||
|
|||||||
79
README.md
79
README.md
@ -16,7 +16,18 @@ Easy, fast, and cheap LLM serving for everyone
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
**Ray Summit CPF is Open (June 4th to June 20th)!**
|
||||||
|
|
||||||
|
There will be a track for vLLM at the Ray Summit (09/30-10/02, SF) this year!
|
||||||
|
If you have cool projects related to vLLM or LLM inference, we would love to see your proposals.
|
||||||
|
This will be a great chance for everyone in the community to get together and learn.
|
||||||
|
Please submit your proposal [here](https://raysummit.anyscale.com/flow/anyscale/raysummit2024/landing/page/eventsite)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
*Latest News* 🔥
|
*Latest News* 🔥
|
||||||
|
- [2024/06] We hosted [the fourth vLLM meetup](https://lu.ma/agivllm) with Cloudflare and BentoML! Please find the meetup slides [here](https://docs.google.com/presentation/d/1iJ8o7V2bQEi0BFEljLTwc5G1S10_Rhv3beed5oB0NJ4/edit?usp=sharing).
|
||||||
|
- [2024/04] We hosted [the third vLLM meetup](https://robloxandvllmmeetup2024.splashthat.com/) with Roblox! Please find the meetup slides [here](https://docs.google.com/presentation/d/1A--47JAK4BJ39t954HyTkvtfwn0fkqtsL8NGFuslReM/edit?usp=sharing).
|
||||||
- [2024/01] We hosted [the second vLLM meetup](https://lu.ma/ygxbpzhl) in SF! Please find the meetup slides [here](https://docs.google.com/presentation/d/12mI2sKABnUw5RBWXDYY-HtHth4iMSNcEoQ10jDQbxgA/edit?usp=sharing).
|
- [2024/01] We hosted [the second vLLM meetup](https://lu.ma/ygxbpzhl) in SF! Please find the meetup slides [here](https://docs.google.com/presentation/d/12mI2sKABnUw5RBWXDYY-HtHth4iMSNcEoQ10jDQbxgA/edit?usp=sharing).
|
||||||
- [2024/01] Added ROCm 6.0 support to vLLM.
|
- [2024/01] Added ROCm 6.0 support to vLLM.
|
||||||
- [2023/12] Added ROCm 5.7 support to vLLM.
|
- [2023/12] Added ROCm 5.7 support to vLLM.
|
||||||
@ -48,38 +59,18 @@ vLLM is flexible and easy to use with:
|
|||||||
- Tensor parallelism support for distributed inference
|
- Tensor parallelism support for distributed inference
|
||||||
- Streaming outputs
|
- Streaming outputs
|
||||||
- OpenAI-compatible API server
|
- OpenAI-compatible API server
|
||||||
- Support NVIDIA GPUs and AMD GPUs
|
- Support NVIDIA GPUs, AMD GPUs, Intel CPUs and GPUs
|
||||||
- (Experimental) Prefix caching support
|
- (Experimental) Prefix caching support
|
||||||
- (Experimental) Multi-lora support
|
- (Experimental) Multi-lora support
|
||||||
|
|
||||||
vLLM seamlessly supports many Hugging Face models, including the following architectures:
|
vLLM seamlessly supports most popular open-source models on HuggingFace, including:
|
||||||
|
- Transformer-like LLMs (e.g., Llama)
|
||||||
|
- Mixture-of-Expert LLMs (e.g., Mixtral)
|
||||||
|
- Multi-modal LLMs (e.g., LLaVA)
|
||||||
|
|
||||||
- Aquila & Aquila2 (`BAAI/AquilaChat2-7B`, `BAAI/AquilaChat2-34B`, `BAAI/Aquila-7B`, `BAAI/AquilaChat-7B`, etc.)
|
Find the full list of supported models [here](https://docs.vllm.ai/en/latest/models/supported_models.html).
|
||||||
- Baichuan & Baichuan2 (`baichuan-inc/Baichuan2-13B-Chat`, `baichuan-inc/Baichuan-7B`, etc.)
|
|
||||||
- BLOOM (`bigscience/bloom`, `bigscience/bloomz`, etc.)
|
## Getting Started
|
||||||
- ChatGLM (`THUDM/chatglm2-6b`, `THUDM/chatglm3-6b`, etc.)
|
|
||||||
- DeciLM (`Deci/DeciLM-7B`, `Deci/DeciLM-7B-instruct`, etc.)
|
|
||||||
- Falcon (`tiiuae/falcon-7b`, `tiiuae/falcon-40b`, `tiiuae/falcon-rw-7b`, etc.)
|
|
||||||
- Gemma (`google/gemma-2b`, `google/gemma-7b`, etc.)
|
|
||||||
- GPT-2 (`gpt2`, `gpt2-xl`, etc.)
|
|
||||||
- GPT BigCode (`bigcode/starcoder`, `bigcode/gpt_bigcode-santacoder`, etc.)
|
|
||||||
- GPT-J (`EleutherAI/gpt-j-6b`, `nomic-ai/gpt4all-j`, etc.)
|
|
||||||
- GPT-NeoX (`EleutherAI/gpt-neox-20b`, `databricks/dolly-v2-12b`, `stabilityai/stablelm-tuned-alpha-7b`, etc.)
|
|
||||||
- InternLM (`internlm/internlm-7b`, `internlm/internlm-chat-7b`, etc.)
|
|
||||||
- InternLM2 (`internlm/internlm2-7b`, `internlm/internlm2-chat-7b`, etc.)
|
|
||||||
- LLaMA & LLaMA-2 (`meta-llama/Llama-2-70b-hf`, `lmsys/vicuna-13b-v1.3`, `young-geng/koala`, `openlm-research/open_llama_13b`, etc.)
|
|
||||||
- Mistral (`mistralai/Mistral-7B-v0.1`, `mistralai/Mistral-7B-Instruct-v0.1`, etc.)
|
|
||||||
- Mixtral (`mistralai/Mixtral-8x7B-v0.1`, `mistralai/Mixtral-8x7B-Instruct-v0.1`, etc.)
|
|
||||||
- MPT (`mosaicml/mpt-7b`, `mosaicml/mpt-30b`, etc.)
|
|
||||||
- OLMo (`allenai/OLMo-1B`, `allenai/OLMo-7B`, etc.)
|
|
||||||
- OPT (`facebook/opt-66b`, `facebook/opt-iml-max-30b`, etc.)
|
|
||||||
- Orion (`OrionStarAI/Orion-14B-Base`, `OrionStarAI/Orion-14B-Chat`, etc.)
|
|
||||||
- Phi (`microsoft/phi-1_5`, `microsoft/phi-2`, etc.)
|
|
||||||
- Qwen (`Qwen/Qwen-7B`, `Qwen/Qwen-7B-Chat`, etc.)
|
|
||||||
- Qwen2 (`Qwen/Qwen2-7B-beta`, `Qwen/Qwen-7B-Chat-beta`, etc.)
|
|
||||||
- StableLM(`stabilityai/stablelm-3b-4e1t`, `stabilityai/stablelm-base-alpha-7b-v2`, etc.)
|
|
||||||
- Starcoder2(`bigcode/starcoder2-3b`, `bigcode/starcoder2-7b`, `bigcode/starcoder2-15b`, etc.)
|
|
||||||
- Yi (`01-ai/Yi-6B`, `01-ai/Yi-34B`, etc.)
|
|
||||||
|
|
||||||
Install vLLM with pip or [from source](https://vllm.readthedocs.io/en/latest/getting_started/installation.html#build-from-source):
|
Install vLLM with pip or [from source](https://vllm.readthedocs.io/en/latest/getting_started/installation.html#build-from-source):
|
||||||
|
|
||||||
@ -87,9 +78,7 @@ Install vLLM with pip or [from source](https://vllm.readthedocs.io/en/latest/get
|
|||||||
pip install vllm
|
pip install vllm
|
||||||
```
|
```
|
||||||
|
|
||||||
## Getting Started
|
Visit our [documentation](https://vllm.readthedocs.io/en/latest/) to learn more.
|
||||||
|
|
||||||
Visit our [documentation](https://vllm.readthedocs.io/en/latest/) to get started.
|
|
||||||
- [Installation](https://vllm.readthedocs.io/en/latest/getting_started/installation.html)
|
- [Installation](https://vllm.readthedocs.io/en/latest/getting_started/installation.html)
|
||||||
- [Quickstart](https://vllm.readthedocs.io/en/latest/getting_started/quickstart.html)
|
- [Quickstart](https://vllm.readthedocs.io/en/latest/getting_started/quickstart.html)
|
||||||
- [Supported Models](https://vllm.readthedocs.io/en/latest/models/supported_models.html)
|
- [Supported Models](https://vllm.readthedocs.io/en/latest/models/supported_models.html)
|
||||||
@ -99,6 +88,34 @@ Visit our [documentation](https://vllm.readthedocs.io/en/latest/) to get started
|
|||||||
We welcome and value any contributions and collaborations.
|
We welcome and value any contributions and collaborations.
|
||||||
Please check out [CONTRIBUTING.md](./CONTRIBUTING.md) for how to get involved.
|
Please check out [CONTRIBUTING.md](./CONTRIBUTING.md) for how to get involved.
|
||||||
|
|
||||||
|
## Sponsors
|
||||||
|
|
||||||
|
vLLM is a community project. Our compute resources for development and testing are supported by the following organizations. Thank you for your support!
|
||||||
|
|
||||||
|
<!-- Note: Please sort them in alphabetical order. -->
|
||||||
|
<!-- Note: Please keep these consistent with docs/source/community/sponsors.md -->
|
||||||
|
|
||||||
|
- a16z
|
||||||
|
- AMD
|
||||||
|
- Anyscale
|
||||||
|
- AWS
|
||||||
|
- Crusoe Cloud
|
||||||
|
- Databricks
|
||||||
|
- DeepInfra
|
||||||
|
- Dropbox
|
||||||
|
- Lambda Lab
|
||||||
|
- NVIDIA
|
||||||
|
- Replicate
|
||||||
|
- Roblox
|
||||||
|
- RunPod
|
||||||
|
- Sequoia Capital
|
||||||
|
- Trainy
|
||||||
|
- UC Berkeley
|
||||||
|
- UC San Diego
|
||||||
|
- ZhenFund
|
||||||
|
|
||||||
|
We also have an official fundraising venue through [OpenCollective](https://opencollective.com/vllm). We plan to use the fund to support the development, maintenance, and adoption of vLLM.
|
||||||
|
|
||||||
## Citation
|
## Citation
|
||||||
|
|
||||||
If you use vLLM for your research, please cite our [paper](https://arxiv.org/abs/2309.06180):
|
If you use vLLM for your research, please cite our [paper](https://arxiv.org/abs/2309.06180):
|
||||||
|
|||||||
@ -1,11 +1,16 @@
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import sys
|
||||||
import time
|
import time
|
||||||
from dataclasses import dataclass
|
import traceback
|
||||||
from typing import Optional
|
from dataclasses import dataclass, field
|
||||||
|
from typing import List, Optional, Union
|
||||||
|
|
||||||
import aiohttp
|
import aiohttp
|
||||||
|
import huggingface_hub.constants
|
||||||
from tqdm.asyncio import tqdm
|
from tqdm.asyncio import tqdm
|
||||||
|
from transformers import (AutoTokenizer, PreTrainedTokenizer,
|
||||||
|
PreTrainedTokenizerFast)
|
||||||
|
|
||||||
AIOHTTP_TIMEOUT = aiohttp.ClientTimeout(total=6 * 60 * 60)
|
AIOHTTP_TIMEOUT = aiohttp.ClientTimeout(total=6 * 60 * 60)
|
||||||
|
|
||||||
@ -25,9 +30,12 @@ class RequestFuncInput:
|
|||||||
class RequestFuncOutput:
|
class RequestFuncOutput:
|
||||||
generated_text: str = ""
|
generated_text: str = ""
|
||||||
success: bool = False
|
success: bool = False
|
||||||
latency: float = 0
|
latency: float = 0.0
|
||||||
ttft: float = 0
|
ttft: float = 0.0 # Time to first token
|
||||||
|
itl: List[float] = field(
|
||||||
|
default_factory=list) # List of inter-token latencies
|
||||||
prompt_len: int = 0
|
prompt_len: int = 0
|
||||||
|
error: str = ""
|
||||||
|
|
||||||
|
|
||||||
async def async_request_tgi(
|
async def async_request_tgi(
|
||||||
@ -53,73 +61,48 @@ async def async_request_tgi(
|
|||||||
output = RequestFuncOutput()
|
output = RequestFuncOutput()
|
||||||
output.prompt_len = request_func_input.prompt_len
|
output.prompt_len = request_func_input.prompt_len
|
||||||
|
|
||||||
ttft = 0
|
ttft = 0.0
|
||||||
st = time.perf_counter()
|
st = time.perf_counter()
|
||||||
|
most_recent_timestamp = st
|
||||||
try:
|
try:
|
||||||
async with session.post(url=api_url, json=payload) as response:
|
async with session.post(url=api_url, json=payload) as response:
|
||||||
if response.status == 200:
|
if response.status == 200:
|
||||||
async for data in response.content.iter_any():
|
async for chunk_bytes in response.content:
|
||||||
if ttft == 0:
|
chunk_bytes = chunk_bytes.strip()
|
||||||
|
if not chunk_bytes:
|
||||||
|
continue
|
||||||
|
chunk_bytes = chunk_bytes.decode("utf-8")
|
||||||
|
|
||||||
|
#NOTE: Sometimes TGI returns a ping response without
|
||||||
|
# any data, we should skip it.
|
||||||
|
if chunk_bytes.startswith(":"):
|
||||||
|
continue
|
||||||
|
chunk = remove_prefix(chunk_bytes, "data:")
|
||||||
|
|
||||||
|
data = json.loads(chunk)
|
||||||
|
timestamp = time.perf_counter()
|
||||||
|
# First token
|
||||||
|
if ttft == 0.0:
|
||||||
ttft = time.perf_counter() - st
|
ttft = time.perf_counter() - st
|
||||||
output.ttft = ttft
|
output.ttft = ttft
|
||||||
output.latency = time.perf_counter() - st
|
|
||||||
|
|
||||||
body = data.decode("utf-8").lstrip("data:")
|
# Decoding phase
|
||||||
output.generated_text = json.loads(body)["generated_text"]
|
else:
|
||||||
|
output.itl.append(timestamp -
|
||||||
|
most_recent_timestamp)
|
||||||
|
|
||||||
|
most_recent_timestamp = timestamp
|
||||||
|
|
||||||
|
output.latency = most_recent_timestamp - st
|
||||||
output.success = True
|
output.success = True
|
||||||
|
output.generated_text = data["generated_text"]
|
||||||
else:
|
else:
|
||||||
|
output.error = response.reason or ""
|
||||||
output.success = False
|
output.success = False
|
||||||
except (aiohttp.ClientOSError, aiohttp.ServerDisconnectedError):
|
except Exception:
|
||||||
output.success = False
|
|
||||||
|
|
||||||
if pbar:
|
|
||||||
pbar.update(1)
|
|
||||||
return output
|
|
||||||
|
|
||||||
|
|
||||||
async def async_request_vllm(
|
|
||||||
request_func_input: RequestFuncInput,
|
|
||||||
pbar: Optional[tqdm] = None,
|
|
||||||
) -> RequestFuncOutput:
|
|
||||||
api_url = request_func_input.api_url
|
|
||||||
assert api_url.endswith("generate")
|
|
||||||
|
|
||||||
async with aiohttp.ClientSession(timeout=AIOHTTP_TIMEOUT) as session:
|
|
||||||
payload = {
|
|
||||||
"prompt": request_func_input.prompt,
|
|
||||||
"n": 1,
|
|
||||||
"best_of": request_func_input.best_of,
|
|
||||||
"use_beam_search": request_func_input.use_beam_search,
|
|
||||||
"temperature": 0.0 if request_func_input.use_beam_search else 1.0,
|
|
||||||
"top_p": 1.0,
|
|
||||||
"max_tokens": request_func_input.output_len,
|
|
||||||
"ignore_eos": True,
|
|
||||||
"stream": True,
|
|
||||||
}
|
|
||||||
output = RequestFuncOutput()
|
|
||||||
output.prompt_len = request_func_input.prompt_len
|
|
||||||
|
|
||||||
ttft = 0
|
|
||||||
st = time.perf_counter()
|
|
||||||
try:
|
|
||||||
async with session.post(url=api_url, json=payload) as response:
|
|
||||||
if response.status == 200:
|
|
||||||
async for data in response.content.iter_any():
|
|
||||||
if ttft == 0:
|
|
||||||
ttft = time.perf_counter() - st
|
|
||||||
output.ttft = ttft
|
|
||||||
output.latency = time.perf_counter() - st
|
|
||||||
|
|
||||||
# When streaming, '\0' is appended to the end of the response.
|
|
||||||
body = data.decode("utf-8").strip("\0")
|
|
||||||
output.generated_text = json.loads(
|
|
||||||
body)["text"][0][len(request_func_input.prompt):]
|
|
||||||
output.success = True
|
|
||||||
|
|
||||||
else:
|
|
||||||
output.success = False
|
|
||||||
except (aiohttp.ClientOSError, aiohttp.ServerDisconnectedError):
|
|
||||||
output.success = False
|
output.success = False
|
||||||
|
exc_info = sys.exc_info()
|
||||||
|
output.error = "".join(traceback.format_exception(*exc_info))
|
||||||
|
|
||||||
if pbar:
|
if pbar:
|
||||||
pbar.update(1)
|
pbar.update(1)
|
||||||
@ -146,26 +129,46 @@ async def async_request_trt_llm(
|
|||||||
}
|
}
|
||||||
output = RequestFuncOutput()
|
output = RequestFuncOutput()
|
||||||
output.prompt_len = request_func_input.prompt_len
|
output.prompt_len = request_func_input.prompt_len
|
||||||
ttft = 0
|
|
||||||
|
|
||||||
|
ttft = 0.0
|
||||||
st = time.perf_counter()
|
st = time.perf_counter()
|
||||||
|
most_recent_timestamp = st
|
||||||
try:
|
try:
|
||||||
async with session.post(url=api_url, json=payload) as resp:
|
async with session.post(url=api_url, json=payload) as response:
|
||||||
if resp.status == 200:
|
if response.status == 200:
|
||||||
async for data in resp.content.iter_any():
|
async for chunk_bytes in response.content:
|
||||||
if ttft == 0:
|
chunk_bytes = chunk_bytes.strip()
|
||||||
|
if not chunk_bytes:
|
||||||
|
continue
|
||||||
|
|
||||||
|
chunk = remove_prefix(chunk_bytes.decode("utf-8"),
|
||||||
|
"data:")
|
||||||
|
|
||||||
|
data = json.loads(chunk)
|
||||||
|
output.generated_text += data["text_output"]
|
||||||
|
timestamp = time.perf_counter()
|
||||||
|
# First token
|
||||||
|
if ttft == 0.0:
|
||||||
ttft = time.perf_counter() - st
|
ttft = time.perf_counter() - st
|
||||||
output.ttft = ttft
|
output.ttft = ttft
|
||||||
output.latency = time.perf_counter() - st
|
|
||||||
|
|
||||||
body = data.decode("utf-8").lstrip("data:")
|
# Decoding phase
|
||||||
output.generated_text = json.loads(body)["text_output"]
|
else:
|
||||||
|
output.itl.append(timestamp -
|
||||||
|
most_recent_timestamp)
|
||||||
|
|
||||||
|
most_recent_timestamp = timestamp
|
||||||
|
|
||||||
|
output.latency = most_recent_timestamp - st
|
||||||
output.success = True
|
output.success = True
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
output.error = response.reason or ""
|
||||||
output.success = False
|
output.success = False
|
||||||
except (aiohttp.ClientOSError, aiohttp.ServerDisconnectedError):
|
except Exception:
|
||||||
output.success = False
|
output.success = False
|
||||||
|
exc_info = sys.exc_info()
|
||||||
|
output.error = "".join(traceback.format_exception(*exc_info))
|
||||||
|
|
||||||
if pbar:
|
if pbar:
|
||||||
pbar.update(1)
|
pbar.update(1)
|
||||||
@ -181,34 +184,35 @@ async def async_request_deepspeed_mii(
|
|||||||
assert not request_func_input.use_beam_search
|
assert not request_func_input.use_beam_search
|
||||||
|
|
||||||
payload = {
|
payload = {
|
||||||
"prompts": request_func_input.prompt,
|
"prompt": request_func_input.prompt,
|
||||||
"max_new_tokens": request_func_input.output_len,
|
"max_tokens": request_func_input.output_len,
|
||||||
"ignore_eos": True,
|
"temperature": 0.01, # deepspeed-mii does not accept 0.0 temp.
|
||||||
"do_sample": True,
|
|
||||||
"temperature":
|
|
||||||
0.01, # deepspeed-mii does not accept 0.0 temperature.
|
|
||||||
"top_p": 1.0,
|
"top_p": 1.0,
|
||||||
}
|
}
|
||||||
output = RequestFuncOutput()
|
output = RequestFuncOutput()
|
||||||
output.prompt_len = request_func_input.prompt_len
|
output.prompt_len = request_func_input.prompt_len
|
||||||
|
|
||||||
# DeepSpeed-MII doesn't support streaming as of Jan 28 2024, will use 0 as placeholder.
|
# NOTE: DeepSpeed-MII doesn't support streaming as of Jan 28 2024,
|
||||||
# https://github.com/microsoft/DeepSpeed-MII/pull/311
|
# will use 0 as placeholder.
|
||||||
|
# See https://github.com/microsoft/DeepSpeed-MII/pull/311
|
||||||
output.ttft = 0
|
output.ttft = 0
|
||||||
|
|
||||||
st = time.perf_counter()
|
st = time.perf_counter()
|
||||||
try:
|
try:
|
||||||
async with session.post(url=request_func_input.api_url,
|
async with session.post(url=request_func_input.api_url,
|
||||||
json=payload) as resp:
|
json=payload) as response:
|
||||||
if resp.status == 200:
|
if response.status == 200:
|
||||||
parsed_resp = await resp.json()
|
parsed_resp = await response.json()
|
||||||
output.latency = time.perf_counter() - st
|
output.latency = time.perf_counter() - st
|
||||||
output.generated_text = parsed_resp[0]["generated_text"]
|
output.generated_text = parsed_resp["text"][0]
|
||||||
output.success = True
|
output.success = True
|
||||||
else:
|
else:
|
||||||
|
output.error = response.reason or ""
|
||||||
output.success = False
|
output.success = False
|
||||||
except (aiohttp.ClientOSError, aiohttp.ServerDisconnectedError):
|
except Exception:
|
||||||
output.success = False
|
output.success = False
|
||||||
|
exc_info = sys.exc_info()
|
||||||
|
output.error = "".join(traceback.format_exception(*exc_info))
|
||||||
|
|
||||||
if pbar:
|
if pbar:
|
||||||
pbar.update(1)
|
pbar.update(1)
|
||||||
@ -220,7 +224,9 @@ async def async_request_openai_completions(
|
|||||||
pbar: Optional[tqdm] = None,
|
pbar: Optional[tqdm] = None,
|
||||||
) -> RequestFuncOutput:
|
) -> RequestFuncOutput:
|
||||||
api_url = request_func_input.api_url
|
api_url = request_func_input.api_url
|
||||||
assert api_url.endswith("v1/completions")
|
assert api_url.endswith(
|
||||||
|
"completions"
|
||||||
|
), "OpenAI Completions API URL must end with 'completions'."
|
||||||
|
|
||||||
async with aiohttp.ClientSession(timeout=AIOHTTP_TIMEOUT) as session:
|
async with aiohttp.ClientSession(timeout=AIOHTTP_TIMEOUT) as session:
|
||||||
assert not request_func_input.use_beam_search
|
assert not request_func_input.use_beam_search
|
||||||
@ -240,45 +246,181 @@ async def async_request_openai_completions(
|
|||||||
output.prompt_len = request_func_input.prompt_len
|
output.prompt_len = request_func_input.prompt_len
|
||||||
|
|
||||||
generated_text = ""
|
generated_text = ""
|
||||||
ttft = 0
|
ttft = 0.0
|
||||||
st = time.perf_counter()
|
st = time.perf_counter()
|
||||||
|
most_recent_timestamp = st
|
||||||
try:
|
try:
|
||||||
async with session.post(url=api_url, json=payload,
|
async with session.post(url=api_url, json=payload,
|
||||||
headers=headers) as response:
|
headers=headers) as response:
|
||||||
if response.status == 200:
|
if response.status == 200:
|
||||||
async for chunk in response.content:
|
async for chunk_bytes in response.content:
|
||||||
if ttft == 0:
|
chunk_bytes = chunk_bytes.strip()
|
||||||
ttft = time.perf_counter() - st
|
if not chunk_bytes:
|
||||||
output.ttft = ttft
|
|
||||||
|
|
||||||
chunk = chunk.strip()
|
|
||||||
if not chunk:
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
chunk = chunk.decode("utf-8").lstrip("data: ")
|
chunk = remove_prefix(chunk_bytes.decode("utf-8"),
|
||||||
|
"data: ")
|
||||||
if chunk == "[DONE]":
|
if chunk == "[DONE]":
|
||||||
latency = time.perf_counter() - st
|
latency = time.perf_counter() - st
|
||||||
else:
|
else:
|
||||||
body = json.loads(chunk)
|
data = json.loads(chunk)
|
||||||
generated_text += body["choices"][0]["text"]
|
|
||||||
|
# NOTE: Some completion API might have a last
|
||||||
|
# usage summary response without a token so we
|
||||||
|
# want to check a token was generated
|
||||||
|
if data["choices"][0]["text"]:
|
||||||
|
timestamp = time.perf_counter()
|
||||||
|
# First token
|
||||||
|
if ttft == 0.0:
|
||||||
|
ttft = time.perf_counter() - st
|
||||||
|
output.ttft = ttft
|
||||||
|
|
||||||
|
# Decoding phase
|
||||||
|
output.itl.append(timestamp -
|
||||||
|
most_recent_timestamp)
|
||||||
|
|
||||||
|
most_recent_timestamp = timestamp
|
||||||
|
generated_text += data["choices"][0]["text"]
|
||||||
|
|
||||||
output.generated_text = generated_text
|
output.generated_text = generated_text
|
||||||
output.success = True
|
output.success = True
|
||||||
output.latency = latency
|
output.latency = latency
|
||||||
else:
|
else:
|
||||||
|
output.error = response.reason or ""
|
||||||
output.success = False
|
output.success = False
|
||||||
except (aiohttp.ClientOSError, aiohttp.ServerDisconnectedError):
|
except Exception:
|
||||||
output.success = False
|
output.success = False
|
||||||
|
exc_info = sys.exc_info()
|
||||||
|
output.error = "".join(traceback.format_exception(*exc_info))
|
||||||
|
|
||||||
if pbar:
|
if pbar:
|
||||||
pbar.update(1)
|
pbar.update(1)
|
||||||
return output
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
async def async_request_openai_chat_completions(
|
||||||
|
request_func_input: RequestFuncInput,
|
||||||
|
pbar: Optional[tqdm] = None,
|
||||||
|
) -> RequestFuncOutput:
|
||||||
|
api_url = request_func_input.api_url
|
||||||
|
assert api_url.endswith(
|
||||||
|
"chat/completions"
|
||||||
|
), "OpenAI Chat Completions API URL must end with 'chat/completions'."
|
||||||
|
|
||||||
|
async with aiohttp.ClientSession(timeout=AIOHTTP_TIMEOUT) as session:
|
||||||
|
assert not request_func_input.use_beam_search
|
||||||
|
payload = {
|
||||||
|
"model": request_func_input.model,
|
||||||
|
"messages": [
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": request_func_input.prompt,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"temperature": 0.0,
|
||||||
|
"max_tokens": request_func_input.output_len,
|
||||||
|
"stream": True,
|
||||||
|
}
|
||||||
|
headers = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Authorization": f"Bearer {os.environ.get('OPENAI_API_KEY')}",
|
||||||
|
}
|
||||||
|
|
||||||
|
output = RequestFuncOutput()
|
||||||
|
output.prompt_len = request_func_input.prompt_len
|
||||||
|
|
||||||
|
generated_text = ""
|
||||||
|
ttft = 0.0
|
||||||
|
st = time.perf_counter()
|
||||||
|
most_recent_timestamp = st
|
||||||
|
try:
|
||||||
|
async with session.post(url=api_url, json=payload,
|
||||||
|
headers=headers) as response:
|
||||||
|
if response.status == 200:
|
||||||
|
async for chunk_bytes in response.content:
|
||||||
|
chunk_bytes = chunk_bytes.strip()
|
||||||
|
if not chunk_bytes:
|
||||||
|
continue
|
||||||
|
|
||||||
|
chunk = remove_prefix(chunk_bytes.decode("utf-8"),
|
||||||
|
"data: ")
|
||||||
|
if chunk == "[DONE]":
|
||||||
|
latency = time.perf_counter() - st
|
||||||
|
else:
|
||||||
|
timestamp = time.perf_counter()
|
||||||
|
data = json.loads(chunk)
|
||||||
|
|
||||||
|
delta = data["choices"][0]["delta"]
|
||||||
|
if delta.get("content", None):
|
||||||
|
# First token
|
||||||
|
if ttft == 0.0:
|
||||||
|
ttft = time.perf_counter() - st
|
||||||
|
output.ttft = ttft
|
||||||
|
|
||||||
|
# Decoding phase
|
||||||
|
else:
|
||||||
|
output.itl.append(timestamp -
|
||||||
|
most_recent_timestamp)
|
||||||
|
|
||||||
|
generated_text += delta["content"]
|
||||||
|
|
||||||
|
most_recent_timestamp = timestamp
|
||||||
|
|
||||||
|
output.generated_text = generated_text
|
||||||
|
output.success = True
|
||||||
|
output.latency = latency
|
||||||
|
else:
|
||||||
|
output.error = response.reason or ""
|
||||||
|
output.success = False
|
||||||
|
except Exception:
|
||||||
|
output.success = False
|
||||||
|
exc_info = sys.exc_info()
|
||||||
|
output.error = "".join(traceback.format_exception(*exc_info))
|
||||||
|
|
||||||
|
if pbar:
|
||||||
|
pbar.update(1)
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
# Since vllm must support Python 3.8, we can't use str.removeprefix(prefix)
|
||||||
|
# introduced in Python 3.9
|
||||||
|
def remove_prefix(text: str, prefix: str) -> str:
|
||||||
|
if text.startswith(prefix):
|
||||||
|
return text[len(prefix):]
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def get_model(pretrained_model_name_or_path: str):
|
||||||
|
if os.getenv('VLLM_USE_MODELSCOPE', 'False').lower() == 'true':
|
||||||
|
from modelscope import snapshot_download
|
||||||
|
else:
|
||||||
|
from huggingface_hub import snapshot_download
|
||||||
|
|
||||||
|
model_path = snapshot_download(
|
||||||
|
model_id=pretrained_model_name_or_path,
|
||||||
|
local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
|
||||||
|
ignore_file_pattern=[".*.pt", ".*.safetensors", ".*.bin"])
|
||||||
|
return model_path
|
||||||
|
|
||||||
|
|
||||||
|
def get_tokenizer(
|
||||||
|
pretrained_model_name_or_path: str, trust_remote_code: bool
|
||||||
|
) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]:
|
||||||
|
if pretrained_model_name_or_path is not None and not os.path.exists(
|
||||||
|
pretrained_model_name_or_path):
|
||||||
|
pretrained_model_name_or_path = get_model(
|
||||||
|
pretrained_model_name_or_path)
|
||||||
|
return AutoTokenizer.from_pretrained(pretrained_model_name_or_path,
|
||||||
|
trust_remote_code=trust_remote_code)
|
||||||
|
|
||||||
|
|
||||||
ASYNC_REQUEST_FUNCS = {
|
ASYNC_REQUEST_FUNCS = {
|
||||||
"tgi": async_request_tgi,
|
"tgi": async_request_tgi,
|
||||||
"vllm": async_request_vllm,
|
"vllm": async_request_openai_completions,
|
||||||
|
"lmdeploy": async_request_openai_completions,
|
||||||
"deepspeed-mii": async_request_deepspeed_mii,
|
"deepspeed-mii": async_request_deepspeed_mii,
|
||||||
"openai": async_request_openai_completions,
|
"openai": async_request_openai_completions,
|
||||||
|
"openai-chat": async_request_openai_chat_completions,
|
||||||
"tensorrt-llm": async_request_trt_llm,
|
"tensorrt-llm": async_request_trt_llm,
|
||||||
|
"scalellm": async_request_openai_completions,
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,14 +1,19 @@
|
|||||||
"""Benchmark the latency of processing a single batch of requests."""
|
"""Benchmark the latency of processing a single batch of requests."""
|
||||||
import argparse
|
import argparse
|
||||||
|
import json
|
||||||
import time
|
import time
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Optional
|
from typing import List, Optional
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
from tqdm import tqdm
|
from tqdm import tqdm
|
||||||
|
|
||||||
from vllm import LLM, SamplingParams
|
from vllm import LLM, SamplingParams
|
||||||
|
from vllm.engine.arg_utils import EngineArgs
|
||||||
|
from vllm.inputs import PromptStrictInputs
|
||||||
|
from vllm.model_executor.layers.quantization import QUANTIZATION_METHODS
|
||||||
|
from vllm.utils import FlexibleArgumentParser
|
||||||
|
|
||||||
|
|
||||||
def main(args: argparse.Namespace):
|
def main(args: argparse.Namespace):
|
||||||
@ -18,14 +23,30 @@ def main(args: argparse.Namespace):
|
|||||||
# the engine will automatically process the request in multiple batches.
|
# the engine will automatically process the request in multiple batches.
|
||||||
llm = LLM(
|
llm = LLM(
|
||||||
model=args.model,
|
model=args.model,
|
||||||
|
speculative_model=args.speculative_model,
|
||||||
|
num_speculative_tokens=args.num_speculative_tokens,
|
||||||
|
speculative_draft_tensor_parallel_size=\
|
||||||
|
args.speculative_draft_tensor_parallel_size,
|
||||||
tokenizer=args.tokenizer,
|
tokenizer=args.tokenizer,
|
||||||
quantization=args.quantization,
|
quantization=args.quantization,
|
||||||
tensor_parallel_size=args.tensor_parallel_size,
|
tensor_parallel_size=args.tensor_parallel_size,
|
||||||
trust_remote_code=args.trust_remote_code,
|
trust_remote_code=args.trust_remote_code,
|
||||||
dtype=args.dtype,
|
dtype=args.dtype,
|
||||||
|
max_model_len=args.max_model_len,
|
||||||
enforce_eager=args.enforce_eager,
|
enforce_eager=args.enforce_eager,
|
||||||
kv_cache_dtype=args.kv_cache_dtype,
|
kv_cache_dtype=args.kv_cache_dtype,
|
||||||
|
quantization_param_path=args.quantization_param_path,
|
||||||
device=args.device,
|
device=args.device,
|
||||||
|
ray_workers_use_nsight=args.ray_workers_use_nsight,
|
||||||
|
use_v2_block_manager=args.use_v2_block_manager,
|
||||||
|
enable_chunked_prefill=args.enable_chunked_prefill,
|
||||||
|
download_dir=args.download_dir,
|
||||||
|
block_size=args.block_size,
|
||||||
|
gpu_memory_utilization=args.gpu_memory_utilization,
|
||||||
|
load_format=args.load_format,
|
||||||
|
distributed_executor_backend=args.distributed_executor_backend,
|
||||||
|
otlp_traces_endpoint=args.otlp_traces_endpoint,
|
||||||
|
enable_prefix_caching=args.enable_prefix_caching,
|
||||||
)
|
)
|
||||||
|
|
||||||
sampling_params = SamplingParams(
|
sampling_params = SamplingParams(
|
||||||
@ -40,7 +61,9 @@ def main(args: argparse.Namespace):
|
|||||||
dummy_prompt_token_ids = np.random.randint(10000,
|
dummy_prompt_token_ids = np.random.randint(10000,
|
||||||
size=(args.batch_size,
|
size=(args.batch_size,
|
||||||
args.input_len))
|
args.input_len))
|
||||||
dummy_prompt_token_ids = dummy_prompt_token_ids.tolist()
|
dummy_inputs: List[PromptStrictInputs] = [{
|
||||||
|
"prompt_token_ids": batch
|
||||||
|
} for batch in dummy_prompt_token_ids.tolist()]
|
||||||
|
|
||||||
def run_to_completion(profile_dir: Optional[str] = None):
|
def run_to_completion(profile_dir: Optional[str] = None):
|
||||||
if profile_dir:
|
if profile_dir:
|
||||||
@ -51,13 +74,13 @@ def main(args: argparse.Namespace):
|
|||||||
],
|
],
|
||||||
on_trace_ready=torch.profiler.tensorboard_trace_handler(
|
on_trace_ready=torch.profiler.tensorboard_trace_handler(
|
||||||
str(profile_dir))) as p:
|
str(profile_dir))) as p:
|
||||||
llm.generate(prompt_token_ids=dummy_prompt_token_ids,
|
llm.generate(dummy_inputs,
|
||||||
sampling_params=sampling_params,
|
sampling_params=sampling_params,
|
||||||
use_tqdm=False)
|
use_tqdm=False)
|
||||||
print(p.key_averages())
|
print(p.key_averages())
|
||||||
else:
|
else:
|
||||||
start_time = time.perf_counter()
|
start_time = time.perf_counter()
|
||||||
llm.generate(prompt_token_ids=dummy_prompt_token_ids,
|
llm.generate(dummy_inputs,
|
||||||
sampling_params=sampling_params,
|
sampling_params=sampling_params,
|
||||||
use_tqdm=False)
|
use_tqdm=False)
|
||||||
end_time = time.perf_counter()
|
end_time = time.perf_counter()
|
||||||
@ -65,7 +88,8 @@ def main(args: argparse.Namespace):
|
|||||||
return latency
|
return latency
|
||||||
|
|
||||||
print("Warming up...")
|
print("Warming up...")
|
||||||
run_to_completion(profile_dir=None)
|
for _ in tqdm(range(args.num_iters_warmup), desc="Warmup iterations"):
|
||||||
|
run_to_completion(profile_dir=None)
|
||||||
|
|
||||||
if args.profile:
|
if args.profile:
|
||||||
profile_dir = args.profile_result_dir
|
profile_dir = args.profile_result_dir
|
||||||
@ -81,18 +105,39 @@ def main(args: argparse.Namespace):
|
|||||||
latencies = []
|
latencies = []
|
||||||
for _ in tqdm(range(args.num_iters), desc="Profiling iterations"):
|
for _ in tqdm(range(args.num_iters), desc="Profiling iterations"):
|
||||||
latencies.append(run_to_completion(profile_dir=None))
|
latencies.append(run_to_completion(profile_dir=None))
|
||||||
|
latencies = np.array(latencies)
|
||||||
|
percentages = [10, 25, 50, 75, 90, 99]
|
||||||
|
percentiles = np.percentile(latencies, percentages)
|
||||||
print(f'Avg latency: {np.mean(latencies)} seconds')
|
print(f'Avg latency: {np.mean(latencies)} seconds')
|
||||||
|
for percentage, percentile in zip(percentages, percentiles):
|
||||||
|
print(f'{percentage}% percentile latency: {percentile} seconds')
|
||||||
|
|
||||||
|
# Output JSON results if specified
|
||||||
|
if args.output_json:
|
||||||
|
results = {
|
||||||
|
"avg_latency": np.mean(latencies),
|
||||||
|
"latencies": latencies.tolist(),
|
||||||
|
"percentiles": dict(zip(percentages, percentiles.tolist())),
|
||||||
|
}
|
||||||
|
with open(args.output_json, "w") as f:
|
||||||
|
json.dump(results, f, indent=4)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
parser = argparse.ArgumentParser(
|
parser = FlexibleArgumentParser(
|
||||||
description='Benchmark the latency of processing a single batch of '
|
description='Benchmark the latency of processing a single batch of '
|
||||||
'requests till completion.')
|
'requests till completion.')
|
||||||
parser.add_argument('--model', type=str, default='facebook/opt-125m')
|
parser.add_argument('--model', type=str, default='facebook/opt-125m')
|
||||||
|
parser.add_argument('--speculative-model', type=str, default=None)
|
||||||
|
parser.add_argument('--num-speculative-tokens', type=int, default=None)
|
||||||
|
parser.add_argument('--speculative-draft-tensor-parallel-size',
|
||||||
|
'-spec-draft-tp',
|
||||||
|
type=int,
|
||||||
|
default=None)
|
||||||
parser.add_argument('--tokenizer', type=str, default=None)
|
parser.add_argument('--tokenizer', type=str, default=None)
|
||||||
parser.add_argument('--quantization',
|
parser.add_argument('--quantization',
|
||||||
'-q',
|
'-q',
|
||||||
choices=['awq', 'gptq', 'squeezellm', None],
|
choices=[*QUANTIZATION_METHODS, None],
|
||||||
default=None)
|
default=None)
|
||||||
parser.add_argument('--tensor-parallel-size', '-tp', type=int, default=1)
|
parser.add_argument('--tensor-parallel-size', '-tp', type=int, default=1)
|
||||||
parser.add_argument('--input-len', type=int, default=32)
|
parser.add_argument('--input-len', type=int, default=32)
|
||||||
@ -103,13 +148,23 @@ if __name__ == '__main__':
|
|||||||
default=1,
|
default=1,
|
||||||
help='Number of generated sequences per prompt.')
|
help='Number of generated sequences per prompt.')
|
||||||
parser.add_argument('--use-beam-search', action='store_true')
|
parser.add_argument('--use-beam-search', action='store_true')
|
||||||
|
parser.add_argument('--num-iters-warmup',
|
||||||
|
type=int,
|
||||||
|
default=10,
|
||||||
|
help='Number of iterations to run for warmup.')
|
||||||
parser.add_argument('--num-iters',
|
parser.add_argument('--num-iters',
|
||||||
type=int,
|
type=int,
|
||||||
default=3,
|
default=30,
|
||||||
help='Number of iterations to run.')
|
help='Number of iterations to run.')
|
||||||
parser.add_argument('--trust-remote-code',
|
parser.add_argument('--trust-remote-code',
|
||||||
action='store_true',
|
action='store_true',
|
||||||
help='trust remote code from huggingface')
|
help='trust remote code from huggingface')
|
||||||
|
parser.add_argument(
|
||||||
|
'--max-model-len',
|
||||||
|
type=int,
|
||||||
|
default=None,
|
||||||
|
help='Maximum length of a sequence (including prompt and output). '
|
||||||
|
'If None, will be derived from the model.')
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
'--dtype',
|
'--dtype',
|
||||||
type=str,
|
type=str,
|
||||||
@ -123,12 +178,23 @@ if __name__ == '__main__':
|
|||||||
action='store_true',
|
action='store_true',
|
||||||
help='enforce eager mode and disable CUDA graph')
|
help='enforce eager mode and disable CUDA graph')
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--kv-cache-dtype",
|
'--kv-cache-dtype',
|
||||||
type=str,
|
type=str,
|
||||||
choices=['auto', 'fp8_e5m2'],
|
choices=['auto', 'fp8', 'fp8_e5m2', 'fp8_e4m3'],
|
||||||
default='auto',
|
default="auto",
|
||||||
help=
|
help='Data type for kv cache storage. If "auto", will use model '
|
||||||
'Data type for kv cache storage. If "auto", will use model data type.')
|
'data type. CUDA 11.8+ supports fp8 (=fp8_e4m3) and fp8_e5m2. '
|
||||||
|
'ROCm (AMD GPU) supports fp8 (=fp8_e4m3)')
|
||||||
|
parser.add_argument(
|
||||||
|
'--quantization-param-path',
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help='Path to the JSON file containing the KV cache scaling factors. '
|
||||||
|
'This should generally be supplied, when KV cache dtype is FP8. '
|
||||||
|
'Otherwise, KV cache scaling factors default to 1.0, which may cause '
|
||||||
|
'accuracy issues. FP8_E5M2 (without scaling) is only supported on '
|
||||||
|
'cuda version greater than 11.8. On ROCm (AMD GPU), FP8_E4M3 is '
|
||||||
|
'instead supported for common inference criteria.')
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
'--profile',
|
'--profile',
|
||||||
action='store_true',
|
action='store_true',
|
||||||
@ -142,8 +208,78 @@ if __name__ == '__main__':
|
|||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--device",
|
"--device",
|
||||||
type=str,
|
type=str,
|
||||||
default="cuda",
|
default="auto",
|
||||||
choices=["cuda"],
|
choices=["auto", "cuda", "cpu", "openvino", "tpu", "xpu"],
|
||||||
help='device type for vLLM execution, supporting CUDA only currently.')
|
help='device type for vLLM execution, supporting CUDA, OpenVINO and '
|
||||||
|
'CPU.')
|
||||||
|
parser.add_argument('--block-size',
|
||||||
|
type=int,
|
||||||
|
default=16,
|
||||||
|
help='block size of key/value cache')
|
||||||
|
parser.add_argument(
|
||||||
|
'--enable-chunked-prefill',
|
||||||
|
action='store_true',
|
||||||
|
help='If True, the prefill requests can be chunked based on the '
|
||||||
|
'max_num_batched_tokens')
|
||||||
|
parser.add_argument("--enable-prefix-caching",
|
||||||
|
action='store_true',
|
||||||
|
help="Enable automatic prefix caching")
|
||||||
|
parser.add_argument('--use-v2-block-manager', action='store_true')
|
||||||
|
parser.add_argument(
|
||||||
|
"--ray-workers-use-nsight",
|
||||||
|
action='store_true',
|
||||||
|
help="If specified, use nsight to profile ray workers",
|
||||||
|
)
|
||||||
|
parser.add_argument('--download-dir',
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help='directory to download and load the weights, '
|
||||||
|
'default to the default cache dir of huggingface')
|
||||||
|
parser.add_argument(
|
||||||
|
'--output-json',
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help='Path to save the latency results in JSON format.')
|
||||||
|
parser.add_argument('--gpu-memory-utilization',
|
||||||
|
type=float,
|
||||||
|
default=0.9,
|
||||||
|
help='the fraction of GPU memory to be used for '
|
||||||
|
'the model executor, which can range from 0 to 1.'
|
||||||
|
'If unspecified, will use the default value of 0.9.')
|
||||||
|
parser.add_argument(
|
||||||
|
'--load-format',
|
||||||
|
type=str,
|
||||||
|
default=EngineArgs.load_format,
|
||||||
|
choices=[
|
||||||
|
'auto', 'pt', 'safetensors', 'npcache', 'dummy', 'tensorizer',
|
||||||
|
'bitsandbytes'
|
||||||
|
],
|
||||||
|
help='The format of the model weights to load.\n\n'
|
||||||
|
'* "auto" will try to load the weights in the safetensors format '
|
||||||
|
'and fall back to the pytorch bin format if safetensors format '
|
||||||
|
'is not available.\n'
|
||||||
|
'* "pt" will load the weights in the pytorch bin format.\n'
|
||||||
|
'* "safetensors" will load the weights in the safetensors format.\n'
|
||||||
|
'* "npcache" will load the weights in pytorch format and store '
|
||||||
|
'a numpy cache to speed up the loading.\n'
|
||||||
|
'* "dummy" will initialize the weights with random values, '
|
||||||
|
'which is mainly for profiling.\n'
|
||||||
|
'* "tensorizer" will load the weights using tensorizer from '
|
||||||
|
'CoreWeave. See the Tensorize vLLM Model script in the Examples'
|
||||||
|
'section for more information.\n'
|
||||||
|
'* "bitsandbytes" will load the weights using bitsandbytes '
|
||||||
|
'quantization.\n')
|
||||||
|
parser.add_argument(
|
||||||
|
'--distributed-executor-backend',
|
||||||
|
choices=['ray', 'mp'],
|
||||||
|
default=None,
|
||||||
|
help='Backend to use for distributed serving. When more than 1 GPU '
|
||||||
|
'is used, will be automatically set to "ray" if installed '
|
||||||
|
'or "mp" (multiprocessing) otherwise.')
|
||||||
|
parser.add_argument(
|
||||||
|
'--otlp-traces-endpoint',
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help='Target URL to which OpenTelemetry traces will be sent.')
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
main(args)
|
main(args)
|
||||||
|
|||||||
62
benchmarks/benchmark_prefix_caching.py
Normal file
62
benchmarks/benchmark_prefix_caching.py
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
import time
|
||||||
|
|
||||||
|
from vllm import LLM, SamplingParams
|
||||||
|
from vllm.utils import FlexibleArgumentParser
|
||||||
|
|
||||||
|
PROMPT = "You are a helpful assistant in recognizes the content of tables in markdown format. Here is a table as fellows. You need to answer my question about the table.\n# Table\n|Opening|Opening|Sl. No.|Film|Cast|Director|Music Director|Notes|\n|----|----|----|----|----|----|----|----|\n|J A N|9|1|Agni Pushpam|Jayabharathi, Kamalahasan|Jeassy|M. K. Arjunan||\n|J A N|16|2|Priyamvada|Mohan Sharma, Lakshmi, KPAC Lalitha|K. S. Sethumadhavan|V. Dakshinamoorthy||\n|J A N|23|3|Yakshagaanam|Madhu, Sheela|Sheela|M. S. Viswanathan||\n|J A N|30|4|Paalkkadal|Sheela, Sharada|T. K. Prasad|A. T. Ummer||\n|F E B|5|5|Amma|Madhu, Srividya|M. Krishnan Nair|M. K. Arjunan||\n|F E B|13|6|Appooppan|Thikkurissi Sukumaran Nair, Kamal Haasan|P. Bhaskaran|M. S. Baburaj||\n|F E B|20|7|Srishti|Chowalloor Krishnankutty, Ravi Alummoodu|K. T. Muhammad|M. S. Baburaj||\n|F E B|20|8|Vanadevatha|Prem Nazir, Madhubala|Yusufali Kechery|G. Devarajan||\n|F E B|27|9|Samasya|Madhu, Kamalahaasan|K. Thankappan|Shyam||\n|F E B|27|10|Yudhabhoomi|K. P. Ummer, Vidhubala|Crossbelt Mani|R. K. Shekhar||\n|M A R|5|11|Seemantha Puthran|Prem Nazir, Jayabharathi|A. B. Raj|M. K. Arjunan||\n|M A R|12|12|Swapnadanam|Rani Chandra, Dr. Mohandas|K. G. George|Bhaskar Chandavarkar||\n|M A R|19|13|Thulavarsham|Prem Nazir, sreedevi, Sudheer|N. Sankaran Nair|V. Dakshinamoorthy||\n|M A R|20|14|Aruthu|Kaviyoor Ponnamma, Kamalahasan|Ravi|G. Devarajan||\n|M A R|26|15|Swimming Pool|Kamal Haasan, M. G. Soman|J. Sasikumar|M. K. Arjunan||\n\n# Question\nWhat' s the content in the (1,1) cells\n" # noqa: E501
|
||||||
|
|
||||||
|
|
||||||
|
def test_prefix(llm=None, sampling_params=None, prompts=None):
|
||||||
|
start_time = time.time()
|
||||||
|
|
||||||
|
llm.generate(prompts, sampling_params=sampling_params)
|
||||||
|
|
||||||
|
end_time = time.time()
|
||||||
|
print(f"cost time {end_time - start_time}")
|
||||||
|
|
||||||
|
|
||||||
|
def main(args):
|
||||||
|
llm = LLM(model=args.model,
|
||||||
|
tokenizer_mode='auto',
|
||||||
|
trust_remote_code=True,
|
||||||
|
enforce_eager=True,
|
||||||
|
use_v2_block_manager=args.use_v2_block_manager,
|
||||||
|
tensor_parallel_size=args.tensor_parallel_size,
|
||||||
|
enable_prefix_caching=args.enable_prefix_caching)
|
||||||
|
|
||||||
|
num_prompts = 100
|
||||||
|
prompts = [PROMPT] * num_prompts
|
||||||
|
sampling_params = SamplingParams(temperature=0, max_tokens=args.output_len)
|
||||||
|
|
||||||
|
print("------warm up------")
|
||||||
|
test_prefix(
|
||||||
|
llm=llm,
|
||||||
|
prompts=prompts,
|
||||||
|
sampling_params=sampling_params,
|
||||||
|
)
|
||||||
|
|
||||||
|
print("------start generating------")
|
||||||
|
test_prefix(
|
||||||
|
llm=llm,
|
||||||
|
prompts=prompts,
|
||||||
|
sampling_params=sampling_params,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
parser = FlexibleArgumentParser(
|
||||||
|
description='Benchmark the performance with or without automatic '
|
||||||
|
'prefix caching.')
|
||||||
|
parser.add_argument('--model',
|
||||||
|
type=str,
|
||||||
|
default='baichuan-inc/Baichuan2-13B-Chat')
|
||||||
|
parser.add_argument('--tensor-parallel-size', '-tp', type=int, default=1)
|
||||||
|
parser.add_argument('--output-len', type=int, default=10)
|
||||||
|
parser.add_argument('--enable-prefix-caching',
|
||||||
|
action='store_true',
|
||||||
|
help='enable prefix caching')
|
||||||
|
parser.add_argument('--use-v2-block-manager',
|
||||||
|
action='store_true',
|
||||||
|
help='Use BlockSpaceMangerV2')
|
||||||
|
args = parser.parse_args()
|
||||||
|
main(args)
|
||||||
@ -1,8 +1,8 @@
|
|||||||
"""Benchmark online serving throughput.
|
"""Benchmark online serving throughput.
|
||||||
|
|
||||||
On the server side, run one of the following commands:
|
On the server side, run one of the following commands:
|
||||||
(vLLM backend)
|
vLLM OpenAI API server
|
||||||
python -m vllm.entrypoints.api_server \
|
python -m vllm.entrypoints.openai.api_server \
|
||||||
--model <your_model> --swap-space 16 \
|
--model <your_model> --swap-space 16 \
|
||||||
--disable-log-requests
|
--disable-log-requests
|
||||||
|
|
||||||
@ -12,28 +12,42 @@ On the server side, run one of the following commands:
|
|||||||
On the client side, run:
|
On the client side, run:
|
||||||
python benchmarks/benchmark_serving.py \
|
python benchmarks/benchmark_serving.py \
|
||||||
--backend <backend> \
|
--backend <backend> \
|
||||||
--tokenizer <your_model> --dataset <target_dataset> \
|
--model <your_model> \
|
||||||
--request-rate <request_rate>
|
--dataset-name sharegpt \
|
||||||
|
--dataset-path <path to dataset> \
|
||||||
|
--request-rate <request_rate> \ # By default <request_rate> is inf
|
||||||
|
--num-prompts <num_prompts> # By default <num_prompts> is 1000
|
||||||
|
|
||||||
|
when using tgi backend, add
|
||||||
|
--endpoint /generate_stream
|
||||||
|
to the end of the command above.
|
||||||
"""
|
"""
|
||||||
import argparse
|
import argparse
|
||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
|
import os
|
||||||
import random
|
import random
|
||||||
import time
|
import time
|
||||||
|
import warnings
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import AsyncGenerator, List, Tuple
|
from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
from backend_request_func import (ASYNC_REQUEST_FUNCS, RequestFuncInput,
|
||||||
|
RequestFuncOutput)
|
||||||
from tqdm.asyncio import tqdm
|
from tqdm.asyncio import tqdm
|
||||||
from transformers import PreTrainedTokenizerBase
|
from transformers import PreTrainedTokenizerBase
|
||||||
from vllm.transformers_utils.tokenizer import get_tokenizer
|
|
||||||
|
|
||||||
from backend_request_func import (
|
try:
|
||||||
ASYNC_REQUEST_FUNCS,
|
from vllm.transformers_utils.tokenizer import get_tokenizer
|
||||||
RequestFuncInput,
|
except ImportError:
|
||||||
RequestFuncOutput,
|
from backend_request_func import get_tokenizer
|
||||||
)
|
|
||||||
|
try:
|
||||||
|
from vllm.utils import FlexibleArgumentParser
|
||||||
|
except ImportError:
|
||||||
|
from argparse import ArgumentParser as FlexibleArgumentParser
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@ -50,13 +64,20 @@ class BenchmarkMetrics:
|
|||||||
mean_tpot_ms: float
|
mean_tpot_ms: float
|
||||||
median_tpot_ms: float
|
median_tpot_ms: float
|
||||||
p99_tpot_ms: float
|
p99_tpot_ms: float
|
||||||
|
mean_itl_ms: float
|
||||||
|
median_itl_ms: float
|
||||||
|
p99_itl_ms: float
|
||||||
|
|
||||||
|
|
||||||
def sample_requests(
|
def sample_sharegpt_requests(
|
||||||
dataset_path: str,
|
dataset_path: str,
|
||||||
num_requests: int,
|
num_requests: int,
|
||||||
tokenizer: PreTrainedTokenizerBase,
|
tokenizer: PreTrainedTokenizerBase,
|
||||||
|
fixed_output_len: Optional[int] = None,
|
||||||
) -> List[Tuple[str, int, int]]:
|
) -> List[Tuple[str, int, int]]:
|
||||||
|
if fixed_output_len is not None and fixed_output_len < 4:
|
||||||
|
raise ValueError("output_len too small")
|
||||||
|
|
||||||
# Load the dataset.
|
# Load the dataset.
|
||||||
with open(dataset_path) as f:
|
with open(dataset_path) as f:
|
||||||
dataset = json.load(f)
|
dataset = json.load(f)
|
||||||
@ -66,37 +87,101 @@ def sample_requests(
|
|||||||
dataset = [(data["conversations"][0]["value"],
|
dataset = [(data["conversations"][0]["value"],
|
||||||
data["conversations"][1]["value"]) for data in dataset]
|
data["conversations"][1]["value"]) for data in dataset]
|
||||||
|
|
||||||
# some of these will be filtered out, so sample more than we need
|
# Shuffle the dataset.
|
||||||
sampled_indices = random.sample(range(len(dataset)),
|
random.shuffle(dataset)
|
||||||
int(num_requests * 1.2))
|
|
||||||
dataset = [dataset[i] for i in sampled_indices]
|
|
||||||
|
|
||||||
# Tokenize the prompts and completions.
|
# Filter out sequences that are too long or too short
|
||||||
prompts = [prompt for prompt, _ in dataset]
|
|
||||||
prompt_token_ids = tokenizer(prompts).input_ids
|
|
||||||
completions = [completion for _, completion in dataset]
|
|
||||||
completion_token_ids = tokenizer(completions).input_ids
|
|
||||||
tokenized_dataset = []
|
|
||||||
for i in range(len(dataset)):
|
|
||||||
output_len = len(completion_token_ids[i])
|
|
||||||
tokenized_dataset.append((prompts[i], prompt_token_ids[i], output_len))
|
|
||||||
|
|
||||||
# Filter out too long sequences.
|
|
||||||
filtered_dataset: List[Tuple[str, int, int]] = []
|
filtered_dataset: List[Tuple[str, int, int]] = []
|
||||||
for prompt, prompt_token_ids, output_len in tokenized_dataset:
|
for i in range(len(dataset)):
|
||||||
|
if len(filtered_dataset) == num_requests:
|
||||||
|
break
|
||||||
|
|
||||||
|
# Tokenize the prompts and completions.
|
||||||
|
prompt = dataset[i][0]
|
||||||
|
prompt_token_ids = tokenizer(prompt).input_ids
|
||||||
|
completion = dataset[i][1]
|
||||||
|
completion_token_ids = tokenizer(completion).input_ids
|
||||||
prompt_len = len(prompt_token_ids)
|
prompt_len = len(prompt_token_ids)
|
||||||
|
output_len = len(completion_token_ids
|
||||||
|
) if fixed_output_len is None else fixed_output_len
|
||||||
if prompt_len < 4 or output_len < 4:
|
if prompt_len < 4 or output_len < 4:
|
||||||
# Prune too short sequences.
|
# Prune too short sequences.
|
||||||
# This is because TGI causes errors when the input or output length
|
|
||||||
# is too short.
|
|
||||||
continue
|
continue
|
||||||
if prompt_len > 1024 or prompt_len + output_len > 2048:
|
if prompt_len > 1024 or prompt_len + output_len > 2048:
|
||||||
# Prune too long sequences.
|
# Prune too long sequences.
|
||||||
continue
|
continue
|
||||||
filtered_dataset.append((prompt, prompt_len, output_len))
|
filtered_dataset.append((prompt, prompt_len, output_len))
|
||||||
|
|
||||||
# Sample the requests.
|
return filtered_dataset
|
||||||
sampled_requests = random.sample(filtered_dataset, num_requests)
|
|
||||||
|
|
||||||
|
def sample_sonnet_requests(
|
||||||
|
dataset_path: str,
|
||||||
|
num_requests: int,
|
||||||
|
input_len: int,
|
||||||
|
output_len: int,
|
||||||
|
prefix_len: int,
|
||||||
|
tokenizer: PreTrainedTokenizerBase,
|
||||||
|
) -> List[Tuple[str, str, int, int]]:
|
||||||
|
assert (
|
||||||
|
input_len > prefix_len
|
||||||
|
), "'args.sonnet-input-len' must be greater than 'args.prefix-input-len'."
|
||||||
|
|
||||||
|
# Load the dataset.
|
||||||
|
with open(dataset_path) as f:
|
||||||
|
poem_lines = f.readlines()
|
||||||
|
|
||||||
|
# Tokenize the poem lines.
|
||||||
|
poem_token_ids = tokenizer(poem_lines).input_ids
|
||||||
|
average_poem_len = sum(
|
||||||
|
len(token_ids) for token_ids in poem_token_ids) / len(poem_token_ids)
|
||||||
|
|
||||||
|
# Base prefix for all requests.
|
||||||
|
base_prompt = "Pick as many lines as you can from these poem lines:\n"
|
||||||
|
base_message = [{
|
||||||
|
"role": "user",
|
||||||
|
"content": base_prompt,
|
||||||
|
}]
|
||||||
|
base_prompt_formatted = tokenizer.apply_chat_template(
|
||||||
|
base_message, add_generation_prompt=True, tokenize=False)
|
||||||
|
base_prompt_offset = len(tokenizer(base_prompt_formatted).input_ids)
|
||||||
|
|
||||||
|
assert (
|
||||||
|
input_len > base_prompt_offset
|
||||||
|
), f"Please set 'args.sonnet-input-len' higher than {base_prompt_offset}."
|
||||||
|
num_input_lines = round(
|
||||||
|
(input_len - base_prompt_offset) / average_poem_len)
|
||||||
|
|
||||||
|
# First approximately `prefix_len` number of tokens in the
|
||||||
|
# prompt are fixed poem lines.
|
||||||
|
assert (
|
||||||
|
prefix_len > base_prompt_offset
|
||||||
|
), f"Please set 'args.sonnet-prefix-len' higher than {base_prompt_offset}."
|
||||||
|
|
||||||
|
num_prefix_lines = round(
|
||||||
|
(prefix_len - base_prompt_offset) / average_poem_len)
|
||||||
|
prefix_lines = poem_lines[:num_prefix_lines]
|
||||||
|
|
||||||
|
# Sample the rest of lines per request.
|
||||||
|
sampled_requests: List[Tuple[str, int, int]] = []
|
||||||
|
for _ in range(num_requests):
|
||||||
|
sampled_lines = "".join(
|
||||||
|
prefix_lines +
|
||||||
|
random.sample(poem_lines, num_input_lines - num_prefix_lines))
|
||||||
|
|
||||||
|
prompt = f"{base_prompt}{sampled_lines}"
|
||||||
|
message = [
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": prompt,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
prompt_formatted = tokenizer.apply_chat_template(
|
||||||
|
message, add_generation_prompt=True, tokenize=False)
|
||||||
|
prompt_len = len(tokenizer(prompt_formatted).input_ids)
|
||||||
|
sampled_requests.append(
|
||||||
|
(prompt, prompt_formatted, prompt_len, output_len))
|
||||||
|
|
||||||
return sampled_requests
|
return sampled_requests
|
||||||
|
|
||||||
|
|
||||||
@ -122,37 +207,58 @@ def calculate_metrics(
|
|||||||
outputs: List[RequestFuncOutput],
|
outputs: List[RequestFuncOutput],
|
||||||
dur_s: float,
|
dur_s: float,
|
||||||
tokenizer: PreTrainedTokenizerBase,
|
tokenizer: PreTrainedTokenizerBase,
|
||||||
) -> BenchmarkMetrics:
|
) -> Tuple[BenchmarkMetrics, List[int]]:
|
||||||
total_output = 0
|
actual_output_lens: List[int] = []
|
||||||
total_input = 0
|
total_input = 0
|
||||||
completed = 0
|
completed = 0
|
||||||
per_token_latencies = []
|
itls: List[float] = []
|
||||||
ttfts = []
|
tpots: List[float] = []
|
||||||
|
ttfts: List[float] = []
|
||||||
for i in range(len(outputs)):
|
for i in range(len(outputs)):
|
||||||
if outputs[i].success:
|
if outputs[i].success:
|
||||||
output_len = len(tokenizer.encode(outputs[i].generated_text))
|
# We use the tokenizer to count the number of output tokens for all
|
||||||
total_output += output_len
|
# serving backends instead of looking at len(outputs[i].itl) since
|
||||||
|
# multiple output tokens may be bundled together
|
||||||
|
# Note: this may inflate the output token count slightly
|
||||||
|
output_len = len(
|
||||||
|
tokenizer(outputs[i].generated_text,
|
||||||
|
add_special_tokens=False).input_ids)
|
||||||
|
actual_output_lens.append(output_len)
|
||||||
total_input += input_requests[i][1]
|
total_input += input_requests[i][1]
|
||||||
per_token_latencies.append(outputs[i].latency / output_len)
|
if output_len > 1:
|
||||||
|
tpots.append(
|
||||||
|
(outputs[i].latency - outputs[i].ttft) / (output_len - 1))
|
||||||
|
itls += outputs[i].itl
|
||||||
ttfts.append(outputs[i].ttft)
|
ttfts.append(outputs[i].ttft)
|
||||||
completed += 1
|
completed += 1
|
||||||
|
else:
|
||||||
|
actual_output_lens.append(0)
|
||||||
|
|
||||||
|
if completed == 0:
|
||||||
|
warnings.warn(
|
||||||
|
"All requests failed. This is likely due to a misconfiguration "
|
||||||
|
"on the benchmark arguments.",
|
||||||
|
stacklevel=2)
|
||||||
metrics = BenchmarkMetrics(
|
metrics = BenchmarkMetrics(
|
||||||
completed=completed,
|
completed=completed,
|
||||||
total_input=total_input,
|
total_input=total_input,
|
||||||
total_output=total_output,
|
total_output=sum(actual_output_lens),
|
||||||
request_throughput=completed / dur_s,
|
request_throughput=completed / dur_s,
|
||||||
input_throughput=total_input / dur_s,
|
input_throughput=total_input / dur_s,
|
||||||
output_throughput=total_output / dur_s,
|
output_throughput=sum(actual_output_lens) / dur_s,
|
||||||
mean_ttft_ms=np.mean(ttfts) * 1000,
|
mean_ttft_ms=np.mean(ttfts or 0) *
|
||||||
median_ttft_ms=np.median(ttfts) * 1000,
|
1000, # ttfts is empty if streaming is not supported by backend
|
||||||
p99_ttft_ms=np.percentile(ttfts, 99) * 1000,
|
median_ttft_ms=np.median(ttfts or 0) * 1000,
|
||||||
mean_tpot_ms=np.mean(per_token_latencies) * 1000,
|
p99_ttft_ms=np.percentile(ttfts or 0, 99) * 1000,
|
||||||
median_tpot_ms=np.median(per_token_latencies) * 1000,
|
mean_tpot_ms=np.mean(tpots or 0) * 1000,
|
||||||
p99_tpot_ms=np.percentile(per_token_latencies, 99) * 1000,
|
median_tpot_ms=np.median(tpots or 0) * 1000,
|
||||||
|
p99_tpot_ms=np.percentile(tpots or 0, 99) * 1000,
|
||||||
|
mean_itl_ms=np.mean(itls or 0) * 1000,
|
||||||
|
median_itl_ms=np.median(itls or 0) * 1000,
|
||||||
|
p99_itl_ms=np.percentile(itls or 0, 99) * 1000,
|
||||||
)
|
)
|
||||||
|
|
||||||
return metrics
|
return metrics, actual_output_lens
|
||||||
|
|
||||||
|
|
||||||
async def benchmark(
|
async def benchmark(
|
||||||
@ -167,16 +273,34 @@ async def benchmark(
|
|||||||
disable_tqdm: bool,
|
disable_tqdm: bool,
|
||||||
):
|
):
|
||||||
if backend in ASYNC_REQUEST_FUNCS:
|
if backend in ASYNC_REQUEST_FUNCS:
|
||||||
request_func = ASYNC_REQUEST_FUNCS.get(backend)
|
request_func = ASYNC_REQUEST_FUNCS[backend]
|
||||||
else:
|
else:
|
||||||
raise ValueError(f"Unknown backend: {backend}")
|
raise ValueError(f"Unknown backend: {backend}")
|
||||||
|
|
||||||
pbar = None if disable_tqdm else tqdm(total=len(input_requests))
|
print("Starting initial single prompt test run...")
|
||||||
|
test_prompt, test_prompt_len, test_output_len = input_requests[0]
|
||||||
|
test_input = RequestFuncInput(
|
||||||
|
model=model_id,
|
||||||
|
prompt=test_prompt,
|
||||||
|
api_url=api_url,
|
||||||
|
prompt_len=test_prompt_len,
|
||||||
|
output_len=test_output_len,
|
||||||
|
best_of=best_of,
|
||||||
|
use_beam_search=use_beam_search,
|
||||||
|
)
|
||||||
|
test_output = await request_func(request_func_input=test_input)
|
||||||
|
if not test_output.success:
|
||||||
|
raise ValueError(
|
||||||
|
"Initial test run failed - Please make sure benchmark arguments "
|
||||||
|
f"are correctly specified. Error: {test_output.error}")
|
||||||
|
else:
|
||||||
|
print("Initial test run completed. Starting main benchmark run...")
|
||||||
print(f"Traffic request rate: {request_rate}")
|
print(f"Traffic request rate: {request_rate}")
|
||||||
|
|
||||||
|
pbar = None if disable_tqdm else tqdm(total=len(input_requests))
|
||||||
|
|
||||||
benchmark_start_time = time.perf_counter()
|
benchmark_start_time = time.perf_counter()
|
||||||
tasks = []
|
tasks: List[asyncio.Task] = []
|
||||||
async for request in get_request(input_requests, request_rate):
|
async for request in get_request(input_requests, request_rate):
|
||||||
prompt, prompt_len, output_len = request
|
prompt, prompt_len, output_len = request
|
||||||
request_func_input = RequestFuncInput(
|
request_func_input = RequestFuncInput(
|
||||||
@ -192,40 +316,57 @@ async def benchmark(
|
|||||||
asyncio.create_task(
|
asyncio.create_task(
|
||||||
request_func(request_func_input=request_func_input,
|
request_func(request_func_input=request_func_input,
|
||||||
pbar=pbar)))
|
pbar=pbar)))
|
||||||
outputs = await asyncio.gather(*tasks)
|
outputs: List[RequestFuncOutput] = await asyncio.gather(*tasks)
|
||||||
|
|
||||||
if not disable_tqdm:
|
if pbar is not None:
|
||||||
pbar.close()
|
pbar.close()
|
||||||
|
|
||||||
benchmark_duration = time.perf_counter() - benchmark_start_time
|
benchmark_duration = time.perf_counter() - benchmark_start_time
|
||||||
|
|
||||||
metrics = calculate_metrics(
|
metrics, actual_output_lens = calculate_metrics(
|
||||||
input_requests=input_requests,
|
input_requests=input_requests,
|
||||||
outputs=outputs,
|
outputs=outputs,
|
||||||
dur_s=benchmark_duration,
|
dur_s=benchmark_duration,
|
||||||
tokenizer=tokenizer,
|
tokenizer=tokenizer,
|
||||||
)
|
)
|
||||||
|
|
||||||
print(f"Successful requests: {metrics.completed}")
|
print("{s:{c}^{n}}".format(s=' Serving Benchmark Result ', n=50, c='='))
|
||||||
print(f"Benchmark duration: {benchmark_duration:2f} s")
|
print("{:<40} {:<10}".format("Successful requests:", metrics.completed))
|
||||||
print(f"Total input tokens: {metrics.total_input}")
|
print("{:<40} {:<10.2f}".format("Benchmark duration (s):",
|
||||||
print(f"Total generated tokens: {metrics.total_output}")
|
benchmark_duration))
|
||||||
print(f"Request throughput: {metrics.request_throughput:.2f} requests/s")
|
print("{:<40} {:<10}".format("Total input tokens:", metrics.total_input))
|
||||||
print(f"Input token throughput: {metrics.input_throughput:.2f} tokens/s")
|
print("{:<40} {:<10}".format("Total generated tokens:",
|
||||||
print(f"Output token throughput: {metrics.output_throughput:.2f} tokens/s")
|
metrics.total_output))
|
||||||
print(f"Mean TTFT: {metrics.mean_ttft_ms:.2f} ms")
|
print("{:<40} {:<10.2f}".format("Request throughput (req/s):",
|
||||||
print(f"Median TTFT: {metrics.median_ttft_ms:.2f} ms")
|
metrics.request_throughput))
|
||||||
print(f"P99 TTFT: {metrics.p99_ttft_ms:.2f} ms")
|
print("{:<40} {:<10.2f}".format("Input token throughput (tok/s):",
|
||||||
print(f"Mean TPOT: {metrics.mean_tpot_ms:.2f} ms")
|
metrics.input_throughput))
|
||||||
print(f"Median TPOT: {metrics.median_tpot_ms:.2f} ms")
|
print("{:<40} {:<10.2f}".format("Output token throughput (tok/s):",
|
||||||
print(f"P99 TPOT: {metrics.p99_tpot_ms:.2f} ms")
|
metrics.output_throughput))
|
||||||
|
print("{s:{c}^{n}}".format(s='Time to First Token', n=50, c='-'))
|
||||||
|
print("{:<40} {:<10.2f}".format("Mean TTFT (ms):", metrics.mean_ttft_ms))
|
||||||
|
print("{:<40} {:<10.2f}".format("Median TTFT (ms):",
|
||||||
|
metrics.median_ttft_ms))
|
||||||
|
print("{:<40} {:<10.2f}".format("P99 TTFT (ms):", metrics.p99_ttft_ms))
|
||||||
|
print("{s:{c}^{n}}".format(s='Time per Output Token (excl. 1st token)',
|
||||||
|
n=50,
|
||||||
|
c='-'))
|
||||||
|
print("{:<40} {:<10.2f}".format("Mean TPOT (ms):", metrics.mean_tpot_ms))
|
||||||
|
print("{:<40} {:<10.2f}".format("Median TPOT (ms):",
|
||||||
|
metrics.median_tpot_ms))
|
||||||
|
print("{:<40} {:<10.2f}".format("P99 TPOT (ms):", metrics.p99_tpot_ms))
|
||||||
|
print("{s:{c}^{n}}".format(s='Inter-token Latency', n=50, c='-'))
|
||||||
|
print("{:<40} {:<10.2f}".format("Mean ITL (ms):", metrics.mean_itl_ms))
|
||||||
|
print("{:<40} {:<10.2f}".format("Median ITL (ms):", metrics.median_itl_ms))
|
||||||
|
print("{:<40} {:<10.2f}".format("P99 ITL (ms):", metrics.p99_itl_ms))
|
||||||
|
print("=" * 50)
|
||||||
|
|
||||||
result = {
|
result = {
|
||||||
"duration": benchmark_duration,
|
"duration": benchmark_duration,
|
||||||
"completed": metrics.completed,
|
"completed": metrics.completed,
|
||||||
"total_input_tokens": metrics.total_input,
|
"total_input_tokens": metrics.total_input,
|
||||||
"total_output_tokens": metrics.total_output,
|
"total_output_tokens": metrics.total_output,
|
||||||
"request_inthroughput": metrics.request_throughput,
|
"request_throughput": metrics.request_throughput,
|
||||||
"input_throughput": metrics.input_throughput,
|
"input_throughput": metrics.input_throughput,
|
||||||
"output_throughput": metrics.output_throughput,
|
"output_throughput": metrics.output_throughput,
|
||||||
"mean_ttft_ms": metrics.mean_ttft_ms,
|
"mean_ttft_ms": metrics.mean_ttft_ms,
|
||||||
@ -233,7 +374,16 @@ async def benchmark(
|
|||||||
"p99_ttft_ms": metrics.p99_ttft_ms,
|
"p99_ttft_ms": metrics.p99_ttft_ms,
|
||||||
"mean_tpot_ms": metrics.mean_tpot_ms,
|
"mean_tpot_ms": metrics.mean_tpot_ms,
|
||||||
"median_tpot_ms": metrics.median_tpot_ms,
|
"median_tpot_ms": metrics.median_tpot_ms,
|
||||||
"p99_tpot_ms": metrics.p99_tpot_ms
|
"p99_tpot_ms": metrics.p99_tpot_ms,
|
||||||
|
"mean_itl_ms": metrics.mean_itl_ms,
|
||||||
|
"median_itl_ms": metrics.median_itl_ms,
|
||||||
|
"p99_itl_ms": metrics.p99_itl_ms,
|
||||||
|
"input_lens": [output.prompt_len for output in outputs],
|
||||||
|
"output_lens": actual_output_lens,
|
||||||
|
"ttfts": [output.ttft for output in outputs],
|
||||||
|
"itls": [output.itl for output in outputs],
|
||||||
|
"generated_texts": [output.generated_text for output in outputs],
|
||||||
|
"errors": [output.error for output in outputs],
|
||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
|
|
||||||
@ -254,7 +404,60 @@ def main(args: argparse.Namespace):
|
|||||||
|
|
||||||
tokenizer = get_tokenizer(tokenizer_id,
|
tokenizer = get_tokenizer(tokenizer_id,
|
||||||
trust_remote_code=args.trust_remote_code)
|
trust_remote_code=args.trust_remote_code)
|
||||||
input_requests = sample_requests(args.dataset, args.num_prompts, tokenizer)
|
|
||||||
|
if args.dataset is not None:
|
||||||
|
warnings.warn(
|
||||||
|
"The '--dataset' argument will be deprecated in the next "
|
||||||
|
"release. Please use '--dataset-name' and "
|
||||||
|
"'--dataset-path' in the future runs.",
|
||||||
|
stacklevel=2)
|
||||||
|
input_requests = sample_sharegpt_requests(
|
||||||
|
dataset_path=args.dataset,
|
||||||
|
num_requests=args.num_prompts,
|
||||||
|
tokenizer=tokenizer,
|
||||||
|
fixed_output_len=args.sharegpt_output_len,
|
||||||
|
)
|
||||||
|
|
||||||
|
elif args.dataset_name == "sharegpt":
|
||||||
|
input_requests = sample_sharegpt_requests(
|
||||||
|
dataset_path=args.dataset_path,
|
||||||
|
num_requests=args.num_prompts,
|
||||||
|
tokenizer=tokenizer,
|
||||||
|
fixed_output_len=args.sharegpt_output_len,
|
||||||
|
)
|
||||||
|
|
||||||
|
elif args.dataset_name == "sonnet":
|
||||||
|
# Do not format the prompt, pass to message directly
|
||||||
|
if args.backend == "openai-chat":
|
||||||
|
input_requests = sample_sonnet_requests(
|
||||||
|
dataset_path=args.dataset_path,
|
||||||
|
num_requests=args.num_prompts,
|
||||||
|
input_len=args.sonnet_input_len,
|
||||||
|
output_len=args.sonnet_output_len,
|
||||||
|
prefix_len=args.sonnet_prefix_len,
|
||||||
|
tokenizer=tokenizer,
|
||||||
|
)
|
||||||
|
input_requests = [(prompt, prompt_len, output_len)
|
||||||
|
for prompt, prompt_formatted, prompt_len,
|
||||||
|
output_len in input_requests]
|
||||||
|
else:
|
||||||
|
assert (
|
||||||
|
tokenizer.chat_template or tokenizer.default_chat_template
|
||||||
|
), "Tokenizer/model must have chat template for sonnet dataset."
|
||||||
|
input_requests = sample_sonnet_requests(
|
||||||
|
dataset_path=args.dataset_path,
|
||||||
|
num_requests=args.num_prompts,
|
||||||
|
input_len=args.sonnet_input_len,
|
||||||
|
output_len=args.sonnet_output_len,
|
||||||
|
prefix_len=args.sonnet_prefix_len,
|
||||||
|
tokenizer=tokenizer,
|
||||||
|
)
|
||||||
|
input_requests = [(prompt_formatted, prompt_len, output_len)
|
||||||
|
for prompt, prompt_formatted, prompt_len,
|
||||||
|
output_len in input_requests]
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Unknown dataset: {args.dataset_name}")
|
||||||
|
|
||||||
benchmark_result = asyncio.run(
|
benchmark_result = asyncio.run(
|
||||||
benchmark(
|
benchmark(
|
||||||
@ -271,19 +474,29 @@ def main(args: argparse.Namespace):
|
|||||||
|
|
||||||
# Save config and results to json
|
# Save config and results to json
|
||||||
if args.save_result:
|
if args.save_result:
|
||||||
result_json = {}
|
result_json: Dict[str, Any] = {}
|
||||||
|
|
||||||
# Setup
|
# Setup
|
||||||
current_dt = datetime.now().strftime("%Y%m%d-%H%M%S")
|
current_dt = datetime.now().strftime("%Y%m%d-%H%M%S")
|
||||||
result_json["date"] = current_dt
|
result_json["date"] = current_dt
|
||||||
result_json["backend"] = backend
|
result_json["backend"] = backend
|
||||||
result_json["version"] = args.version
|
|
||||||
result_json["model_id"] = model_id
|
result_json["model_id"] = model_id
|
||||||
result_json["tokenizer_id"] = tokenizer_id
|
result_json["tokenizer_id"] = tokenizer_id
|
||||||
result_json["best_of"] = args.best_of
|
result_json["best_of"] = args.best_of
|
||||||
result_json["use_beam_search"] = args.use_beam_search
|
result_json["use_beam_search"] = args.use_beam_search
|
||||||
result_json["num_prompts"] = args.num_prompts
|
result_json["num_prompts"] = args.num_prompts
|
||||||
|
|
||||||
|
# Metadata
|
||||||
|
if args.metadata:
|
||||||
|
for item in args.metadata:
|
||||||
|
if "=" in item:
|
||||||
|
kvstring = item.split("=")
|
||||||
|
result_json[kvstring[0].strip()] = kvstring[1].strip()
|
||||||
|
else:
|
||||||
|
raise ValueError(
|
||||||
|
"Invalid metadata format. Please use KEY=VALUE format."
|
||||||
|
)
|
||||||
|
|
||||||
# Traffic
|
# Traffic
|
||||||
result_json["request_rate"] = (
|
result_json["request_rate"] = (
|
||||||
args.request_rate if args.request_rate < float("inf") else "inf")
|
args.request_rate if args.request_rate < float("inf") else "inf")
|
||||||
@ -293,13 +506,17 @@ def main(args: argparse.Namespace):
|
|||||||
|
|
||||||
# Save to file
|
# Save to file
|
||||||
base_model_id = model_id.split("/")[-1]
|
base_model_id = model_id.split("/")[-1]
|
||||||
file_name = f"{backend}-{args.request_rate}qps-{base_model_id}-{current_dt}.json"
|
file_name = f"{backend}-{args.request_rate}qps-{base_model_id}-{current_dt}.json" #noqa
|
||||||
|
if args.result_filename:
|
||||||
|
file_name = args.result_filename
|
||||||
|
if args.result_dir:
|
||||||
|
file_name = os.path.join(args.result_dir, file_name)
|
||||||
with open(file_name, "w") as outfile:
|
with open(file_name, "w") as outfile:
|
||||||
json.dump(result_json, outfile)
|
json.dump(result_json, outfile)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
parser = argparse.ArgumentParser(
|
parser = FlexibleArgumentParser(
|
||||||
description="Benchmark the online serving throughput.")
|
description="Benchmark the online serving throughput.")
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--backend",
|
"--backend",
|
||||||
@ -307,12 +524,6 @@ if __name__ == "__main__":
|
|||||||
default="vllm",
|
default="vllm",
|
||||||
choices=list(ASYNC_REQUEST_FUNCS.keys()),
|
choices=list(ASYNC_REQUEST_FUNCS.keys()),
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
|
||||||
"--version",
|
|
||||||
type=str,
|
|
||||||
default="N/A",
|
|
||||||
help="Version of the serving backend/engine.",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--base-url",
|
"--base-url",
|
||||||
type=str,
|
type=str,
|
||||||
@ -324,12 +535,26 @@ if __name__ == "__main__":
|
|||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--endpoint",
|
"--endpoint",
|
||||||
type=str,
|
type=str,
|
||||||
default="/generate",
|
default="/v1/completions",
|
||||||
help="API endpoint.",
|
help="API endpoint.",
|
||||||
)
|
)
|
||||||
parser.add_argument("--dataset",
|
parser.add_argument(
|
||||||
|
"--dataset",
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help="Path to the ShareGPT dataset, will be deprecated in the "
|
||||||
|
"next release.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--dataset-name",
|
||||||
|
type=str,
|
||||||
|
default="sharegpt",
|
||||||
|
choices=["sharegpt", "sonnet"],
|
||||||
|
help="Name of the dataset to benchmark on.",
|
||||||
|
)
|
||||||
|
parser.add_argument("--dataset-path",
|
||||||
type=str,
|
type=str,
|
||||||
required=True,
|
default=None,
|
||||||
help="Path to the dataset.")
|
help="Path to the dataset.")
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--model",
|
"--model",
|
||||||
@ -341,7 +566,7 @@ if __name__ == "__main__":
|
|||||||
"--tokenizer",
|
"--tokenizer",
|
||||||
type=str,
|
type=str,
|
||||||
help=
|
help=
|
||||||
"Name or path of the tokenizer, if not using the default model tokenizer.",
|
"Name or path of the tokenizer, if not using the default tokenizer.",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--best-of",
|
"--best-of",
|
||||||
@ -357,6 +582,33 @@ if __name__ == "__main__":
|
|||||||
default=1000,
|
default=1000,
|
||||||
help="Number of prompts to process.",
|
help="Number of prompts to process.",
|
||||||
)
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--sharegpt-output-len",
|
||||||
|
type=int,
|
||||||
|
default=None,
|
||||||
|
help="Output length for each request. Overrides the output length "
|
||||||
|
"from the ShareGPT dataset.")
|
||||||
|
parser.add_argument(
|
||||||
|
"--sonnet-input-len",
|
||||||
|
type=int,
|
||||||
|
default=550,
|
||||||
|
help=
|
||||||
|
"Number of input tokens per request, used only for sonnet dataset.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--sonnet-output-len",
|
||||||
|
type=int,
|
||||||
|
default=150,
|
||||||
|
help=
|
||||||
|
"Number of output tokens per request, used only for sonnet dataset.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--sonnet-prefix-len",
|
||||||
|
type=int,
|
||||||
|
default=200,
|
||||||
|
help=
|
||||||
|
"Number of prefix tokens per request, used only for sonnet dataset.",
|
||||||
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--request-rate",
|
"--request-rate",
|
||||||
type=float,
|
type=float,
|
||||||
@ -382,6 +634,30 @@ if __name__ == "__main__":
|
|||||||
action="store_true",
|
action="store_true",
|
||||||
help="Specify to save benchmark results to a json file",
|
help="Specify to save benchmark results to a json file",
|
||||||
)
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--metadata",
|
||||||
|
metavar="KEY=VALUE",
|
||||||
|
nargs="*",
|
||||||
|
help="Key-value pairs (e.g, --metadata version=0.3.3 tp=1) "
|
||||||
|
"for metadata of this run to be saved in the result JSON file "
|
||||||
|
"for record keeping purposes.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--result-dir",
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help="Specify directory to save benchmark json results."
|
||||||
|
"If not specified, results are saved in the current directory.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--result-filename",
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help="Specify the filename to save benchmark json results."
|
||||||
|
"If not specified, results will be saved in "
|
||||||
|
"{backend}-{args.request_rate}qps-{base_model_id}-{current_dt}.json"
|
||||||
|
" format.",
|
||||||
|
)
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
main(args)
|
main(args)
|
||||||
|
|||||||
@ -6,9 +6,13 @@ import time
|
|||||||
from typing import List, Optional, Tuple
|
from typing import List, Optional, Tuple
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
|
from tqdm import tqdm
|
||||||
from transformers import (AutoModelForCausalLM, AutoTokenizer,
|
from transformers import (AutoModelForCausalLM, AutoTokenizer,
|
||||||
PreTrainedTokenizerBase)
|
PreTrainedTokenizerBase)
|
||||||
from tqdm import tqdm
|
|
||||||
|
from vllm.engine.arg_utils import EngineArgs
|
||||||
|
from vllm.model_executor.layers.quantization import QUANTIZATION_METHODS
|
||||||
|
from vllm.utils import FlexibleArgumentParser
|
||||||
|
|
||||||
|
|
||||||
def sample_requests(
|
def sample_requests(
|
||||||
@ -29,22 +33,23 @@ def sample_requests(
|
|||||||
dataset = [(data["conversations"][0]["value"],
|
dataset = [(data["conversations"][0]["value"],
|
||||||
data["conversations"][1]["value"]) for data in dataset]
|
data["conversations"][1]["value"]) for data in dataset]
|
||||||
|
|
||||||
# Tokenize the prompts and completions.
|
# Shuffle the dataset.
|
||||||
prompts = [prompt for prompt, _ in dataset]
|
random.shuffle(dataset)
|
||||||
prompt_token_ids = tokenizer(prompts).input_ids
|
|
||||||
completions = [completion for _, completion in dataset]
|
|
||||||
completion_token_ids = tokenizer(completions).input_ids
|
|
||||||
tokenized_dataset = []
|
|
||||||
for i in range(len(dataset)):
|
|
||||||
output_len = len(completion_token_ids[i])
|
|
||||||
if fixed_output_len is not None:
|
|
||||||
output_len = fixed_output_len
|
|
||||||
tokenized_dataset.append((prompts[i], prompt_token_ids[i], output_len))
|
|
||||||
|
|
||||||
# Filter out too long sequences.
|
# Filter out sequences that are too long or too short
|
||||||
filtered_dataset: List[Tuple[str, int, int]] = []
|
filtered_dataset: List[Tuple[str, int, int]] = []
|
||||||
for prompt, prompt_token_ids, output_len in tokenized_dataset:
|
for i in range(len(dataset)):
|
||||||
|
if len(filtered_dataset) == num_requests:
|
||||||
|
break
|
||||||
|
|
||||||
|
# Tokenize the prompts and completions.
|
||||||
|
prompt = dataset[i][0]
|
||||||
|
prompt_token_ids = tokenizer(prompt).input_ids
|
||||||
|
completion = dataset[i][1]
|
||||||
|
completion_token_ids = tokenizer(completion).input_ids
|
||||||
prompt_len = len(prompt_token_ids)
|
prompt_len = len(prompt_token_ids)
|
||||||
|
output_len = len(completion_token_ids
|
||||||
|
) if fixed_output_len is None else fixed_output_len
|
||||||
if prompt_len < 4 or output_len < 4:
|
if prompt_len < 4 or output_len < 4:
|
||||||
# Prune too short sequences.
|
# Prune too short sequences.
|
||||||
continue
|
continue
|
||||||
@ -53,9 +58,7 @@ def sample_requests(
|
|||||||
continue
|
continue
|
||||||
filtered_dataset.append((prompt, prompt_len, output_len))
|
filtered_dataset.append((prompt, prompt_len, output_len))
|
||||||
|
|
||||||
# Sample the requests.
|
return filtered_dataset
|
||||||
sampled_requests = random.sample(filtered_dataset, num_requests)
|
|
||||||
return sampled_requests
|
|
||||||
|
|
||||||
|
|
||||||
def run_vllm(
|
def run_vllm(
|
||||||
@ -72,7 +75,15 @@ def run_vllm(
|
|||||||
max_model_len: Optional[int],
|
max_model_len: Optional[int],
|
||||||
enforce_eager: bool,
|
enforce_eager: bool,
|
||||||
kv_cache_dtype: str,
|
kv_cache_dtype: str,
|
||||||
|
quantization_param_path: Optional[str],
|
||||||
device: str,
|
device: str,
|
||||||
|
enable_prefix_caching: bool,
|
||||||
|
enable_chunked_prefill: bool,
|
||||||
|
max_num_batched_tokens: int,
|
||||||
|
distributed_executor_backend: Optional[str],
|
||||||
|
gpu_memory_utilization: float = 0.9,
|
||||||
|
download_dir: Optional[str] = None,
|
||||||
|
load_format: str = EngineArgs.load_format,
|
||||||
) -> float:
|
) -> float:
|
||||||
from vllm import LLM, SamplingParams
|
from vllm import LLM, SamplingParams
|
||||||
llm = LLM(
|
llm = LLM(
|
||||||
@ -84,31 +95,36 @@ def run_vllm(
|
|||||||
trust_remote_code=trust_remote_code,
|
trust_remote_code=trust_remote_code,
|
||||||
dtype=dtype,
|
dtype=dtype,
|
||||||
max_model_len=max_model_len,
|
max_model_len=max_model_len,
|
||||||
|
gpu_memory_utilization=gpu_memory_utilization,
|
||||||
enforce_eager=enforce_eager,
|
enforce_eager=enforce_eager,
|
||||||
kv_cache_dtype=kv_cache_dtype,
|
kv_cache_dtype=kv_cache_dtype,
|
||||||
|
quantization_param_path=quantization_param_path,
|
||||||
device=device,
|
device=device,
|
||||||
|
enable_prefix_caching=enable_prefix_caching,
|
||||||
|
download_dir=download_dir,
|
||||||
|
enable_chunked_prefill=enable_chunked_prefill,
|
||||||
|
max_num_batched_tokens=max_num_batched_tokens,
|
||||||
|
distributed_executor_backend=distributed_executor_backend,
|
||||||
|
load_format=load_format,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Add the requests to the engine.
|
# Add the requests to the engine.
|
||||||
|
prompts: List[str] = []
|
||||||
|
sampling_params: List[SamplingParams] = []
|
||||||
for prompt, _, output_len in requests:
|
for prompt, _, output_len in requests:
|
||||||
sampling_params = SamplingParams(
|
prompts.append(prompt)
|
||||||
n=n,
|
sampling_params.append(
|
||||||
temperature=0.0 if use_beam_search else 1.0,
|
SamplingParams(
|
||||||
top_p=1.0,
|
n=n,
|
||||||
use_beam_search=use_beam_search,
|
temperature=0.0 if use_beam_search else 1.0,
|
||||||
ignore_eos=True,
|
top_p=1.0,
|
||||||
max_tokens=output_len,
|
use_beam_search=use_beam_search,
|
||||||
)
|
ignore_eos=True,
|
||||||
# FIXME(woosuk): Do not use internal method.
|
max_tokens=output_len,
|
||||||
llm._add_request(
|
))
|
||||||
prompt=prompt,
|
|
||||||
prompt_token_ids=None,
|
|
||||||
sampling_params=sampling_params,
|
|
||||||
)
|
|
||||||
|
|
||||||
start = time.perf_counter()
|
start = time.perf_counter()
|
||||||
# FIXME(woosuk): Do not use internal method.
|
llm.generate(prompts, sampling_params, use_tqdm=True)
|
||||||
llm._run_engine(use_tqdm=True)
|
|
||||||
end = time.perf_counter()
|
end = time.perf_counter()
|
||||||
return end - start
|
return end - start
|
||||||
|
|
||||||
@ -179,13 +195,15 @@ def run_mii(
|
|||||||
tensor_parallel_size: int,
|
tensor_parallel_size: int,
|
||||||
output_len: int,
|
output_len: int,
|
||||||
) -> float:
|
) -> float:
|
||||||
from mii import pipeline
|
from mii import client, serve
|
||||||
llm = pipeline(model, tensor_parallel=tensor_parallel_size)
|
llm = serve(model, tensor_parallel=tensor_parallel_size)
|
||||||
prompts = [prompt for prompt, _, _ in requests]
|
prompts = [prompt for prompt, _, _ in requests]
|
||||||
|
|
||||||
start = time.perf_counter()
|
start = time.perf_counter()
|
||||||
llm(prompts, max_new_tokens=output_len)
|
llm.generate(prompts, max_new_tokens=output_len)
|
||||||
end = time.perf_counter()
|
end = time.perf_counter()
|
||||||
|
client = client(model)
|
||||||
|
client.terminate_server()
|
||||||
return end - start
|
return end - start
|
||||||
|
|
||||||
|
|
||||||
@ -206,12 +224,15 @@ def main(args: argparse.Namespace):
|
|||||||
args.output_len)
|
args.output_len)
|
||||||
|
|
||||||
if args.backend == "vllm":
|
if args.backend == "vllm":
|
||||||
elapsed_time = run_vllm(requests, args.model, args.tokenizer,
|
elapsed_time = run_vllm(
|
||||||
args.quantization, args.tensor_parallel_size,
|
requests, args.model, args.tokenizer, args.quantization,
|
||||||
args.seed, args.n, args.use_beam_search,
|
args.tensor_parallel_size, args.seed, args.n, args.use_beam_search,
|
||||||
args.trust_remote_code, args.dtype,
|
args.trust_remote_code, args.dtype, args.max_model_len,
|
||||||
args.max_model_len, args.enforce_eager,
|
args.enforce_eager, args.kv_cache_dtype,
|
||||||
args.kv_cache_dtype, args.device)
|
args.quantization_param_path, args.device,
|
||||||
|
args.enable_prefix_caching, args.enable_chunked_prefill,
|
||||||
|
args.max_num_batched_tokens, args.distributed_executor_backend,
|
||||||
|
args.gpu_memory_utilization, args.download_dir, args.load_format)
|
||||||
elif args.backend == "hf":
|
elif args.backend == "hf":
|
||||||
assert args.tensor_parallel_size == 1
|
assert args.tensor_parallel_size == 1
|
||||||
elapsed_time = run_hf(requests, args.model, tokenizer, args.n,
|
elapsed_time = run_hf(requests, args.model, tokenizer, args.n,
|
||||||
@ -227,9 +248,21 @@ def main(args: argparse.Namespace):
|
|||||||
print(f"Throughput: {len(requests) / elapsed_time:.2f} requests/s, "
|
print(f"Throughput: {len(requests) / elapsed_time:.2f} requests/s, "
|
||||||
f"{total_num_tokens / elapsed_time:.2f} tokens/s")
|
f"{total_num_tokens / elapsed_time:.2f} tokens/s")
|
||||||
|
|
||||||
|
# Output JSON results if specified
|
||||||
|
if args.output_json:
|
||||||
|
results = {
|
||||||
|
"elapsed_time": elapsed_time,
|
||||||
|
"num_requests": len(requests),
|
||||||
|
"total_num_tokens": total_num_tokens,
|
||||||
|
"requests_per_second": len(requests) / elapsed_time,
|
||||||
|
"tokens_per_second": total_num_tokens / elapsed_time,
|
||||||
|
}
|
||||||
|
with open(args.output_json, "w") as f:
|
||||||
|
json.dump(results, f, indent=4)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
parser = argparse.ArgumentParser(description="Benchmark the throughput.")
|
parser = FlexibleArgumentParser(description="Benchmark the throughput.")
|
||||||
parser.add_argument("--backend",
|
parser.add_argument("--backend",
|
||||||
type=str,
|
type=str,
|
||||||
choices=["vllm", "hf", "mii"],
|
choices=["vllm", "hf", "mii"],
|
||||||
@ -251,7 +284,7 @@ if __name__ == "__main__":
|
|||||||
parser.add_argument("--tokenizer", type=str, default=None)
|
parser.add_argument("--tokenizer", type=str, default=None)
|
||||||
parser.add_argument('--quantization',
|
parser.add_argument('--quantization',
|
||||||
'-q',
|
'-q',
|
||||||
choices=['awq', 'gptq', 'squeezellm', None],
|
choices=[*QUANTIZATION_METHODS, None],
|
||||||
default=None)
|
default=None)
|
||||||
parser.add_argument("--tensor-parallel-size", "-tp", type=int, default=1)
|
parser.add_argument("--tensor-parallel-size", "-tp", type=int, default=1)
|
||||||
parser.add_argument("--n",
|
parser.add_argument("--n",
|
||||||
@ -286,22 +319,92 @@ if __name__ == "__main__":
|
|||||||
'The "auto" option will use FP16 precision '
|
'The "auto" option will use FP16 precision '
|
||||||
'for FP32 and FP16 models, and BF16 precision '
|
'for FP32 and FP16 models, and BF16 precision '
|
||||||
'for BF16 models.')
|
'for BF16 models.')
|
||||||
|
parser.add_argument('--gpu-memory-utilization',
|
||||||
|
type=float,
|
||||||
|
default=0.9,
|
||||||
|
help='the fraction of GPU memory to be used for '
|
||||||
|
'the model executor, which can range from 0 to 1.'
|
||||||
|
'If unspecified, will use the default value of 0.9.')
|
||||||
parser.add_argument("--enforce-eager",
|
parser.add_argument("--enforce-eager",
|
||||||
action="store_true",
|
action="store_true",
|
||||||
help="enforce eager execution")
|
help="enforce eager execution")
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--kv-cache-dtype",
|
'--kv-cache-dtype',
|
||||||
type=str,
|
type=str,
|
||||||
choices=["auto", "fp8_e5m2"],
|
choices=['auto', 'fp8', 'fp8_e5m2', 'fp8_e4m3'],
|
||||||
default="auto",
|
default="auto",
|
||||||
help=
|
help='Data type for kv cache storage. If "auto", will use model '
|
||||||
'Data type for kv cache storage. If "auto", will use model data type.')
|
'data type. CUDA 11.8+ supports fp8 (=fp8_e4m3) and fp8_e5m2. '
|
||||||
|
'ROCm (AMD GPU) supports fp8 (=fp8_e4m3)')
|
||||||
|
parser.add_argument(
|
||||||
|
'--quantization-param-path',
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help='Path to the JSON file containing the KV cache scaling factors. '
|
||||||
|
'This should generally be supplied, when KV cache dtype is FP8. '
|
||||||
|
'Otherwise, KV cache scaling factors default to 1.0, which may cause '
|
||||||
|
'accuracy issues. FP8_E5M2 (without scaling) is only supported on '
|
||||||
|
'cuda version greater than 11.8. On ROCm (AMD GPU), FP8_E4M3 is '
|
||||||
|
'instead supported for common inference criteria.')
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--device",
|
"--device",
|
||||||
type=str,
|
type=str,
|
||||||
default="cuda",
|
default="auto",
|
||||||
choices=["cuda"],
|
choices=["auto", "cuda", "cpu", "openvino", "tpu", "xpu"],
|
||||||
help='device type for vLLM execution, supporting CUDA only currently.')
|
help='device type for vLLM execution, supporting CUDA, OpenVINO and '
|
||||||
|
'CPU.')
|
||||||
|
parser.add_argument(
|
||||||
|
"--enable-prefix-caching",
|
||||||
|
action='store_true',
|
||||||
|
help="enable automatic prefix caching for vLLM backend.")
|
||||||
|
parser.add_argument("--enable-chunked-prefill",
|
||||||
|
action='store_true',
|
||||||
|
help="enable chunked prefill for vLLM backend.")
|
||||||
|
parser.add_argument('--max-num-batched-tokens',
|
||||||
|
type=int,
|
||||||
|
default=None,
|
||||||
|
help='maximum number of batched tokens per '
|
||||||
|
'iteration')
|
||||||
|
parser.add_argument('--download-dir',
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help='directory to download and load the weights, '
|
||||||
|
'default to the default cache dir of huggingface')
|
||||||
|
parser.add_argument(
|
||||||
|
'--output-json',
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help='Path to save the throughput results in JSON format.')
|
||||||
|
parser.add_argument(
|
||||||
|
'--distributed-executor-backend',
|
||||||
|
choices=['ray', 'mp'],
|
||||||
|
default=None,
|
||||||
|
help='Backend to use for distributed serving. When more than 1 GPU '
|
||||||
|
'is used, will be automatically set to "ray" if installed '
|
||||||
|
'or "mp" (multiprocessing) otherwise.')
|
||||||
|
parser.add_argument(
|
||||||
|
'--load-format',
|
||||||
|
type=str,
|
||||||
|
default=EngineArgs.load_format,
|
||||||
|
choices=[
|
||||||
|
'auto', 'pt', 'safetensors', 'npcache', 'dummy', 'tensorizer',
|
||||||
|
'bitsandbytes'
|
||||||
|
],
|
||||||
|
help='The format of the model weights to load.\n\n'
|
||||||
|
'* "auto" will try to load the weights in the safetensors format '
|
||||||
|
'and fall back to the pytorch bin format if safetensors format '
|
||||||
|
'is not available.\n'
|
||||||
|
'* "pt" will load the weights in the pytorch bin format.\n'
|
||||||
|
'* "safetensors" will load the weights in the safetensors format.\n'
|
||||||
|
'* "npcache" will load the weights in pytorch format and store '
|
||||||
|
'a numpy cache to speed up the loading.\n'
|
||||||
|
'* "dummy" will initialize the weights with random values, '
|
||||||
|
'which is mainly for profiling.\n'
|
||||||
|
'* "tensorizer" will load the weights using tensorizer from '
|
||||||
|
'CoreWeave. See the Tensorize vLLM Model script in the Examples'
|
||||||
|
'section for more information.\n'
|
||||||
|
'* "bitsandbytes" will load the weights using bitsandbytes '
|
||||||
|
'quantization.\n')
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
if args.tokenizer is None:
|
if args.tokenizer is None:
|
||||||
args.tokenizer = args.model
|
args.tokenizer = args.model
|
||||||
|
|||||||
353
benchmarks/cutlass_benchmarks/w8a8_benchmarks.py
Normal file
353
benchmarks/cutlass_benchmarks/w8a8_benchmarks.py
Normal file
@ -0,0 +1,353 @@
|
|||||||
|
import argparse
|
||||||
|
import copy
|
||||||
|
import itertools
|
||||||
|
import pickle as pkl
|
||||||
|
import time
|
||||||
|
from typing import Callable, Iterable, List, Tuple
|
||||||
|
|
||||||
|
import torch
|
||||||
|
import torch.utils.benchmark as TBenchmark
|
||||||
|
from torch.utils.benchmark import Measurement as TMeasurement
|
||||||
|
from weight_shapes import WEIGHT_SHAPES
|
||||||
|
|
||||||
|
from vllm import _custom_ops as ops
|
||||||
|
from vllm.utils import FlexibleArgumentParser
|
||||||
|
|
||||||
|
DEFAULT_MODELS = list(WEIGHT_SHAPES.keys())[1:]
|
||||||
|
DEFAULT_BATCH_SIZES = [1, 16, 32, 64, 128, 256, 512]
|
||||||
|
DEFAULT_TP_SIZES = [1]
|
||||||
|
|
||||||
|
# helpers
|
||||||
|
|
||||||
|
|
||||||
|
def to_fp8(tensor: torch.tensor) -> torch.tensor:
|
||||||
|
finfo = torch.finfo(torch.float8_e4m3fn)
|
||||||
|
return torch.round(tensor.clamp(
|
||||||
|
min=finfo.min, max=finfo.max)).to(dtype=torch.float8_e4m3fn)
|
||||||
|
|
||||||
|
|
||||||
|
def to_int8(tensor: torch.tensor) -> torch.tensor:
|
||||||
|
return torch.round(tensor.clamp(min=-128, max=127)).to(dtype=torch.int8)
|
||||||
|
|
||||||
|
|
||||||
|
def make_rand_tensors(dtype: torch.dtype, m: int, n: int,
|
||||||
|
k: int) -> Tuple[torch.tensor, torch.tensor]:
|
||||||
|
|
||||||
|
a = torch.randn((m, k), device='cuda') * 5
|
||||||
|
b = torch.randn((n, k), device='cuda').t() * 5
|
||||||
|
|
||||||
|
if dtype == torch.int8:
|
||||||
|
return to_int8(a), to_int8(b)
|
||||||
|
if dtype == torch.float8_e4m3fn:
|
||||||
|
return to_fp8(a), to_fp8(b)
|
||||||
|
|
||||||
|
raise ValueError("unsupported dtype")
|
||||||
|
|
||||||
|
|
||||||
|
# impl
|
||||||
|
|
||||||
|
|
||||||
|
def pytorch_mm_impl(a: torch.tensor, b: torch.tensor, scale_a: torch.tensor,
|
||||||
|
scale_b: torch.tensor,
|
||||||
|
out_dtype: torch.dtype) -> torch.tensor:
|
||||||
|
return torch.mm(a, b)
|
||||||
|
|
||||||
|
|
||||||
|
def pytorch_fp8_impl(a: torch.tensor, b: torch.tensor, scale_a: torch.tensor,
|
||||||
|
scale_b: torch.tensor,
|
||||||
|
out_dtype: torch.dtype) -> torch.tensor:
|
||||||
|
return torch._scaled_mm(a,
|
||||||
|
b,
|
||||||
|
scale_a=scale_a,
|
||||||
|
scale_b=scale_b,
|
||||||
|
out_dtype=out_dtype)
|
||||||
|
|
||||||
|
|
||||||
|
def pytorch_fp8_impl_fast_accum(a: torch.tensor, b: torch.tensor,
|
||||||
|
scale_a: torch.tensor, scale_b: torch.tensor,
|
||||||
|
out_dtype: torch.dtype) -> torch.tensor:
|
||||||
|
return torch._scaled_mm(a,
|
||||||
|
b,
|
||||||
|
scale_a=scale_a,
|
||||||
|
scale_b=scale_b,
|
||||||
|
out_dtype=out_dtype,
|
||||||
|
use_fast_accum=True)
|
||||||
|
|
||||||
|
|
||||||
|
def cutlass_impl(a: torch.tensor, b: torch.tensor, scale_a: torch.tensor,
|
||||||
|
scale_b: torch.tensor,
|
||||||
|
out_dtype: torch.dtype) -> torch.tensor:
|
||||||
|
return ops.cutlass_scaled_mm(a, b, scale_a, scale_b, out_dtype=out_dtype)
|
||||||
|
|
||||||
|
|
||||||
|
# bench
|
||||||
|
def bench_fn(a: torch.tensor, b: torch.tensor, scale_a: torch.tensor,
|
||||||
|
scale_b: torch.tensor, out_dtype: torch.dtype, label: str,
|
||||||
|
sub_label: str, fn: Callable, description: str) -> TMeasurement:
|
||||||
|
|
||||||
|
min_run_time = 1
|
||||||
|
|
||||||
|
globals = {
|
||||||
|
"a": a,
|
||||||
|
"b": b,
|
||||||
|
"scale_a": scale_a,
|
||||||
|
"scale_b": scale_b,
|
||||||
|
"out_dtype": out_dtype,
|
||||||
|
"fn": fn,
|
||||||
|
}
|
||||||
|
return TBenchmark.Timer(
|
||||||
|
stmt="fn(a, b, scale_a, scale_b, out_dtype)",
|
||||||
|
globals=globals,
|
||||||
|
label=label,
|
||||||
|
sub_label=sub_label,
|
||||||
|
description=description,
|
||||||
|
).blocked_autorange(min_run_time=min_run_time)
|
||||||
|
|
||||||
|
|
||||||
|
def bench_int8(dtype: torch.dtype, m: int, k: int, n: int, label: str,
|
||||||
|
sub_label: str) -> Iterable[TMeasurement]:
|
||||||
|
assert dtype == torch.int8
|
||||||
|
a, b = make_rand_tensors(torch.int8, m, n, k)
|
||||||
|
scale_a = torch.tensor(1.0, device="cuda", dtype=torch.float32)
|
||||||
|
scale_b = torch.tensor(1.0, device="cuda", dtype=torch.float32)
|
||||||
|
|
||||||
|
timers = []
|
||||||
|
# pytorch impl
|
||||||
|
timers.append(
|
||||||
|
bench_fn(a.to(dtype=torch.bfloat16, device="cuda"),
|
||||||
|
b.to(dtype=torch.bfloat16, device="cuda"), scale_a, scale_b,
|
||||||
|
torch.bfloat16, label, sub_label, pytorch_mm_impl,
|
||||||
|
"pytorch_bf16_bf16_bf16_matmul-no-scales"))
|
||||||
|
|
||||||
|
# cutlass impl
|
||||||
|
timers.append(
|
||||||
|
bench_fn(a, b, scale_a, scale_b, torch.bfloat16, label, sub_label,
|
||||||
|
cutlass_impl, "cutlass_i8_i8_bf16_scaled_mm"))
|
||||||
|
|
||||||
|
return timers
|
||||||
|
|
||||||
|
|
||||||
|
def bench_fp8(dtype: torch.dtype, m: int, k: int, n: int, label: str,
|
||||||
|
sub_label: str) -> Iterable[TMeasurement]:
|
||||||
|
assert dtype == torch.float8_e4m3fn
|
||||||
|
a, b = make_rand_tensors(torch.float8_e4m3fn, m, n, k)
|
||||||
|
scale_a = torch.tensor(1.0, device="cuda", dtype=torch.float32)
|
||||||
|
scale_b = torch.tensor(1.0, device="cuda", dtype=torch.float32)
|
||||||
|
|
||||||
|
timers = []
|
||||||
|
|
||||||
|
# pytorch impl w. bf16
|
||||||
|
timers.append(
|
||||||
|
bench_fn(a.to(dtype=torch.bfloat16, device="cuda"),
|
||||||
|
b.to(dtype=torch.bfloat16, device="cuda"), scale_a, scale_b,
|
||||||
|
torch.bfloat16, label, sub_label, pytorch_mm_impl,
|
||||||
|
"pytorch_bf16_bf16_bf16_matmul-no-scales"))
|
||||||
|
|
||||||
|
# pytorch impl: bf16 output, without fp8 fast accum
|
||||||
|
timers.append(
|
||||||
|
bench_fn(a, b, scale_a, scale_b, torch.bfloat16, label, sub_label,
|
||||||
|
pytorch_fp8_impl, "pytorch_fp8_fp8_bf16_scaled_mm"))
|
||||||
|
|
||||||
|
# pytorch impl: bf16 output, with fp8 fast accum
|
||||||
|
timers.append(
|
||||||
|
bench_fn(a, b, scale_a, scale_b, torch.bfloat16, label, sub_label,
|
||||||
|
pytorch_fp8_impl_fast_accum,
|
||||||
|
"pytorch_fp8_fp8_bf16_scaled_mm_fast_accum"))
|
||||||
|
|
||||||
|
# pytorch impl: fp16 output, without fp8 fast accum
|
||||||
|
timers.append(
|
||||||
|
bench_fn(a, b, scale_a, scale_b, torch.float16, label, sub_label,
|
||||||
|
pytorch_fp8_impl, "pytorch_fp8_fp8_fp16_scaled_mm"))
|
||||||
|
|
||||||
|
# pytorch impl: fp16 output, with fp8 fast accum
|
||||||
|
timers.append(
|
||||||
|
bench_fn(a, b, scale_a, scale_b, torch.float16, label, sub_label,
|
||||||
|
pytorch_fp8_impl_fast_accum,
|
||||||
|
"pytorch_fp8_fp8_fp16_scaled_mm_fast_accum"))
|
||||||
|
|
||||||
|
# cutlass impl: bf16 output
|
||||||
|
timers.append(
|
||||||
|
bench_fn(a, b, scale_a, scale_b, torch.bfloat16, label, sub_label,
|
||||||
|
cutlass_impl, "cutlass_fp8_fp8_bf16_scaled_mm"))
|
||||||
|
# cutlass impl: fp16 output
|
||||||
|
timers.append(
|
||||||
|
bench_fn(a, b, scale_a, scale_b, torch.float16, label, sub_label,
|
||||||
|
cutlass_impl, "cutlass_fp8_fp8_fp16_scaled_mm"))
|
||||||
|
return timers
|
||||||
|
|
||||||
|
|
||||||
|
def bench(dtype: torch.dtype, m: int, k: int, n: int, label: str,
|
||||||
|
sub_label: str) -> Iterable[TMeasurement]:
|
||||||
|
if dtype == torch.int8:
|
||||||
|
return bench_int8(dtype, m, k, n, label, sub_label)
|
||||||
|
if dtype == torch.float8_e4m3fn:
|
||||||
|
return bench_fp8(dtype, m, k, n, label, sub_label)
|
||||||
|
raise ValueError("unsupported type")
|
||||||
|
|
||||||
|
|
||||||
|
# runner
|
||||||
|
def print_timers(timers: Iterable[TMeasurement]):
|
||||||
|
compare = TBenchmark.Compare(timers)
|
||||||
|
compare.print()
|
||||||
|
|
||||||
|
|
||||||
|
def run(dtype: torch.dtype,
|
||||||
|
MKNs: Iterable[Tuple[int, int, int]]) -> Iterable[TMeasurement]:
|
||||||
|
|
||||||
|
results = []
|
||||||
|
for m, k, n in MKNs:
|
||||||
|
timers = bench(dtype, m, k, n, f"scaled-{dtype}-gemm",
|
||||||
|
f"MKN=({m}x{k}x{n})")
|
||||||
|
print_timers(timers)
|
||||||
|
results.extend(timers)
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
# output makers
|
||||||
|
def make_output(data: Iterable[TMeasurement],
|
||||||
|
MKNs: Iterable[Tuple[int, int, int]],
|
||||||
|
base_description: str,
|
||||||
|
timestamp=None):
|
||||||
|
|
||||||
|
print(f"== All Results {base_description} ====")
|
||||||
|
print_timers(data)
|
||||||
|
|
||||||
|
# pickle all the results
|
||||||
|
timestamp = int(time.time()) if timestamp is None else timestamp
|
||||||
|
with open(f"{base_description}-{timestamp}.pkl", "wb") as f:
|
||||||
|
pkl.dump(data, f)
|
||||||
|
|
||||||
|
|
||||||
|
# argparse runners
|
||||||
|
|
||||||
|
|
||||||
|
def run_square_bench(args):
|
||||||
|
dim_sizes = list(
|
||||||
|
range(args.dim_start, args.dim_end + 1, args.dim_increment))
|
||||||
|
MKNs = list(zip(dim_sizes, dim_sizes, dim_sizes))
|
||||||
|
data = run(args.dtype, MKNs)
|
||||||
|
|
||||||
|
make_output(data, MKNs, f"square_bench-{args.dtype}")
|
||||||
|
|
||||||
|
|
||||||
|
def run_range_bench(args):
|
||||||
|
dim_sizes = list(range(args.dim_start, args.dim_end, args.dim_increment))
|
||||||
|
n = len(dim_sizes)
|
||||||
|
Ms = [args.m_constant] * n if args.m_constant is not None else dim_sizes
|
||||||
|
Ks = [args.k_constant] * n if args.k_constant is not None else dim_sizes
|
||||||
|
Ns = [args.n_constant] * n if args.n_constant is not None else dim_sizes
|
||||||
|
MKNs = list(zip(Ms, Ks, Ns))
|
||||||
|
data = run(args.dtype, MKNs)
|
||||||
|
|
||||||
|
make_output(data, MKNs, f"range_bench-{args.dtype}")
|
||||||
|
|
||||||
|
|
||||||
|
def run_model_bench(args):
|
||||||
|
|
||||||
|
print("Benchmarking models:")
|
||||||
|
for i, model in enumerate(args.models):
|
||||||
|
print(f"[{i}] {model}")
|
||||||
|
|
||||||
|
def model_shapes(model_name: str, tp_size: int) -> List[Tuple[int, int]]:
|
||||||
|
KNs = []
|
||||||
|
for KN, tp_split_dim in copy.deepcopy(WEIGHT_SHAPES[model_name]):
|
||||||
|
KN[tp_split_dim] = KN[tp_split_dim] // tp_size
|
||||||
|
KNs.append(KN)
|
||||||
|
return KNs
|
||||||
|
|
||||||
|
model_bench_data = []
|
||||||
|
models_tps = list(itertools.product(args.models, args.tp_sizes))
|
||||||
|
for model, tp_size in models_tps:
|
||||||
|
Ms = args.batch_sizes
|
||||||
|
KNs = model_shapes(model, tp_size)
|
||||||
|
MKNs = []
|
||||||
|
for m in Ms:
|
||||||
|
for k, n in KNs:
|
||||||
|
MKNs.append((m, k, n))
|
||||||
|
|
||||||
|
data = run(args.dtype, MKNs)
|
||||||
|
model_bench_data.append(data)
|
||||||
|
|
||||||
|
# Print all results
|
||||||
|
for data, model_tp in zip(model_bench_data, models_tps):
|
||||||
|
model, tp_size = model_tp
|
||||||
|
print(f"== Results {args.dtype} {model}-TP{tp_size} ====")
|
||||||
|
print_timers(data)
|
||||||
|
|
||||||
|
timestamp = int(time.time())
|
||||||
|
|
||||||
|
all_data = []
|
||||||
|
for d in model_bench_data:
|
||||||
|
all_data.extend(d)
|
||||||
|
# pickle all data
|
||||||
|
with open(f"model_bench-{args.dtype}-{timestamp}.pkl", "wb") as f:
|
||||||
|
pkl.dump(all_data, f)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
|
||||||
|
def to_torch_dtype(dt):
|
||||||
|
if dt == "int8":
|
||||||
|
return torch.int8
|
||||||
|
if dt == "fp8":
|
||||||
|
return torch.float8_e4m3fn
|
||||||
|
raise ValueError("unsupported dtype")
|
||||||
|
|
||||||
|
parser = FlexibleArgumentParser(
|
||||||
|
description="""
|
||||||
|
Benchmark Cutlass GEMM.
|
||||||
|
|
||||||
|
To run square GEMMs:
|
||||||
|
python3 ./benchmarks/cutlass_benchmarks/w8a8_benchmarks.py --dtype fp8 square_bench --dim-start 128 --dim-end 512 --dim-increment 64
|
||||||
|
|
||||||
|
To run constant N and K and sweep M:
|
||||||
|
python3 ./benchmarks/cutlass_benchmarks/w8a8_benchmarks.py --dtype fp8 range_bench --dim-start 128 --dim-end 512 --dim-increment 64 --n-constant 16384 --k-constant 16384
|
||||||
|
|
||||||
|
To run dimensions from a model:
|
||||||
|
python3 ./benchmarks/cutlass_benchmarks/w8a8_benchmarks.py --dtype fp8 model_bench --models meta-llama/Llama-2-7b-hf --batch-sizes 16 --tp-sizes 1
|
||||||
|
|
||||||
|
Output:
|
||||||
|
- a .pkl file, that is a list of raw torch.benchmark.utils.Measurements for the pytorch and cutlass implementations for the various GEMMs.
|
||||||
|
""", # noqa: E501
|
||||||
|
formatter_class=argparse.RawTextHelpFormatter)
|
||||||
|
|
||||||
|
parser.add_argument("--dtype",
|
||||||
|
type=to_torch_dtype,
|
||||||
|
required=True,
|
||||||
|
help="Available options are ['int8', 'fp8']")
|
||||||
|
subparsers = parser.add_subparsers(dest="cmd")
|
||||||
|
|
||||||
|
square_parser = subparsers.add_parser("square_bench")
|
||||||
|
square_parser.add_argument("--dim-start", type=int, required=True)
|
||||||
|
square_parser.add_argument("--dim-end", type=int, required=True)
|
||||||
|
square_parser.add_argument("--dim-increment", type=int, required=True)
|
||||||
|
square_parser.set_defaults(func=run_square_bench)
|
||||||
|
|
||||||
|
range_parser = subparsers.add_parser("range_bench")
|
||||||
|
range_parser.add_argument("--dim-start", type=int, required=True)
|
||||||
|
range_parser.add_argument("--dim-end", type=int, required=True)
|
||||||
|
range_parser.add_argument("--dim-increment", type=int, required=True)
|
||||||
|
range_parser.add_argument("--m-constant", type=int, default=None)
|
||||||
|
range_parser.add_argument("--n-constant", type=int, default=None)
|
||||||
|
range_parser.add_argument("--k-constant", type=int, default=None)
|
||||||
|
range_parser.set_defaults(func=run_range_bench)
|
||||||
|
|
||||||
|
model_parser = subparsers.add_parser("model_bench")
|
||||||
|
model_parser.add_argument("--models",
|
||||||
|
nargs="+",
|
||||||
|
type=str,
|
||||||
|
default=DEFAULT_MODELS,
|
||||||
|
choices=WEIGHT_SHAPES.keys())
|
||||||
|
model_parser.add_argument("--tp-sizes",
|
||||||
|
nargs="+",
|
||||||
|
type=int,
|
||||||
|
default=DEFAULT_TP_SIZES)
|
||||||
|
model_parser.add_argument("--batch-sizes",
|
||||||
|
nargs="+",
|
||||||
|
type=int,
|
||||||
|
default=DEFAULT_BATCH_SIZES)
|
||||||
|
model_parser.set_defaults(func=run_model_bench)
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
args.func(args)
|
||||||
43
benchmarks/cutlass_benchmarks/weight_shapes.py
Normal file
43
benchmarks/cutlass_benchmarks/weight_shapes.py
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
# Weight Shapes are in the format
|
||||||
|
# ([K, N], TP_SPLIT_DIM)
|
||||||
|
# Example:
|
||||||
|
# A shape of ([14336, 4096], 0) indicates the following GEMM shape,
|
||||||
|
# - TP1 : K = 14336, N = 4096
|
||||||
|
# - TP2 : K = 7168, N = 4096
|
||||||
|
# A shape of ([4096, 6144], 1) indicates the following GEMM shape,
|
||||||
|
# - TP1 : K = 4096, N = 6144
|
||||||
|
# - TP4 : K = 4096, N = 1536
|
||||||
|
|
||||||
|
# TP1 shapes
|
||||||
|
WEIGHT_SHAPES = {
|
||||||
|
"mistralai/Mistral-7B-v0.1": [
|
||||||
|
([4096, 6144], 1),
|
||||||
|
([4096, 4096], 0),
|
||||||
|
([4096, 28672], 1),
|
||||||
|
([14336, 4096], 0),
|
||||||
|
],
|
||||||
|
"meta-llama/Llama-2-7b-hf": [
|
||||||
|
([4096, 12288], 1),
|
||||||
|
([4096, 4096], 0),
|
||||||
|
([4096, 22016], 1),
|
||||||
|
([11008, 4096], 0),
|
||||||
|
],
|
||||||
|
"meta-llama/Llama-3-8b": [
|
||||||
|
([4096, 6144], 1),
|
||||||
|
([4096, 4096], 0),
|
||||||
|
([4096, 28672], 1),
|
||||||
|
([14336, 4096], 0),
|
||||||
|
],
|
||||||
|
"meta-llama/Llama-2-13b-hf": [
|
||||||
|
([5120, 15360], 1),
|
||||||
|
([5120, 5120], 0),
|
||||||
|
([5120, 27648], 1),
|
||||||
|
([13824, 5120], 0),
|
||||||
|
],
|
||||||
|
"meta-llama/Llama-2-70b-hf": [
|
||||||
|
([8192, 10240], 1),
|
||||||
|
([8192, 8192], 0),
|
||||||
|
([8192, 57344], 1),
|
||||||
|
([28672, 8192], 0),
|
||||||
|
],
|
||||||
|
}
|
||||||
302
benchmarks/kernels/benchmark_aqlm.py
Normal file
302
benchmarks/kernels/benchmark_aqlm.py
Normal file
@ -0,0 +1,302 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
import torch
|
||||||
|
import torch.nn.functional as F
|
||||||
|
|
||||||
|
from vllm import _custom_ops as ops
|
||||||
|
from vllm.model_executor.layers.quantization.aqlm import (
|
||||||
|
dequantize_weight, generic_dequantize_gemm, get_int_dtype,
|
||||||
|
optimized_dequantize_gemm)
|
||||||
|
from vllm.utils import FlexibleArgumentParser
|
||||||
|
|
||||||
|
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
||||||
|
|
||||||
|
|
||||||
|
def torch_mult(
|
||||||
|
input: torch.Tensor, # [..., in_features]
|
||||||
|
weights: torch.Tensor,
|
||||||
|
scales: torch.Tensor, # [num_out_groups, 1, 1, 1]
|
||||||
|
) -> torch.Tensor:
|
||||||
|
output = F.linear(input, weights)
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
def dequant_out_scale(
|
||||||
|
input: torch.Tensor, # [..., in_features]
|
||||||
|
codes: torch.IntTensor, # [num_out_groups, num_in_groups, num_codebooks]
|
||||||
|
codebooks: torch.
|
||||||
|
Tensor, # [num_codebooks, codebook_size, out_group_size, in_group_size]
|
||||||
|
scales: torch.Tensor, # [num_out_groups, 1, 1, 1]
|
||||||
|
output_partition_sizes: torch.IntTensor,
|
||||||
|
bias: Optional[torch.Tensor],
|
||||||
|
) -> torch.Tensor:
|
||||||
|
|
||||||
|
weights = ops.aqlm_dequant(codes, codebooks, output_partition_sizes)
|
||||||
|
|
||||||
|
if bias is None:
|
||||||
|
output = F.linear(input, weights, bias)
|
||||||
|
orig_shape = output.shape
|
||||||
|
flattened_output = output.view(-1, output.size(-1))
|
||||||
|
f_scales = scales.view(-1, scales.shape[0])
|
||||||
|
b_scales = f_scales.expand(flattened_output.shape[0], -1)
|
||||||
|
flattened_output *= b_scales
|
||||||
|
return flattened_output.view(orig_shape)
|
||||||
|
else:
|
||||||
|
b_scales = scales.view(scales.shape[:-3] + (-1, )).expand(
|
||||||
|
-1, weights.shape[1])
|
||||||
|
weights *= b_scales
|
||||||
|
return F.linear(input, weights, bias)
|
||||||
|
|
||||||
|
|
||||||
|
def dequant_weight_scale(
|
||||||
|
input: torch.Tensor, # [..., in_features]
|
||||||
|
codes: torch.IntTensor, # [num_out_groups, num_in_groups, num_codebooks]
|
||||||
|
codebooks: torch.
|
||||||
|
Tensor, # [num_codebooks, codebook_size, out_group_size, in_group_size]
|
||||||
|
scales: torch.Tensor, # [num_out_groups, 1, 1, 1]
|
||||||
|
output_partition_sizes: torch.IntTensor,
|
||||||
|
bias: Optional[torch.Tensor],
|
||||||
|
) -> torch.Tensor:
|
||||||
|
|
||||||
|
weights = ops.aqlm_dequant(codes, codebooks, output_partition_sizes)
|
||||||
|
|
||||||
|
b_scales = scales.view(scales.shape[:-3] + (-1, )).expand(
|
||||||
|
-1, weights.shape[1])
|
||||||
|
weights *= b_scales
|
||||||
|
return F.linear(input, weights, bias)
|
||||||
|
|
||||||
|
|
||||||
|
def dequant_no_scale(
|
||||||
|
input: torch.Tensor, # [..., in_features]
|
||||||
|
codes: torch.IntTensor, # [num_out_groups, num_in_groups, num_codebooks]
|
||||||
|
codebooks: torch.
|
||||||
|
Tensor, # [num_codebooks, codebook_size, out_group_size, in_group_size]
|
||||||
|
scales: torch.Tensor, # [num_out_groups, 1, 1, 1]
|
||||||
|
output_partition_sizes: torch.IntTensor,
|
||||||
|
bias: Optional[torch.Tensor],
|
||||||
|
) -> torch.Tensor:
|
||||||
|
|
||||||
|
weights = ops.aqlm_dequant(codes, codebooks, output_partition_sizes)
|
||||||
|
|
||||||
|
return F.linear(input, weights, bias)
|
||||||
|
|
||||||
|
|
||||||
|
# Compare the optimized 1x16 and 2x8 cuda decompression/dequant kernels against
|
||||||
|
# the generic pytorch version.
|
||||||
|
# Just visual comparison.
|
||||||
|
def dequant_test(k: int, parts: torch.Tensor, nbooks: int, bits: int) -> None:
|
||||||
|
|
||||||
|
n = int(parts.sum().item())
|
||||||
|
|
||||||
|
device = torch.device('cuda:0')
|
||||||
|
|
||||||
|
code_range = (1 << bits) // 2
|
||||||
|
ingroups = 8
|
||||||
|
|
||||||
|
codes = torch.randint(-code_range,
|
||||||
|
code_range,
|
||||||
|
size=(n, k // ingroups, nbooks),
|
||||||
|
dtype=get_int_dtype(bits),
|
||||||
|
device=device)
|
||||||
|
|
||||||
|
codebooks = torch.randn(size=(parts.shape[0] * nbooks, 1 << bits, 1, 8),
|
||||||
|
dtype=torch.float16,
|
||||||
|
device=device)
|
||||||
|
|
||||||
|
count = 0
|
||||||
|
for index in range(16):
|
||||||
|
for i in range(8):
|
||||||
|
for book in range(nbooks):
|
||||||
|
codebooks[book, index, 0, i] = count * (10**book)
|
||||||
|
count += 1
|
||||||
|
|
||||||
|
print("codes shape", codes.shape)
|
||||||
|
|
||||||
|
for i in range(16):
|
||||||
|
for book in range(nbooks):
|
||||||
|
codes[0, i, book] = i
|
||||||
|
codes[0, -i, book] = i
|
||||||
|
|
||||||
|
weights = dequantize_weight(codes, codebooks, None)
|
||||||
|
weights2 = ops.aqlm_dequant(codes, codebooks, parts)
|
||||||
|
|
||||||
|
print("weights shape:", weights.shape)
|
||||||
|
print("weights2 shape:", weights2.shape)
|
||||||
|
|
||||||
|
print("weights are:", weights)
|
||||||
|
print("weights2 are:", weights2)
|
||||||
|
|
||||||
|
print("first 128 weights are", weights[0, 0:128].to(torch.int32))
|
||||||
|
print("first 128 weights2 are:", weights2[0, 0:128].to(torch.int32))
|
||||||
|
|
||||||
|
print("last 128 weights are", weights[0, -128:])
|
||||||
|
print("last 128 weights2 are:", weights2[0, -128:])
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
|
||||||
|
parser = FlexibleArgumentParser(description="Benchmark aqlm performance.")
|
||||||
|
|
||||||
|
# Add arguments
|
||||||
|
parser.add_argument("--nbooks",
|
||||||
|
type=int,
|
||||||
|
default=1,
|
||||||
|
help="Number of codebooks (default: 1)")
|
||||||
|
parser.add_argument("--bits",
|
||||||
|
type=int,
|
||||||
|
default=16,
|
||||||
|
help="Number of bits per code element (default: 16)")
|
||||||
|
parser.add_argument(
|
||||||
|
"--test",
|
||||||
|
type=bool,
|
||||||
|
default=False,
|
||||||
|
help="Run the decompression/dequant tester rather than benchmarking "
|
||||||
|
"(default: False)")
|
||||||
|
|
||||||
|
# Parse the arguments
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
# Extract values
|
||||||
|
nbooks = args.nbooks
|
||||||
|
bits = args.bits
|
||||||
|
|
||||||
|
if args.test:
|
||||||
|
dequant_test(4096, torch.tensor((4096, )), nbooks, bits)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Otherwise, benchmark.
|
||||||
|
methods = [
|
||||||
|
ops.aqlm_gemm,
|
||||||
|
dequant_out_scale,
|
||||||
|
generic_dequantize_gemm,
|
||||||
|
optimized_dequantize_gemm,
|
||||||
|
dequant_weight_scale,
|
||||||
|
torch_mult,
|
||||||
|
dequant_no_scale,
|
||||||
|
]
|
||||||
|
|
||||||
|
filename = f"./aqlm_benchmark_{nbooks}x{bits}.csv"
|
||||||
|
print(f"writing benchmarks to file {filename}")
|
||||||
|
with open(filename, "w") as f:
|
||||||
|
sys.stdout = f
|
||||||
|
|
||||||
|
print('m | k | n | n parts', end='')
|
||||||
|
for method in methods:
|
||||||
|
print(f" | {method.__name__.replace('_', ' ')} (µs)", end='')
|
||||||
|
print('')
|
||||||
|
|
||||||
|
# These are reasonable prefill sizes.
|
||||||
|
ksandpartions = ((4096, (4096, 4096, 4096)), (4096, (4096, )),
|
||||||
|
(4096, (11008, 11008)), (11008, (4096, )))
|
||||||
|
|
||||||
|
# reasonable ranges for m.
|
||||||
|
for m in [
|
||||||
|
1, 2, 4, 8, 10, 12, 14, 16, 24, 32, 48, 52, 56, 64, 96, 112,
|
||||||
|
128, 256, 512, 1024, 1536, 2048, 3072, 4096
|
||||||
|
]:
|
||||||
|
print(f'{m}', file=sys.__stdout__)
|
||||||
|
for ksp in ksandpartions:
|
||||||
|
run_grid(m, ksp[0], torch.tensor(ksp[1]), nbooks, bits,
|
||||||
|
methods)
|
||||||
|
|
||||||
|
sys.stdout = sys.__stdout__
|
||||||
|
|
||||||
|
|
||||||
|
def run_grid(m: int, k: int, parts: torch.Tensor, nbooks: int, bits: int,
|
||||||
|
methods):
|
||||||
|
|
||||||
|
# I didn't see visible improvements from increasing these, but feel free :)
|
||||||
|
num_warmup_trials = 1
|
||||||
|
num_trials = 1
|
||||||
|
|
||||||
|
num_calls = 100
|
||||||
|
|
||||||
|
# warmup.
|
||||||
|
for method in methods:
|
||||||
|
for _ in range(num_warmup_trials):
|
||||||
|
run_timing(
|
||||||
|
num_calls=num_calls,
|
||||||
|
m=m,
|
||||||
|
k=k,
|
||||||
|
parts=parts,
|
||||||
|
nbooks=nbooks,
|
||||||
|
bits=bits,
|
||||||
|
method=method,
|
||||||
|
)
|
||||||
|
|
||||||
|
n = parts.sum().item()
|
||||||
|
print(f'{m} | {k} | {n} | {parts.tolist()}', end='')
|
||||||
|
|
||||||
|
for method in methods:
|
||||||
|
best_time_us = 1e20
|
||||||
|
for _ in range(num_trials):
|
||||||
|
kernel_dur_ms = run_timing(
|
||||||
|
num_calls=num_calls,
|
||||||
|
m=m,
|
||||||
|
k=k,
|
||||||
|
parts=parts,
|
||||||
|
nbooks=nbooks,
|
||||||
|
bits=bits,
|
||||||
|
method=method,
|
||||||
|
)
|
||||||
|
|
||||||
|
kernel_dur_us = 1000 * kernel_dur_ms
|
||||||
|
|
||||||
|
if kernel_dur_us < best_time_us:
|
||||||
|
best_time_us = kernel_dur_us
|
||||||
|
|
||||||
|
print(f' | {kernel_dur_us:.0f}', end='')
|
||||||
|
|
||||||
|
print('')
|
||||||
|
|
||||||
|
|
||||||
|
def run_timing(num_calls: int, m: int, k: int, parts: torch.Tensor,
|
||||||
|
nbooks: int, bits: int, method) -> float:
|
||||||
|
|
||||||
|
n = int(parts.sum().item())
|
||||||
|
|
||||||
|
device = torch.device('cuda:0')
|
||||||
|
|
||||||
|
input = torch.randn((1, m, k), dtype=torch.float16, device=device)
|
||||||
|
|
||||||
|
code_range = (1 << bits) // 2
|
||||||
|
ingroups = 8
|
||||||
|
|
||||||
|
codes = torch.randint(-code_range,
|
||||||
|
code_range,
|
||||||
|
size=(n, k // ingroups, nbooks),
|
||||||
|
dtype=get_int_dtype(bits),
|
||||||
|
device=device)
|
||||||
|
|
||||||
|
codebooks = torch.randn(size=(parts.shape[0] * nbooks, 1 << bits, 1, 8),
|
||||||
|
dtype=torch.float16,
|
||||||
|
device=device)
|
||||||
|
|
||||||
|
scales = torch.randn(size=(n, 1, 1, 1), dtype=torch.float16, device=device)
|
||||||
|
|
||||||
|
# for comparison to just a pytorch mult.
|
||||||
|
weights = torch.randn((n, k), dtype=torch.float16, device=device)
|
||||||
|
|
||||||
|
start_event = torch.cuda.Event(enable_timing=True)
|
||||||
|
end_event = torch.cuda.Event(enable_timing=True)
|
||||||
|
|
||||||
|
start_event.record()
|
||||||
|
|
||||||
|
if method is torch_mult:
|
||||||
|
for i in range(num_calls):
|
||||||
|
torch_mult(input, weights, scales)
|
||||||
|
else:
|
||||||
|
for i in range(num_calls):
|
||||||
|
method(input, codes, codebooks, scales, parts, None)
|
||||||
|
|
||||||
|
end_event.record()
|
||||||
|
end_event.synchronize()
|
||||||
|
|
||||||
|
dur_ms = start_event.elapsed_time(end_event) / num_calls
|
||||||
|
return dur_ms
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
235
benchmarks/kernels/benchmark_marlin.py
Normal file
235
benchmarks/kernels/benchmark_marlin.py
Normal file
@ -0,0 +1,235 @@
|
|||||||
|
from typing import List
|
||||||
|
|
||||||
|
import torch
|
||||||
|
import torch.utils.benchmark as benchmark
|
||||||
|
from benchmark_shapes import WEIGHT_SHAPES
|
||||||
|
|
||||||
|
from vllm import _custom_ops as ops
|
||||||
|
from vllm.model_executor.layers.quantization.gptq_marlin import (
|
||||||
|
GPTQ_MARLIN_MAX_PARALLEL, GPTQ_MARLIN_MIN_THREAD_N,
|
||||||
|
GPTQ_MARLIN_SUPPORTED_GROUP_SIZES, GPTQ_MARLIN_SUPPORTED_NUM_BITS)
|
||||||
|
from vllm.model_executor.layers.quantization.gptq_marlin_24 import (
|
||||||
|
GPTQ_MARLIN_24_MAX_PARALLEL, GPTQ_MARLIN_24_MIN_THREAD_N,
|
||||||
|
GPTQ_MARLIN_24_SUPPORTED_GROUP_SIZES, GPTQ_MARLIN_24_SUPPORTED_NUM_BITS)
|
||||||
|
from vllm.model_executor.layers.quantization.utils.marlin_utils import (
|
||||||
|
MarlinWorkspace, marlin_24_quantize, marlin_quantize)
|
||||||
|
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||||
|
gptq_pack, quantize_weights, sort_weights)
|
||||||
|
from vllm.utils import FlexibleArgumentParser
|
||||||
|
|
||||||
|
DEFAULT_MODELS = ["meta-llama/Llama-2-7b-hf/TP1"]
|
||||||
|
DEFAULT_BATCH_SIZES = [1, 16, 32, 64, 128, 256, 512]
|
||||||
|
|
||||||
|
ACT_ORDER_OPTS = [False, True]
|
||||||
|
K_FULL_OPTS = [False, True]
|
||||||
|
|
||||||
|
|
||||||
|
def bench_run(results: List[benchmark.Measurement], model: str,
|
||||||
|
act_order: bool, is_k_full: bool, num_bits: int, group_size: int,
|
||||||
|
size_m: int, size_k: int, size_n: int):
|
||||||
|
label = "Quant Matmul"
|
||||||
|
|
||||||
|
sub_label = ("{}, act={} k_full={}, b={}, g={}, "
|
||||||
|
"MKN=({}x{}x{})".format(model, act_order, is_k_full, num_bits,
|
||||||
|
group_size, size_m, size_k, size_n))
|
||||||
|
|
||||||
|
print(f"Testing: {sub_label}")
|
||||||
|
|
||||||
|
a = torch.randn(size_m, size_k).to(torch.half).cuda()
|
||||||
|
b = torch.rand(size_k, size_n).to(torch.half).cuda()
|
||||||
|
|
||||||
|
a_tmp = (torch.zeros(size_m, size_k).to(torch.half).cuda())
|
||||||
|
|
||||||
|
# Marlin quant
|
||||||
|
(
|
||||||
|
marlin_w_ref,
|
||||||
|
marlin_q_w,
|
||||||
|
marlin_s,
|
||||||
|
marlin_g_idx,
|
||||||
|
marlin_sort_indices,
|
||||||
|
marlin_rand_perm,
|
||||||
|
) = marlin_quantize(b, num_bits, group_size, act_order)
|
||||||
|
|
||||||
|
# Marlin_24 quant
|
||||||
|
(marlin_24_w_ref, marlin_24_q_w_comp, marlin_24_meta,
|
||||||
|
marlin_24_s) = marlin_24_quantize(b, num_bits, group_size)
|
||||||
|
|
||||||
|
# GPTQ quant
|
||||||
|
(w_ref, q_w, s, g_idx,
|
||||||
|
rand_perm) = quantize_weights(b, num_bits, group_size, act_order)
|
||||||
|
q_w_gptq = gptq_pack(q_w, num_bits, size_k, size_n)
|
||||||
|
|
||||||
|
# For act_order, sort the "weights" and "g_idx"
|
||||||
|
# so that group ids are increasing
|
||||||
|
repack_sort_indices = torch.empty(0, dtype=torch.int, device=b.device)
|
||||||
|
if act_order:
|
||||||
|
(q_w, g_idx, repack_sort_indices) = sort_weights(q_w, g_idx)
|
||||||
|
|
||||||
|
# Prepare
|
||||||
|
marlin_workspace = MarlinWorkspace(size_n, GPTQ_MARLIN_MIN_THREAD_N,
|
||||||
|
GPTQ_MARLIN_MAX_PARALLEL)
|
||||||
|
|
||||||
|
marlin_24_workspace = MarlinWorkspace(size_n, GPTQ_MARLIN_24_MIN_THREAD_N,
|
||||||
|
GPTQ_MARLIN_24_MAX_PARALLEL)
|
||||||
|
|
||||||
|
globals = {
|
||||||
|
# Gen params
|
||||||
|
"num_bits": num_bits,
|
||||||
|
"group_size": group_size,
|
||||||
|
"size_m": size_m,
|
||||||
|
"size_n": size_n,
|
||||||
|
"size_k": size_k,
|
||||||
|
"a": a,
|
||||||
|
"a_tmp": a_tmp,
|
||||||
|
# Marlin params
|
||||||
|
"marlin_w_ref": marlin_w_ref,
|
||||||
|
"marlin_q_w": marlin_q_w,
|
||||||
|
"marlin_s": marlin_s,
|
||||||
|
"marlin_g_idx": marlin_g_idx,
|
||||||
|
"marlin_sort_indices": marlin_sort_indices,
|
||||||
|
"marlin_rand_perm": marlin_rand_perm,
|
||||||
|
"marlin_workspace": marlin_workspace,
|
||||||
|
"is_k_full": is_k_full,
|
||||||
|
# Marlin_24 params
|
||||||
|
"marlin_24_w_ref": marlin_24_w_ref,
|
||||||
|
"marlin_24_q_w_comp": marlin_24_q_w_comp,
|
||||||
|
"marlin_24_meta": marlin_24_meta,
|
||||||
|
"marlin_24_s": marlin_24_s,
|
||||||
|
"marlin_24_workspace": marlin_24_workspace,
|
||||||
|
# GPTQ params
|
||||||
|
"q_w_gptq": q_w_gptq,
|
||||||
|
"repack_sort_indices": repack_sort_indices,
|
||||||
|
# Kernels
|
||||||
|
"gptq_marlin_gemm": ops.gptq_marlin_gemm,
|
||||||
|
"gptq_marlin_24_gemm": ops.gptq_marlin_24_gemm,
|
||||||
|
"gptq_marlin_repack": ops.gptq_marlin_repack,
|
||||||
|
}
|
||||||
|
|
||||||
|
min_run_time = 1
|
||||||
|
|
||||||
|
# Warmup pytorch
|
||||||
|
for i in range(5):
|
||||||
|
torch.matmul(a, marlin_w_ref)
|
||||||
|
|
||||||
|
results.append(
|
||||||
|
benchmark.Timer(
|
||||||
|
stmt="torch.matmul(a, marlin_w_ref)",
|
||||||
|
globals=globals,
|
||||||
|
label=label,
|
||||||
|
sub_label=sub_label,
|
||||||
|
description="pytorch_gemm",
|
||||||
|
).blocked_autorange(min_run_time=min_run_time))
|
||||||
|
|
||||||
|
results.append(
|
||||||
|
benchmark.Timer(
|
||||||
|
stmt=
|
||||||
|
"output = gptq_marlin_gemm(a, marlin_q_w, marlin_s, marlin_g_idx, marlin_sort_indices, marlin_workspace.scratch, num_bits, size_m, size_n, size_k, is_k_full)", # noqa: E501
|
||||||
|
globals=globals,
|
||||||
|
label=label,
|
||||||
|
sub_label=sub_label,
|
||||||
|
description="gptq_marlin_gemm",
|
||||||
|
).blocked_autorange(min_run_time=min_run_time))
|
||||||
|
|
||||||
|
if (num_bits in GPTQ_MARLIN_24_SUPPORTED_NUM_BITS
|
||||||
|
and group_size in GPTQ_MARLIN_24_SUPPORTED_GROUP_SIZES):
|
||||||
|
results.append(
|
||||||
|
benchmark.Timer(
|
||||||
|
stmt=
|
||||||
|
"output = gptq_marlin_24_gemm(a, marlin_24_q_w_comp, marlin_24_meta, marlin_24_s, marlin_24_workspace.scratch, num_bits, size_m, size_n, size_k)", # noqa: E501
|
||||||
|
globals=globals,
|
||||||
|
label=label,
|
||||||
|
sub_label=sub_label,
|
||||||
|
description="gptq_marlin_24_gemm",
|
||||||
|
).blocked_autorange(min_run_time=min_run_time))
|
||||||
|
|
||||||
|
results.append(
|
||||||
|
benchmark.Timer(
|
||||||
|
stmt=
|
||||||
|
"q_res = gptq_marlin_repack(q_w_gptq, repack_sort_indices, size_k, size_n, num_bits)", # noqa: E501
|
||||||
|
globals=globals,
|
||||||
|
label=label,
|
||||||
|
sub_label=sub_label,
|
||||||
|
description="gptq_marlin_repack",
|
||||||
|
).blocked_autorange(min_run_time=min_run_time))
|
||||||
|
|
||||||
|
|
||||||
|
def main(args):
|
||||||
|
print("Benchmarking models:")
|
||||||
|
for i, model in enumerate(args.models):
|
||||||
|
print(f"[{i}] {model}")
|
||||||
|
|
||||||
|
results: List[benchmark.Measurement] = []
|
||||||
|
|
||||||
|
for model in args.models:
|
||||||
|
for layer in WEIGHT_SHAPES[model]:
|
||||||
|
size_k = layer[0]
|
||||||
|
size_n = layer[1]
|
||||||
|
|
||||||
|
if len(args.limit_k) > 0 and size_k not in args.limit_k:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if len(args.limit_n) > 0 and size_n not in args.limit_n:
|
||||||
|
continue
|
||||||
|
|
||||||
|
for act_order in ACT_ORDER_OPTS:
|
||||||
|
if len(args.limit_act_order
|
||||||
|
) > 0 and act_order not in args.limit_act_order:
|
||||||
|
continue
|
||||||
|
|
||||||
|
for is_k_full in K_FULL_OPTS:
|
||||||
|
if len(args.limit_k_full
|
||||||
|
) > 0 and is_k_full not in args.limit_k_full:
|
||||||
|
continue
|
||||||
|
|
||||||
|
for num_bits in GPTQ_MARLIN_SUPPORTED_NUM_BITS:
|
||||||
|
if len(args.limit_num_bits
|
||||||
|
) > 0 and num_bits not in args.limit_num_bits:
|
||||||
|
continue
|
||||||
|
|
||||||
|
for group_size in GPTQ_MARLIN_SUPPORTED_GROUP_SIZES:
|
||||||
|
if len(
|
||||||
|
args.limit_group_size
|
||||||
|
) > 0 and group_size not in args.limit_group_size:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# For act_order, the group_size must be less than
|
||||||
|
# size_k
|
||||||
|
if act_order and (group_size == size_k
|
||||||
|
or group_size == -1):
|
||||||
|
continue
|
||||||
|
|
||||||
|
for size_m in args.batch_sizes:
|
||||||
|
bench_run(results, model, act_order, is_k_full,
|
||||||
|
num_bits, group_size, size_m, size_k,
|
||||||
|
size_n)
|
||||||
|
|
||||||
|
compare = benchmark.Compare(results)
|
||||||
|
compare.print()
|
||||||
|
|
||||||
|
|
||||||
|
# For quick benchmarking use:
|
||||||
|
# python benchmark_marlin.py --batch-sizes 1 16 32 --limit-k 4096 --limit-n 4096 --limit-group-size 128 --limit-num-bits 4 --limit-act-order 0 --limit-k-full 1 # noqa E501
|
||||||
|
#
|
||||||
|
if __name__ == "__main__":
|
||||||
|
parser = FlexibleArgumentParser(
|
||||||
|
description="Benchmark Marlin across specified models/shapes/batches")
|
||||||
|
parser.add_argument(
|
||||||
|
"--models",
|
||||||
|
nargs="+",
|
||||||
|
type=str,
|
||||||
|
default=DEFAULT_MODELS,
|
||||||
|
choices=WEIGHT_SHAPES.keys(),
|
||||||
|
)
|
||||||
|
parser.add_argument("--batch-sizes",
|
||||||
|
nargs="+",
|
||||||
|
type=int,
|
||||||
|
default=DEFAULT_BATCH_SIZES)
|
||||||
|
parser.add_argument("--limit-k", nargs="+", type=int, default=[])
|
||||||
|
parser.add_argument("--limit-n", nargs="+", type=int, default=[])
|
||||||
|
parser.add_argument("--limit-group-size", nargs="+", type=int, default=[])
|
||||||
|
parser.add_argument("--limit-num-bits", nargs="+", type=int, default=[])
|
||||||
|
parser.add_argument("--limit-act-order", nargs="+", type=int, default=[])
|
||||||
|
parser.add_argument("--limit-k-full", nargs="+", type=int, default=[])
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
main(args)
|
||||||
@ -1,172 +0,0 @@
|
|||||||
import json
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
|
||||||
|
|
||||||
from vllm.model_executor.layers.fused_moe import fused_moe
|
|
||||||
import torch
|
|
||||||
import torch.nn.functional as F
|
|
||||||
import triton
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
method = fused_moe
|
|
||||||
for bs in [
|
|
||||||
1, 2, 4, 8, 16, 24, 32, 48, 64, 96, 128, 256, 512, 1024, 1536,
|
|
||||||
2048, 3072, 4096
|
|
||||||
]:
|
|
||||||
run_grid(bs, method=method)
|
|
||||||
|
|
||||||
|
|
||||||
def run_grid(bs, method):
|
|
||||||
d_model = 4096
|
|
||||||
num_total_experts = 8
|
|
||||||
top_k = 2
|
|
||||||
tp_size = 2
|
|
||||||
model_intermediate_size = 14336
|
|
||||||
num_layers = 32
|
|
||||||
num_calls = 100
|
|
||||||
|
|
||||||
num_warmup_trials = 1
|
|
||||||
num_trials = 1
|
|
||||||
|
|
||||||
configs = []
|
|
||||||
if bs <= 16:
|
|
||||||
BLOCK_SIZES_M = [16]
|
|
||||||
elif bs <= 32:
|
|
||||||
BLOCK_SIZES_M = [16, 32]
|
|
||||||
elif bs <= 64:
|
|
||||||
BLOCK_SIZES_M = [16, 32, 64]
|
|
||||||
elif bs <= 128:
|
|
||||||
BLOCK_SIZES_M = [16, 32, 64, 128]
|
|
||||||
else:
|
|
||||||
BLOCK_SIZES_M = [16, 32, 64, 128, 256]
|
|
||||||
|
|
||||||
for block_size_n in [32, 64, 128, 256]:
|
|
||||||
for block_size_m in BLOCK_SIZES_M:
|
|
||||||
for block_size_k in [64, 128, 256]:
|
|
||||||
for group_size_m in [1, 16, 32, 64]:
|
|
||||||
for num_warps in [4, 8]:
|
|
||||||
configs.append({
|
|
||||||
"BLOCK_SIZE_M": block_size_m,
|
|
||||||
"BLOCK_SIZE_N": block_size_n,
|
|
||||||
"BLOCK_SIZE_K": block_size_k,
|
|
||||||
"GROUP_SIZE_M": group_size_m,
|
|
||||||
"num_warps": num_warps,
|
|
||||||
"num_stages": 4,
|
|
||||||
})
|
|
||||||
|
|
||||||
best_config = None
|
|
||||||
best_time_us = 1e20
|
|
||||||
|
|
||||||
for config in configs:
|
|
||||||
print(f'{tp_size=} {bs=}')
|
|
||||||
print(f'{config}')
|
|
||||||
# warmup
|
|
||||||
print(f'warming up')
|
|
||||||
try:
|
|
||||||
for _ in range(num_warmup_trials):
|
|
||||||
run_timing(
|
|
||||||
num_calls=num_calls,
|
|
||||||
bs=bs,
|
|
||||||
d_model=d_model,
|
|
||||||
num_total_experts=num_total_experts,
|
|
||||||
top_k=top_k,
|
|
||||||
tp_size=tp_size,
|
|
||||||
model_intermediate_size=model_intermediate_size,
|
|
||||||
method=method,
|
|
||||||
config=config,
|
|
||||||
)
|
|
||||||
except triton.runtime.autotuner.OutOfResources:
|
|
||||||
continue
|
|
||||||
|
|
||||||
# trial
|
|
||||||
print(f'benchmarking')
|
|
||||||
for _ in range(num_trials):
|
|
||||||
kernel_dur_ms = run_timing(
|
|
||||||
num_calls=num_calls,
|
|
||||||
bs=bs,
|
|
||||||
d_model=d_model,
|
|
||||||
num_total_experts=num_total_experts,
|
|
||||||
top_k=top_k,
|
|
||||||
tp_size=tp_size,
|
|
||||||
model_intermediate_size=model_intermediate_size,
|
|
||||||
method=method,
|
|
||||||
config=config,
|
|
||||||
)
|
|
||||||
|
|
||||||
kernel_dur_us = 1000 * kernel_dur_ms
|
|
||||||
model_dur_ms = kernel_dur_ms * num_layers
|
|
||||||
|
|
||||||
if kernel_dur_us < best_time_us:
|
|
||||||
best_config = config
|
|
||||||
best_time_us = kernel_dur_us
|
|
||||||
|
|
||||||
print(
|
|
||||||
f'{kernel_dur_us=:.1f} {model_dur_ms=:.1f} {bs=} {tp_size=} {top_k=} {num_total_experts=} {d_model=} {model_intermediate_size=} {num_layers=}'
|
|
||||||
)
|
|
||||||
|
|
||||||
print("best_time_us", best_time_us)
|
|
||||||
print("best_config", best_config)
|
|
||||||
|
|
||||||
filename = "/tmp/config.jsonl"
|
|
||||||
print(f"writing config to file {filename}")
|
|
||||||
with open(filename, "a") as f:
|
|
||||||
f.write(json.dumps({str(bs): best_config}) + "\n")
|
|
||||||
|
|
||||||
|
|
||||||
def run_timing(num_calls: int, bs: int, d_model: int, num_total_experts: int,
|
|
||||||
top_k: int, tp_size: int, model_intermediate_size: int, method,
|
|
||||||
config) -> float:
|
|
||||||
shard_intermediate_size = model_intermediate_size // tp_size
|
|
||||||
|
|
||||||
hidden_states = torch.rand(
|
|
||||||
(bs, d_model),
|
|
||||||
device="cuda:0",
|
|
||||||
dtype=torch.bfloat16,
|
|
||||||
)
|
|
||||||
|
|
||||||
ws = torch.rand(
|
|
||||||
(num_total_experts, 2 * shard_intermediate_size, d_model),
|
|
||||||
device=hidden_states.device,
|
|
||||||
dtype=hidden_states.dtype,
|
|
||||||
)
|
|
||||||
|
|
||||||
w2s = torch.rand(
|
|
||||||
(num_total_experts, d_model, shard_intermediate_size),
|
|
||||||
device=hidden_states.device,
|
|
||||||
dtype=hidden_states.dtype,
|
|
||||||
)
|
|
||||||
|
|
||||||
gating_output = F.softmax(torch.rand(
|
|
||||||
(num_calls, bs, num_total_experts),
|
|
||||||
device=hidden_states.device,
|
|
||||||
dtype=torch.float32,
|
|
||||||
),
|
|
||||||
dim=-1)
|
|
||||||
|
|
||||||
start_event = torch.cuda.Event(enable_timing=True)
|
|
||||||
end_event = torch.cuda.Event(enable_timing=True)
|
|
||||||
|
|
||||||
start_event.record()
|
|
||||||
for i in range(num_calls):
|
|
||||||
hidden_states = method(
|
|
||||||
hidden_states=hidden_states,
|
|
||||||
w1=ws,
|
|
||||||
w2=w2s,
|
|
||||||
gating_output=gating_output[i],
|
|
||||||
topk=2,
|
|
||||||
renormalize=True,
|
|
||||||
inplace=True,
|
|
||||||
override_config=config,
|
|
||||||
)
|
|
||||||
end_event.record()
|
|
||||||
end_event.synchronize()
|
|
||||||
|
|
||||||
dur_ms = start_event.elapsed_time(end_event) / num_calls
|
|
||||||
return dur_ms
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main())
|
|
||||||
333
benchmarks/kernels/benchmark_moe.py
Normal file
333
benchmarks/kernels/benchmark_moe.py
Normal file
@ -0,0 +1,333 @@
|
|||||||
|
import argparse
|
||||||
|
import time
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any, Dict, List, Tuple, TypedDict
|
||||||
|
|
||||||
|
import ray
|
||||||
|
import torch
|
||||||
|
import triton
|
||||||
|
from ray.experimental.tqdm_ray import tqdm
|
||||||
|
from transformers import AutoConfig
|
||||||
|
|
||||||
|
from vllm.model_executor.layers.fused_moe.fused_moe import *
|
||||||
|
from vllm.utils import FlexibleArgumentParser
|
||||||
|
|
||||||
|
|
||||||
|
class BenchmarkConfig(TypedDict):
|
||||||
|
BLOCK_SIZE_M: int
|
||||||
|
BLOCK_SIZE_N: int
|
||||||
|
BLOCK_SIZE_K: int
|
||||||
|
GROUP_SIZE_M: int
|
||||||
|
num_warps: int
|
||||||
|
num_stages: int
|
||||||
|
|
||||||
|
|
||||||
|
def benchmark_config(
|
||||||
|
config: BenchmarkConfig,
|
||||||
|
num_tokens: int,
|
||||||
|
num_experts: int,
|
||||||
|
shard_intermediate_size: int,
|
||||||
|
hidden_size: int,
|
||||||
|
topk: int,
|
||||||
|
dtype: torch.dtype,
|
||||||
|
use_fp8: bool,
|
||||||
|
num_iters: int = 100,
|
||||||
|
) -> float:
|
||||||
|
init_dtype = torch.float16 if use_fp8 else dtype
|
||||||
|
x = torch.randn(num_tokens, hidden_size, dtype=dtype)
|
||||||
|
w1 = torch.randn(num_experts,
|
||||||
|
shard_intermediate_size,
|
||||||
|
hidden_size,
|
||||||
|
dtype=init_dtype)
|
||||||
|
w2 = torch.randn(num_experts,
|
||||||
|
hidden_size,
|
||||||
|
shard_intermediate_size // 2,
|
||||||
|
dtype=init_dtype)
|
||||||
|
gating_output = torch.randn(num_iters,
|
||||||
|
num_tokens,
|
||||||
|
num_experts,
|
||||||
|
dtype=torch.float32)
|
||||||
|
|
||||||
|
w1_scale = None
|
||||||
|
w2_scale = None
|
||||||
|
a1_scale = None
|
||||||
|
a2_scale = None
|
||||||
|
if use_fp8:
|
||||||
|
w1_scale = torch.randn(num_experts, dtype=torch.float32)
|
||||||
|
w2_scale = torch.randn(num_experts, dtype=torch.float32)
|
||||||
|
a1_scale = torch.randn(1, dtype=torch.float32)
|
||||||
|
a2_scale = torch.randn(1, dtype=torch.float32)
|
||||||
|
|
||||||
|
w1 = w1.to(torch.float8_e4m3fn)
|
||||||
|
w2 = w2.to(torch.float8_e4m3fn)
|
||||||
|
|
||||||
|
input_gating = torch.empty(num_tokens, num_experts, dtype=torch.float32)
|
||||||
|
|
||||||
|
def prepare(i: int):
|
||||||
|
input_gating.copy_(gating_output[i])
|
||||||
|
|
||||||
|
def run():
|
||||||
|
fused_moe(
|
||||||
|
x,
|
||||||
|
w1,
|
||||||
|
w2,
|
||||||
|
input_gating,
|
||||||
|
topk,
|
||||||
|
renormalize=True,
|
||||||
|
inplace=True,
|
||||||
|
override_config=config,
|
||||||
|
use_fp8=use_fp8,
|
||||||
|
w1_scale=w1_scale,
|
||||||
|
w2_scale=w2_scale,
|
||||||
|
a1_scale=a1_scale,
|
||||||
|
a2_scale=a2_scale,
|
||||||
|
)
|
||||||
|
|
||||||
|
# JIT compilation & warmup
|
||||||
|
run()
|
||||||
|
torch.cuda.synchronize()
|
||||||
|
|
||||||
|
# Capture 10 invocations with CUDA graph
|
||||||
|
graph = torch.cuda.CUDAGraph()
|
||||||
|
with torch.cuda.graph(graph):
|
||||||
|
for _ in range(10):
|
||||||
|
run()
|
||||||
|
torch.cuda.synchronize()
|
||||||
|
|
||||||
|
# Warmup
|
||||||
|
for _ in range(5):
|
||||||
|
graph.replay()
|
||||||
|
torch.cuda.synchronize()
|
||||||
|
|
||||||
|
start_event = torch.cuda.Event(enable_timing=True)
|
||||||
|
end_event = torch.cuda.Event(enable_timing=True)
|
||||||
|
|
||||||
|
latencies: List[float] = []
|
||||||
|
for i in range(num_iters):
|
||||||
|
prepare(i)
|
||||||
|
torch.cuda.synchronize()
|
||||||
|
|
||||||
|
start_event.record()
|
||||||
|
graph.replay()
|
||||||
|
end_event.record()
|
||||||
|
end_event.synchronize()
|
||||||
|
latencies.append(start_event.elapsed_time(end_event))
|
||||||
|
avg = sum(latencies) / (num_iters * 10) * 1000 # us
|
||||||
|
graph.reset()
|
||||||
|
return avg
|
||||||
|
|
||||||
|
|
||||||
|
def get_configs_compute_bound() -> List[Dict[str, int]]:
|
||||||
|
# Reduced search space for faster tuning.
|
||||||
|
# TODO(woosuk): Increase the search space and use a performance model to
|
||||||
|
# prune the search space.
|
||||||
|
configs: List[BenchmarkConfig] = []
|
||||||
|
for num_stages in [2, 3, 4, 5]:
|
||||||
|
for block_m in [16, 32, 64, 128, 256]:
|
||||||
|
for block_k in [64, 128, 256]:
|
||||||
|
for block_n in [32, 64, 128, 256]:
|
||||||
|
for num_warps in [4, 8]:
|
||||||
|
for group_size in [1, 16, 32, 64]:
|
||||||
|
configs.append({
|
||||||
|
"BLOCK_SIZE_M": block_m,
|
||||||
|
"BLOCK_SIZE_N": block_n,
|
||||||
|
"BLOCK_SIZE_K": block_k,
|
||||||
|
"GROUP_SIZE_M": group_size,
|
||||||
|
"num_warps": num_warps,
|
||||||
|
"num_stages": num_stages,
|
||||||
|
})
|
||||||
|
return configs
|
||||||
|
|
||||||
|
|
||||||
|
@ray.remote(num_gpus=1)
|
||||||
|
class BenchmarkWorker:
|
||||||
|
|
||||||
|
def __init__(self, seed: int) -> None:
|
||||||
|
torch.set_default_device("cuda")
|
||||||
|
torch.cuda.manual_seed_all(seed)
|
||||||
|
self.seed = seed
|
||||||
|
|
||||||
|
def benchmark(
|
||||||
|
self,
|
||||||
|
num_tokens: int,
|
||||||
|
num_experts: int,
|
||||||
|
shard_intermediate_size: int,
|
||||||
|
hidden_size: int,
|
||||||
|
topk: int,
|
||||||
|
dtype: torch.dtype,
|
||||||
|
use_fp8: bool,
|
||||||
|
) -> Tuple[Dict[str, int], float]:
|
||||||
|
torch.cuda.manual_seed_all(self.seed)
|
||||||
|
|
||||||
|
dtype_str = "float8" if use_fp8 else None
|
||||||
|
# NOTE(woosuk): The current naming convention uses w2.shape[2], which
|
||||||
|
# is the intermediate size after silu_and_mul.
|
||||||
|
op_config = get_moe_configs(num_experts, shard_intermediate_size // 2,
|
||||||
|
dtype_str)
|
||||||
|
if op_config is None:
|
||||||
|
config = get_default_config(num_tokens, num_experts,
|
||||||
|
shard_intermediate_size, hidden_size,
|
||||||
|
topk, dtype_str)
|
||||||
|
else:
|
||||||
|
config = op_config[min(op_config.keys(),
|
||||||
|
key=lambda x: abs(x - num_tokens))]
|
||||||
|
kernel_time = benchmark_config(config, num_tokens, num_experts,
|
||||||
|
shard_intermediate_size, hidden_size,
|
||||||
|
topk, dtype, use_fp8)
|
||||||
|
return config, kernel_time
|
||||||
|
|
||||||
|
def tune(
|
||||||
|
self,
|
||||||
|
num_tokens: int,
|
||||||
|
num_experts: int,
|
||||||
|
shard_intermediate_size: int,
|
||||||
|
hidden_size: int,
|
||||||
|
topk: int,
|
||||||
|
dtype: torch.dtype,
|
||||||
|
use_fp8: bool,
|
||||||
|
search_space: List[BenchmarkConfig],
|
||||||
|
) -> BenchmarkConfig:
|
||||||
|
best_config = None
|
||||||
|
best_time = float("inf")
|
||||||
|
for config in tqdm(search_space):
|
||||||
|
try:
|
||||||
|
kernel_time = benchmark_config(config,
|
||||||
|
num_tokens,
|
||||||
|
num_experts,
|
||||||
|
shard_intermediate_size,
|
||||||
|
hidden_size,
|
||||||
|
topk,
|
||||||
|
dtype,
|
||||||
|
use_fp8,
|
||||||
|
num_iters=10)
|
||||||
|
except triton.runtime.autotuner.OutOfResources:
|
||||||
|
# Some configurations may be invalid and fail to compile.
|
||||||
|
continue
|
||||||
|
|
||||||
|
if kernel_time < best_time:
|
||||||
|
best_time = kernel_time
|
||||||
|
best_config = config
|
||||||
|
now = datetime.now()
|
||||||
|
print(f"{now.ctime()}] Completed tuning for batch_size={num_tokens}")
|
||||||
|
assert best_config is not None
|
||||||
|
return best_config
|
||||||
|
|
||||||
|
|
||||||
|
def sort_config(config: BenchmarkConfig) -> BenchmarkConfig:
|
||||||
|
return {
|
||||||
|
"BLOCK_SIZE_M": config["BLOCK_SIZE_M"],
|
||||||
|
"BLOCK_SIZE_N": config["BLOCK_SIZE_N"],
|
||||||
|
"BLOCK_SIZE_K": config["BLOCK_SIZE_K"],
|
||||||
|
"GROUP_SIZE_M": config["GROUP_SIZE_M"],
|
||||||
|
"num_warps": config["num_warps"],
|
||||||
|
"num_stages": config["num_stages"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def save_configs(
|
||||||
|
configs: Dict[int, BenchmarkConfig],
|
||||||
|
num_experts: int,
|
||||||
|
shard_intermediate_size: int,
|
||||||
|
hidden_size: int,
|
||||||
|
topk: int,
|
||||||
|
dtype: torch.dtype,
|
||||||
|
use_fp8: bool,
|
||||||
|
) -> None:
|
||||||
|
dtype_str = "float8" if use_fp8 else None
|
||||||
|
# NOTE(woosuk): The current naming convention uses w2.shape[2], which
|
||||||
|
# is the intermediate size after silu_and_mul.
|
||||||
|
filename = get_config_file_name(num_experts, shard_intermediate_size // 2,
|
||||||
|
dtype_str)
|
||||||
|
print(f"Writing best config to {filename}...")
|
||||||
|
with open(filename, "w") as f:
|
||||||
|
json.dump(configs, f, indent=4)
|
||||||
|
f.write("\n")
|
||||||
|
|
||||||
|
|
||||||
|
def main(args: argparse.Namespace):
|
||||||
|
print(args)
|
||||||
|
|
||||||
|
config = AutoConfig.from_pretrained(args.model)
|
||||||
|
if config.architectures[0] == "DbrxForCausalLM":
|
||||||
|
E = config.ffn_config.moe_num_experts
|
||||||
|
topk = config.ffn_config.moe_top_k
|
||||||
|
intermediate_size = config.ffn_config.ffn_hidden_size
|
||||||
|
shard_intermediate_size = 2 * intermediate_size // args.tp_size
|
||||||
|
else:
|
||||||
|
# Default: Mixtral.
|
||||||
|
E = config.num_local_experts
|
||||||
|
topk = config.num_experts_per_tok
|
||||||
|
intermediate_size = config.intermediate_size
|
||||||
|
shard_intermediate_size = 2 * intermediate_size // args.tp_size
|
||||||
|
|
||||||
|
hidden_size = config.hidden_size
|
||||||
|
dtype = config.torch_dtype
|
||||||
|
use_fp8 = args.dtype == "fp8"
|
||||||
|
|
||||||
|
if args.batch_size is None:
|
||||||
|
batch_sizes = [
|
||||||
|
1, 2, 4, 8, 16, 24, 32, 48, 64, 96, 128, 256, 512, 1024, 1536,
|
||||||
|
2048, 3072, 4096
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
batch_sizes = [args.batch_size]
|
||||||
|
|
||||||
|
ray.init()
|
||||||
|
num_gpus = int(ray.available_resources()["GPU"])
|
||||||
|
workers = [BenchmarkWorker.remote(args.seed) for _ in range(num_gpus)]
|
||||||
|
|
||||||
|
def _distribute(method: str, inputs: List[Any]) -> List[Any]:
|
||||||
|
outputs = []
|
||||||
|
worker_idx = 0
|
||||||
|
for input_args in inputs:
|
||||||
|
worker = workers[worker_idx]
|
||||||
|
worker_method = getattr(worker, method)
|
||||||
|
output = worker_method.remote(*input_args)
|
||||||
|
outputs.append(output)
|
||||||
|
worker_idx = (worker_idx + 1) % num_gpus
|
||||||
|
return ray.get(outputs)
|
||||||
|
|
||||||
|
if args.tune:
|
||||||
|
search_space = get_configs_compute_bound()
|
||||||
|
print(f"Start tuning over {len(search_space)} configurations...")
|
||||||
|
|
||||||
|
start = time.time()
|
||||||
|
configs = _distribute(
|
||||||
|
"tune", [(batch_size, E, shard_intermediate_size, hidden_size,
|
||||||
|
topk, dtype, use_fp8, search_space)
|
||||||
|
for batch_size in batch_sizes])
|
||||||
|
best_configs = {
|
||||||
|
M: sort_config(config)
|
||||||
|
for M, config in zip(batch_sizes, configs)
|
||||||
|
}
|
||||||
|
save_configs(best_configs, E, shard_intermediate_size, hidden_size,
|
||||||
|
topk, dtype, use_fp8)
|
||||||
|
end = time.time()
|
||||||
|
print(f"Tuning took {end - start:.2f} seconds")
|
||||||
|
else:
|
||||||
|
outputs = _distribute("benchmark",
|
||||||
|
[(batch_size, E, shard_intermediate_size,
|
||||||
|
hidden_size, topk, dtype, use_fp8)
|
||||||
|
for batch_size in batch_sizes])
|
||||||
|
|
||||||
|
for batch_size, (config, kernel_time) in zip(batch_sizes, outputs):
|
||||||
|
print(f"Batch size: {batch_size}, config: {config}")
|
||||||
|
print(f"Kernel time: {kernel_time:.2f} us")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
parser = FlexibleArgumentParser()
|
||||||
|
parser.add_argument("--model",
|
||||||
|
type=str,
|
||||||
|
default="mistralai/Mixtral-8x7B-Instruct-v0.1")
|
||||||
|
parser.add_argument("--tp-size", "-tp", type=int, default=2)
|
||||||
|
parser.add_argument("--dtype",
|
||||||
|
type=str,
|
||||||
|
choices=["auto", "fp8"],
|
||||||
|
default="auto")
|
||||||
|
parser.add_argument("--seed", type=int, default=0)
|
||||||
|
parser.add_argument("--batch-size", type=int, required=False)
|
||||||
|
parser.add_argument("--tune", action="store_true")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
main(args)
|
||||||
@ -1,12 +1,12 @@
|
|||||||
from typing import Optional
|
|
||||||
import argparse
|
|
||||||
import random
|
import random
|
||||||
import time
|
import time
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
|
|
||||||
from vllm.utils import STR_DTYPE_TO_TORCH_DTYPE, create_kv_caches_with_random
|
from vllm import _custom_ops as ops
|
||||||
from vllm._C import ops
|
from vllm.utils import (STR_DTYPE_TO_TORCH_DTYPE, FlexibleArgumentParser,
|
||||||
|
create_kv_caches_with_random)
|
||||||
|
|
||||||
NUM_BLOCKS = 1024
|
NUM_BLOCKS = 1024
|
||||||
PARTITION_SIZE = 512
|
PARTITION_SIZE = 512
|
||||||
@ -16,7 +16,7 @@ PARTITION_SIZE = 512
|
|||||||
def main(
|
def main(
|
||||||
version: str,
|
version: str,
|
||||||
num_seqs: int,
|
num_seqs: int,
|
||||||
context_len: int,
|
seq_len: int,
|
||||||
num_query_heads: int,
|
num_query_heads: int,
|
||||||
num_kv_heads: int,
|
num_kv_heads: int,
|
||||||
head_size: int,
|
head_size: int,
|
||||||
@ -48,20 +48,23 @@ def main(
|
|||||||
dtype=torch.float,
|
dtype=torch.float,
|
||||||
device=device)
|
device=device)
|
||||||
|
|
||||||
context_lens = [context_len for _ in range(num_seqs)]
|
seq_lens = [seq_len for _ in range(num_seqs)]
|
||||||
max_context_len = max(context_lens)
|
max_seq_len = max(seq_lens)
|
||||||
context_lens = torch.tensor(context_lens, dtype=torch.int, device=device)
|
seq_lens = torch.tensor(seq_lens, dtype=torch.int, device=device)
|
||||||
|
|
||||||
# Create the block tables.
|
# Create the block tables.
|
||||||
max_num_blocks_per_seq = (max_context_len + block_size - 1) // block_size
|
max_num_blocks_per_seq = (max_seq_len + block_size - 1) // block_size
|
||||||
block_tables = []
|
block_tables_lst: List[List[int]] = []
|
||||||
for _ in range(num_seqs):
|
for _ in range(num_seqs):
|
||||||
block_table = [
|
block_table = [
|
||||||
random.randint(0, NUM_BLOCKS - 1)
|
random.randint(0, NUM_BLOCKS - 1)
|
||||||
for _ in range(max_num_blocks_per_seq)
|
for _ in range(max_num_blocks_per_seq)
|
||||||
]
|
]
|
||||||
block_tables.append(block_table)
|
block_tables_lst.append(block_table)
|
||||||
block_tables = torch.tensor(block_tables, dtype=torch.int, device=device)
|
|
||||||
|
block_tables = torch.tensor(block_tables_lst,
|
||||||
|
dtype=torch.int,
|
||||||
|
device=device)
|
||||||
|
|
||||||
# Create the KV cache.
|
# Create the KV cache.
|
||||||
key_caches, value_caches = create_kv_caches_with_random(NUM_BLOCKS,
|
key_caches, value_caches = create_kv_caches_with_random(NUM_BLOCKS,
|
||||||
@ -77,8 +80,7 @@ def main(
|
|||||||
# Prepare for the paged attention kernel.
|
# Prepare for the paged attention kernel.
|
||||||
output = torch.empty_like(query)
|
output = torch.empty_like(query)
|
||||||
if version == "v2":
|
if version == "v2":
|
||||||
num_partitions = ((max_context_len + PARTITION_SIZE - 1) //
|
num_partitions = ((max_seq_len + PARTITION_SIZE - 1) // PARTITION_SIZE)
|
||||||
PARTITION_SIZE)
|
|
||||||
tmp_output = torch.empty(
|
tmp_output = torch.empty(
|
||||||
size=(num_seqs, num_query_heads, num_partitions, head_size),
|
size=(num_seqs, num_query_heads, num_partitions, head_size),
|
||||||
dtype=output.dtype,
|
dtype=output.dtype,
|
||||||
@ -97,6 +99,9 @@ def main(
|
|||||||
torch.cuda.cudart().cudaProfilerStart()
|
torch.cuda.cudart().cudaProfilerStart()
|
||||||
start_time = time.perf_counter()
|
start_time = time.perf_counter()
|
||||||
|
|
||||||
|
# Using default kv_scale
|
||||||
|
kv_scale = 1.0
|
||||||
|
|
||||||
for _ in range(num_iters):
|
for _ in range(num_iters):
|
||||||
if version == "v1":
|
if version == "v1":
|
||||||
ops.paged_attention_v1(
|
ops.paged_attention_v1(
|
||||||
@ -107,11 +112,12 @@ def main(
|
|||||||
num_kv_heads,
|
num_kv_heads,
|
||||||
scale,
|
scale,
|
||||||
block_tables,
|
block_tables,
|
||||||
context_lens,
|
seq_lens,
|
||||||
block_size,
|
block_size,
|
||||||
max_context_len,
|
max_seq_len,
|
||||||
alibi_slopes,
|
alibi_slopes,
|
||||||
kv_cache_dtype,
|
kv_cache_dtype,
|
||||||
|
kv_scale,
|
||||||
)
|
)
|
||||||
elif version == "v2":
|
elif version == "v2":
|
||||||
ops.paged_attention_v2(
|
ops.paged_attention_v2(
|
||||||
@ -125,11 +131,12 @@ def main(
|
|||||||
num_kv_heads,
|
num_kv_heads,
|
||||||
scale,
|
scale,
|
||||||
block_tables,
|
block_tables,
|
||||||
context_lens,
|
seq_lens,
|
||||||
block_size,
|
block_size,
|
||||||
max_context_len,
|
max_seq_len,
|
||||||
alibi_slopes,
|
alibi_slopes,
|
||||||
kv_cache_dtype,
|
kv_cache_dtype,
|
||||||
|
kv_scale,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
raise ValueError(f"Invalid version: {version}")
|
raise ValueError(f"Invalid version: {version}")
|
||||||
@ -154,19 +161,19 @@ def main(
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
parser = argparse.ArgumentParser(
|
parser = FlexibleArgumentParser(
|
||||||
description="Benchmark the paged attention kernel.")
|
description="Benchmark the paged attention kernel.")
|
||||||
parser.add_argument("--version",
|
parser.add_argument("--version",
|
||||||
type=str,
|
type=str,
|
||||||
choices=["v1", "v2"],
|
choices=["v1", "v2"],
|
||||||
default="v2")
|
default="v2")
|
||||||
parser.add_argument("--batch-size", type=int, default=8)
|
parser.add_argument("--batch-size", type=int, default=8)
|
||||||
parser.add_argument("--context-len", type=int, default=4096)
|
parser.add_argument("--seq-len", type=int, default=4096)
|
||||||
parser.add_argument("--num-query-heads", type=int, default=64)
|
parser.add_argument("--num-query-heads", type=int, default=64)
|
||||||
parser.add_argument("--num-kv-heads", type=int, default=8)
|
parser.add_argument("--num-kv-heads", type=int, default=8)
|
||||||
parser.add_argument("--head-size",
|
parser.add_argument("--head-size",
|
||||||
type=int,
|
type=int,
|
||||||
choices=[64, 80, 96, 112, 128, 256],
|
choices=[64, 80, 96, 112, 128, 192, 256],
|
||||||
default=128)
|
default=128)
|
||||||
parser.add_argument("--block-size", type=int, choices=[16, 32], default=16)
|
parser.add_argument("--block-size", type=int, choices=[16, 32], default=16)
|
||||||
parser.add_argument("--use-alibi", action="store_true")
|
parser.add_argument("--use-alibi", action="store_true")
|
||||||
@ -179,11 +186,11 @@ if __name__ == '__main__':
|
|||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--kv-cache-dtype",
|
"--kv-cache-dtype",
|
||||||
type=str,
|
type=str,
|
||||||
choices=["auto", "fp8_e5m2"],
|
choices=["auto", "fp8", "fp8_e5m2", "fp8_e4m3"],
|
||||||
default="auto",
|
default="auto",
|
||||||
help=
|
help="Data type for kv cache storage. If 'auto', will use model "
|
||||||
'Data type for kv cache storage. If "auto", will use model data type.')
|
"data type. CUDA 11.8+ supports fp8 (=fp8_e4m3) and fp8_e5m2. "
|
||||||
parser.add_argument("--device", type=str, choices=["cuda"], default="cuda")
|
"ROCm (AMD GPU) supports fp8 (=fp8_e4m3)")
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
print(args)
|
print(args)
|
||||||
|
|
||||||
@ -192,7 +199,7 @@ if __name__ == '__main__':
|
|||||||
main(
|
main(
|
||||||
version=args.version,
|
version=args.version,
|
||||||
num_seqs=args.batch_size,
|
num_seqs=args.batch_size,
|
||||||
context_len=args.context_len,
|
seq_len=args.seq_len,
|
||||||
num_query_heads=args.num_query_heads,
|
num_query_heads=args.num_query_heads,
|
||||||
num_kv_heads=args.num_kv_heads,
|
num_kv_heads=args.num_kv_heads,
|
||||||
head_size=args.head_size,
|
head_size=args.head_size,
|
||||||
|
|||||||
122
benchmarks/kernels/benchmark_rope.py
Normal file
122
benchmarks/kernels/benchmark_rope.py
Normal file
@ -0,0 +1,122 @@
|
|||||||
|
from itertools import accumulate
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
import nvtx
|
||||||
|
import torch
|
||||||
|
|
||||||
|
from vllm.model_executor.layers.rotary_embedding import (RotaryEmbedding,
|
||||||
|
get_rope)
|
||||||
|
from vllm.utils import FlexibleArgumentParser
|
||||||
|
|
||||||
|
|
||||||
|
def benchmark_rope_kernels_multi_lora(
|
||||||
|
is_neox_style: bool,
|
||||||
|
batch_size: int,
|
||||||
|
seq_len: int,
|
||||||
|
num_heads: int,
|
||||||
|
head_size: int,
|
||||||
|
rotary_dim: Optional[int],
|
||||||
|
dtype: torch.dtype,
|
||||||
|
seed: int,
|
||||||
|
device: str,
|
||||||
|
max_position: int = 8192,
|
||||||
|
base: int = 10000,
|
||||||
|
) -> None:
|
||||||
|
torch.random.manual_seed(seed)
|
||||||
|
if torch.cuda.is_available():
|
||||||
|
torch.cuda.manual_seed(seed)
|
||||||
|
torch.set_default_device(device)
|
||||||
|
if rotary_dim is None:
|
||||||
|
rotary_dim = head_size
|
||||||
|
# silulating serving 4 LoRAs
|
||||||
|
scaling_factors = [1, 2, 4, 8]
|
||||||
|
# batched RoPE can take multiple scaling factors
|
||||||
|
batched_rope = get_rope(head_size, rotary_dim, max_position, base,
|
||||||
|
is_neox_style, {
|
||||||
|
"type": "linear",
|
||||||
|
"factor": tuple(scaling_factors)
|
||||||
|
})
|
||||||
|
# non-batched RoPE takes only one scaling factor, we create multiple
|
||||||
|
# instances to simulate the same behavior
|
||||||
|
non_batched_ropes: List[RotaryEmbedding] = []
|
||||||
|
for scaling_factor in scaling_factors:
|
||||||
|
non_batched_ropes.append(
|
||||||
|
get_rope(head_size, rotary_dim, max_position, base, is_neox_style,
|
||||||
|
{
|
||||||
|
"type": "linear",
|
||||||
|
"factor": (scaling_factor, )
|
||||||
|
}))
|
||||||
|
|
||||||
|
positions = torch.randint(0, max_position, (batch_size, seq_len))
|
||||||
|
query = torch.randn(batch_size,
|
||||||
|
seq_len,
|
||||||
|
num_heads * head_size,
|
||||||
|
dtype=dtype)
|
||||||
|
key = torch.randn_like(query)
|
||||||
|
|
||||||
|
# create query offsets for batched RoPE, we concat multiple kv cache
|
||||||
|
# together and each query needs to find the right kv cache of its type
|
||||||
|
offset_map = torch.tensor(
|
||||||
|
list(
|
||||||
|
accumulate([0] + [
|
||||||
|
max_position * scaling_factor * 2
|
||||||
|
for scaling_factor in scaling_factors[:-1]
|
||||||
|
])))
|
||||||
|
query_types = torch.randint(0,
|
||||||
|
len(scaling_factors), (batch_size, seq_len),
|
||||||
|
device=device)
|
||||||
|
# map query types to offsets
|
||||||
|
query_offsets = offset_map[query_types]
|
||||||
|
# the kernel takes flattened offsets
|
||||||
|
flatten_offsets = query_offsets.flatten()
|
||||||
|
|
||||||
|
# batched queries of the same type together for non-batched RoPE
|
||||||
|
queries = [query[query_types == i] for i in range(len(scaling_factors))]
|
||||||
|
keys = [key[query_types == i] for i in range(len(scaling_factors))]
|
||||||
|
packed_qkr = zip(queries, keys, non_batched_ropes)
|
||||||
|
# synchronize before start timing
|
||||||
|
torch.cuda.synchronize()
|
||||||
|
with nvtx.annotate("non-batched", color="yellow"):
|
||||||
|
for q, k, r in packed_qkr:
|
||||||
|
r.forward(positions, q, k)
|
||||||
|
torch.cuda.synchronize()
|
||||||
|
with nvtx.annotate("batched", color="green"):
|
||||||
|
batched_rope.forward(positions, query, key, flatten_offsets)
|
||||||
|
torch.cuda.synchronize()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
parser = FlexibleArgumentParser(
|
||||||
|
description="Benchmark the rotary embedding kernels.")
|
||||||
|
parser.add_argument("--is-neox-style", type=bool, default=True)
|
||||||
|
parser.add_argument("--batch-size", type=int, default=16)
|
||||||
|
parser.add_argument("--seq-len", type=int, default=512)
|
||||||
|
parser.add_argument("--num-heads", type=int, default=8)
|
||||||
|
parser.add_argument("--head-size",
|
||||||
|
type=int,
|
||||||
|
choices=[64, 80, 96, 112, 128, 192, 256],
|
||||||
|
default=128)
|
||||||
|
parser.add_argument("--rotary-dim", type=int, choices=[16, 32], default=32)
|
||||||
|
parser.add_argument("--dtype",
|
||||||
|
type=str,
|
||||||
|
choices=["bfloat16", "float"],
|
||||||
|
default="float")
|
||||||
|
parser.add_argument("--seed", type=int, default=0)
|
||||||
|
parser.add_argument("--device",
|
||||||
|
type=str,
|
||||||
|
choices=["cuda:0", "cuda:1"],
|
||||||
|
default="cuda:0")
|
||||||
|
args = parser.parse_args()
|
||||||
|
print(args)
|
||||||
|
|
||||||
|
benchmark_rope_kernels_multi_lora(
|
||||||
|
is_neox_style=args.is_neox_style,
|
||||||
|
batch_size=args.batch_size,
|
||||||
|
seq_len=args.seq_len,
|
||||||
|
num_heads=args.num_heads,
|
||||||
|
head_size=args.head_size,
|
||||||
|
rotary_dim=args.rotary_dim,
|
||||||
|
dtype=getattr(torch, args.dtype),
|
||||||
|
seed=args.seed,
|
||||||
|
device=args.device,
|
||||||
|
)
|
||||||
75
benchmarks/kernels/benchmark_shapes.py
Normal file
75
benchmarks/kernels/benchmark_shapes.py
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
WEIGHT_SHAPES = {
|
||||||
|
"ideal": [[4 * 256 * 32, 256 * 32]],
|
||||||
|
"mistralai/Mistral-7B-v0.1/TP1": [
|
||||||
|
[4096, 6144],
|
||||||
|
[4096, 4096],
|
||||||
|
[4096, 28672],
|
||||||
|
[14336, 4096],
|
||||||
|
],
|
||||||
|
"mistralai/Mistral-7B-v0.1/TP2": [
|
||||||
|
[4096, 3072],
|
||||||
|
[2048, 4096],
|
||||||
|
[4096, 14336],
|
||||||
|
[7168, 4096],
|
||||||
|
],
|
||||||
|
"mistralai/Mistral-7B-v0.1/TP4": [
|
||||||
|
[4096, 1536],
|
||||||
|
[1024, 4096],
|
||||||
|
[4096, 7168],
|
||||||
|
[3584, 4096],
|
||||||
|
],
|
||||||
|
"meta-llama/Llama-2-7b-hf/TP1": [
|
||||||
|
[4096, 12288],
|
||||||
|
[4096, 4096],
|
||||||
|
[4096, 22016],
|
||||||
|
[11008, 4096],
|
||||||
|
],
|
||||||
|
"meta-llama/Llama-2-7b-hf/TP2": [
|
||||||
|
[4096, 6144],
|
||||||
|
[2048, 4096],
|
||||||
|
[4096, 11008],
|
||||||
|
[5504, 4096],
|
||||||
|
],
|
||||||
|
"meta-llama/Llama-2-7b-hf/TP4": [
|
||||||
|
[4096, 3072],
|
||||||
|
[1024, 4096],
|
||||||
|
[4096, 5504],
|
||||||
|
[2752, 4096],
|
||||||
|
],
|
||||||
|
"meta-llama/Llama-2-13b-hf/TP1": [
|
||||||
|
[5120, 15360],
|
||||||
|
[5120, 5120],
|
||||||
|
[5120, 27648],
|
||||||
|
[13824, 5120],
|
||||||
|
],
|
||||||
|
"meta-llama/Llama-2-13b-hf/TP2": [
|
||||||
|
[5120, 7680],
|
||||||
|
[2560, 5120],
|
||||||
|
[5120, 13824],
|
||||||
|
[6912, 5120],
|
||||||
|
],
|
||||||
|
"meta-llama/Llama-2-13b-hf/TP4": [
|
||||||
|
[5120, 3840],
|
||||||
|
[1280, 5120],
|
||||||
|
[5120, 6912],
|
||||||
|
[3456, 5120],
|
||||||
|
],
|
||||||
|
"meta-llama/Llama-2-70b-hf/TP1": [
|
||||||
|
[8192, 10240],
|
||||||
|
[8192, 8192],
|
||||||
|
[8192, 57344],
|
||||||
|
[28672, 8192],
|
||||||
|
],
|
||||||
|
"meta-llama/Llama-2-70b-hf/TP2": [
|
||||||
|
[8192, 5120],
|
||||||
|
[4096, 8192],
|
||||||
|
[8192, 28672],
|
||||||
|
[14336, 8192],
|
||||||
|
],
|
||||||
|
"meta-llama/Llama-2-70b-hf/TP4": [
|
||||||
|
[8192, 2560],
|
||||||
|
[2048, 8192],
|
||||||
|
[8192, 14336],
|
||||||
|
[7168, 8192],
|
||||||
|
],
|
||||||
|
}
|
||||||
@ -4,7 +4,7 @@ PORT=8000
|
|||||||
MODEL=$1
|
MODEL=$1
|
||||||
TOKENS=$2
|
TOKENS=$2
|
||||||
|
|
||||||
docker run --gpus all --shm-size 1g -p $PORT:80 \
|
docker run -e HF_TOKEN=$HF_TOKEN --gpus all --shm-size 1g -p $PORT:80 \
|
||||||
-v $PWD/data:/data \
|
-v $PWD/data:/data \
|
||||||
ghcr.io/huggingface/text-generation-inference:1.4.0 \
|
ghcr.io/huggingface/text-generation-inference:1.4.0 \
|
||||||
--model-id $MODEL \
|
--model-id $MODEL \
|
||||||
|
|||||||
63
benchmarks/overheads/benchmark_hashing.py
Normal file
63
benchmarks/overheads/benchmark_hashing.py
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
import cProfile
|
||||||
|
import pstats
|
||||||
|
|
||||||
|
from vllm import LLM, SamplingParams
|
||||||
|
from vllm.utils import FlexibleArgumentParser
|
||||||
|
|
||||||
|
# A very long prompt, total number of tokens is about 15k.
|
||||||
|
LONG_PROMPT = ["You are an expert in large language models, aren't you?"
|
||||||
|
] * 1000
|
||||||
|
LONG_PROMPT = ' '.join(LONG_PROMPT)
|
||||||
|
|
||||||
|
|
||||||
|
def main(args):
|
||||||
|
llm = LLM(
|
||||||
|
model=args.model,
|
||||||
|
enforce_eager=True,
|
||||||
|
enable_prefix_caching=True,
|
||||||
|
tensor_parallel_size=args.tensor_parallel_size,
|
||||||
|
use_v2_block_manager=args.use_v2_block_manager,
|
||||||
|
)
|
||||||
|
|
||||||
|
sampling_params = SamplingParams(temperature=0, max_tokens=args.output_len)
|
||||||
|
profiler = cProfile.Profile()
|
||||||
|
|
||||||
|
print("------warm up------")
|
||||||
|
for i in range(3):
|
||||||
|
output = llm.generate(LONG_PROMPT, sampling_params)
|
||||||
|
print(output[0].outputs[0].text)
|
||||||
|
|
||||||
|
print("------start generating------")
|
||||||
|
for i in range(3):
|
||||||
|
profiler.runctx('llm.generate(LONG_PROMPT, sampling_params)',
|
||||||
|
globals(), locals())
|
||||||
|
|
||||||
|
# analyze the runtime of hashing function
|
||||||
|
stats = pstats.Stats(profiler)
|
||||||
|
stats.sort_stats('cumulative')
|
||||||
|
total_time = 0
|
||||||
|
total_calls = 0
|
||||||
|
for func in stats.stats:
|
||||||
|
if 'hash_of_block' in func[2]:
|
||||||
|
total_time = stats.stats[func][3]
|
||||||
|
total_calls = stats.stats[func][0]
|
||||||
|
percentage = (total_time / stats.total_tt) * 100
|
||||||
|
print(f"Hashing took {total_time:.2f} seconds,"
|
||||||
|
f"{percentage:.2f}% of the total runtime.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
parser = FlexibleArgumentParser(
|
||||||
|
description='Benchmark the performance of hashing function in'
|
||||||
|
'automatic prefix caching.')
|
||||||
|
parser.add_argument('--model', type=str, default='lmsys/longchat-7b-16k')
|
||||||
|
parser.add_argument('--tensor-parallel-size', '-tp', type=int, default=1)
|
||||||
|
parser.add_argument('--output-len', type=int, default=10)
|
||||||
|
parser.add_argument('--enable-prefix-caching',
|
||||||
|
action='store_true',
|
||||||
|
help='enable prefix caching')
|
||||||
|
parser.add_argument('--use-v2-block-manager',
|
||||||
|
action='store_true',
|
||||||
|
help='Use BlockSpaceMangerV2')
|
||||||
|
args = parser.parse_args()
|
||||||
|
main(args)
|
||||||
518
benchmarks/sonnet.txt
Normal file
518
benchmarks/sonnet.txt
Normal file
@ -0,0 +1,518 @@
|
|||||||
|
FROM fairest creatures we desire increase,
|
||||||
|
That thereby beauty's rose might never die,
|
||||||
|
But as the riper should by time decease,
|
||||||
|
His tender heir might bear his memory:
|
||||||
|
But thou, contracted to thine own bright eyes,
|
||||||
|
Feed'st thy light'st flame with self-substantial fuel,
|
||||||
|
Making a famine where abundance lies,
|
||||||
|
Thyself thy foe, to thy sweet self too cruel.
|
||||||
|
Thou that art now the world's fresh ornament
|
||||||
|
And only herald to the gaudy spring,
|
||||||
|
Within thine own bud buriest thy content
|
||||||
|
And, tender churl, makest waste in niggarding.
|
||||||
|
Pity the world, or else this glutton be,
|
||||||
|
To eat the world's due, by the grave and thee.
|
||||||
|
When forty winters shall beseige thy brow,
|
||||||
|
And dig deep trenches in thy beauty's field,
|
||||||
|
Thy youth's proud livery, so gazed on now,
|
||||||
|
Will be a tatter'd weed, of small worth held:
|
||||||
|
Then being ask'd where all thy beauty lies,
|
||||||
|
Where all the treasure of thy lusty days,
|
||||||
|
To say, within thine own deep-sunken eyes,
|
||||||
|
Were an all-eating shame and thriftless praise.
|
||||||
|
How much more praise deserved thy beauty's use,
|
||||||
|
If thou couldst answer 'This fair child of mine
|
||||||
|
Shall sum my count and make my old excuse,'
|
||||||
|
Proving his beauty by succession thine!
|
||||||
|
This were to be new made when thou art old,
|
||||||
|
And see thy blood warm when thou feel'st it cold.
|
||||||
|
Look in thy glass, and tell the face thou viewest
|
||||||
|
Now is the time that face should form another;
|
||||||
|
Whose fresh repair if now thou not renewest,
|
||||||
|
Thou dost beguile the world, unbless some mother.
|
||||||
|
For where is she so fair whose unear'd womb
|
||||||
|
Disdains the tillage of thy husbandry?
|
||||||
|
Or who is he so fond will be the tomb
|
||||||
|
Of his self-love, to stop posterity?
|
||||||
|
Thou art thy mother's glass, and she in thee
|
||||||
|
Calls back the lovely April of her prime:
|
||||||
|
So thou through windows of thine age shall see
|
||||||
|
Despite of wrinkles this thy golden time.
|
||||||
|
But if thou live, remember'd not to be,
|
||||||
|
Die single, and thine image dies with thee.
|
||||||
|
Unthrifty loveliness, why dost thou spend
|
||||||
|
Upon thyself thy beauty's legacy?
|
||||||
|
Nature's bequest gives nothing but doth lend,
|
||||||
|
And being frank she lends to those are free.
|
||||||
|
Then, beauteous niggard, why dost thou abuse
|
||||||
|
The bounteous largess given thee to give?
|
||||||
|
Profitless usurer, why dost thou use
|
||||||
|
So great a sum of sums, yet canst not live?
|
||||||
|
For having traffic with thyself alone,
|
||||||
|
Thou of thyself thy sweet self dost deceive.
|
||||||
|
Then how, when nature calls thee to be gone,
|
||||||
|
What acceptable audit canst thou leave?
|
||||||
|
Thy unused beauty must be tomb'd with thee,
|
||||||
|
Which, used, lives th' executor to be.
|
||||||
|
Those hours, that with gentle work did frame
|
||||||
|
The lovely gaze where every eye doth dwell,
|
||||||
|
Will play the tyrants to the very same
|
||||||
|
And that unfair which fairly doth excel:
|
||||||
|
For never-resting time leads summer on
|
||||||
|
To hideous winter and confounds him there;
|
||||||
|
Sap cheque'd with frost and lusty leaves quite gone,
|
||||||
|
Beauty o'ersnow'd and bareness every where:
|
||||||
|
Then, were not summer's distillation left,
|
||||||
|
A liquid prisoner pent in walls of glass,
|
||||||
|
Beauty's effect with beauty were bereft,
|
||||||
|
Nor it nor no remembrance what it was:
|
||||||
|
But flowers distill'd though they with winter meet,
|
||||||
|
Leese but their show; their substance still lives sweet.
|
||||||
|
Then let not winter's ragged hand deface
|
||||||
|
In thee thy summer, ere thou be distill'd:
|
||||||
|
Make sweet some vial; treasure thou some place
|
||||||
|
With beauty's treasure, ere it be self-kill'd.
|
||||||
|
That use is not forbidden usury,
|
||||||
|
Which happies those that pay the willing loan;
|
||||||
|
That's for thyself to breed another thee,
|
||||||
|
Or ten times happier, be it ten for one;
|
||||||
|
Ten times thyself were happier than thou art,
|
||||||
|
If ten of thine ten times refigured thee:
|
||||||
|
Then what could death do, if thou shouldst depart,
|
||||||
|
Leaving thee living in posterity?
|
||||||
|
Be not self-will'd, for thou art much too fair
|
||||||
|
To be death's conquest and make worms thine heir.
|
||||||
|
Lo! in the orient when the gracious light
|
||||||
|
Lifts up his burning head, each under eye
|
||||||
|
Doth homage to his new-appearing sight,
|
||||||
|
Serving with looks his sacred majesty;
|
||||||
|
And having climb'd the steep-up heavenly hill,
|
||||||
|
Resembling strong youth in his middle age,
|
||||||
|
yet mortal looks adore his beauty still,
|
||||||
|
Attending on his golden pilgrimage;
|
||||||
|
But when from highmost pitch, with weary car,
|
||||||
|
Like feeble age, he reeleth from the day,
|
||||||
|
The eyes, 'fore duteous, now converted are
|
||||||
|
From his low tract and look another way:
|
||||||
|
So thou, thyself out-going in thy noon,
|
||||||
|
Unlook'd on diest, unless thou get a son.
|
||||||
|
Music to hear, why hear'st thou music sadly?
|
||||||
|
Sweets with sweets war not, joy delights in joy.
|
||||||
|
Why lovest thou that which thou receivest not gladly,
|
||||||
|
Or else receivest with pleasure thine annoy?
|
||||||
|
If the true concord of well-tuned sounds,
|
||||||
|
By unions married, do offend thine ear,
|
||||||
|
They do but sweetly chide thee, who confounds
|
||||||
|
In singleness the parts that thou shouldst bear.
|
||||||
|
Mark how one string, sweet husband to another,
|
||||||
|
Strikes each in each by mutual ordering,
|
||||||
|
Resembling sire and child and happy mother
|
||||||
|
Who all in one, one pleasing note do sing:
|
||||||
|
Whose speechless song, being many, seeming one,
|
||||||
|
Sings this to thee: 'thou single wilt prove none.'
|
||||||
|
Is it for fear to wet a widow's eye
|
||||||
|
That thou consumest thyself in single life?
|
||||||
|
Ah! if thou issueless shalt hap to die.
|
||||||
|
The world will wail thee, like a makeless wife;
|
||||||
|
The world will be thy widow and still weep
|
||||||
|
That thou no form of thee hast left behind,
|
||||||
|
When every private widow well may keep
|
||||||
|
By children's eyes her husband's shape in mind.
|
||||||
|
Look, what an unthrift in the world doth spend
|
||||||
|
Shifts but his place, for still the world enjoys it;
|
||||||
|
But beauty's waste hath in the world an end,
|
||||||
|
And kept unused, the user so destroys it.
|
||||||
|
No love toward others in that bosom sits
|
||||||
|
That on himself such murderous shame commits.
|
||||||
|
For shame! deny that thou bear'st love to any,
|
||||||
|
Who for thyself art so unprovident.
|
||||||
|
Grant, if thou wilt, thou art beloved of many,
|
||||||
|
But that thou none lovest is most evident;
|
||||||
|
For thou art so possess'd with murderous hate
|
||||||
|
That 'gainst thyself thou stick'st not to conspire.
|
||||||
|
Seeking that beauteous roof to ruinate
|
||||||
|
Which to repair should be thy chief desire.
|
||||||
|
O, change thy thought, that I may change my mind!
|
||||||
|
Shall hate be fairer lodged than gentle love?
|
||||||
|
Be, as thy presence is, gracious and kind,
|
||||||
|
Or to thyself at least kind-hearted prove:
|
||||||
|
Make thee another self, for love of me,
|
||||||
|
That beauty still may live in thine or thee.
|
||||||
|
As fast as thou shalt wane, so fast thou growest
|
||||||
|
In one of thine, from that which thou departest;
|
||||||
|
And that fresh blood which youngly thou bestowest
|
||||||
|
Thou mayst call thine when thou from youth convertest.
|
||||||
|
Herein lives wisdom, beauty and increase:
|
||||||
|
Without this, folly, age and cold decay:
|
||||||
|
If all were minded so, the times should cease
|
||||||
|
And threescore year would make the world away.
|
||||||
|
Let those whom Nature hath not made for store,
|
||||||
|
Harsh featureless and rude, barrenly perish:
|
||||||
|
Look, whom she best endow'd she gave the more;
|
||||||
|
Which bounteous gift thou shouldst in bounty cherish:
|
||||||
|
She carved thee for her seal, and meant thereby
|
||||||
|
Thou shouldst print more, not let that copy die.
|
||||||
|
When I do count the clock that tells the time,
|
||||||
|
And see the brave day sunk in hideous night;
|
||||||
|
When I behold the violet past prime,
|
||||||
|
And sable curls all silver'd o'er with white;
|
||||||
|
When lofty trees I see barren of leaves
|
||||||
|
Which erst from heat did canopy the herd,
|
||||||
|
And summer's green all girded up in sheaves
|
||||||
|
Borne on the bier with white and bristly beard,
|
||||||
|
Then of thy beauty do I question make,
|
||||||
|
That thou among the wastes of time must go,
|
||||||
|
Since sweets and beauties do themselves forsake
|
||||||
|
And die as fast as they see others grow;
|
||||||
|
And nothing 'gainst Time's scythe can make defence
|
||||||
|
Save breed, to brave him when he takes thee hence.
|
||||||
|
O, that you were yourself! but, love, you are
|
||||||
|
No longer yours than you yourself here live:
|
||||||
|
Against this coming end you should prepare,
|
||||||
|
And your sweet semblance to some other give.
|
||||||
|
So should that beauty which you hold in lease
|
||||||
|
Find no determination: then you were
|
||||||
|
Yourself again after yourself's decease,
|
||||||
|
When your sweet issue your sweet form should bear.
|
||||||
|
Who lets so fair a house fall to decay,
|
||||||
|
Which husbandry in honour might uphold
|
||||||
|
Against the stormy gusts of winter's day
|
||||||
|
And barren rage of death's eternal cold?
|
||||||
|
O, none but unthrifts! Dear my love, you know
|
||||||
|
You had a father: let your son say so.
|
||||||
|
Not from the stars do I my judgment pluck;
|
||||||
|
And yet methinks I have astronomy,
|
||||||
|
But not to tell of good or evil luck,
|
||||||
|
Of plagues, of dearths, or seasons' quality;
|
||||||
|
Nor can I fortune to brief minutes tell,
|
||||||
|
Pointing to each his thunder, rain and wind,
|
||||||
|
Or say with princes if it shall go well,
|
||||||
|
By oft predict that I in heaven find:
|
||||||
|
But from thine eyes my knowledge I derive,
|
||||||
|
And, constant stars, in them I read such art
|
||||||
|
As truth and beauty shall together thrive,
|
||||||
|
If from thyself to store thou wouldst convert;
|
||||||
|
Or else of thee this I prognosticate:
|
||||||
|
Thy end is truth's and beauty's doom and date.
|
||||||
|
When I consider every thing that grows
|
||||||
|
Holds in perfection but a little moment,
|
||||||
|
That this huge stage presenteth nought but shows
|
||||||
|
Whereon the stars in secret influence comment;
|
||||||
|
When I perceive that men as plants increase,
|
||||||
|
Cheered and cheque'd even by the self-same sky,
|
||||||
|
Vaunt in their youthful sap, at height decrease,
|
||||||
|
And wear their brave state out of memory;
|
||||||
|
Then the conceit of this inconstant stay
|
||||||
|
Sets you most rich in youth before my sight,
|
||||||
|
Where wasteful Time debateth with Decay,
|
||||||
|
To change your day of youth to sullied night;
|
||||||
|
And all in war with Time for love of you,
|
||||||
|
As he takes from you, I engraft you new.
|
||||||
|
But wherefore do not you a mightier way
|
||||||
|
Make war upon this bloody tyrant, Time?
|
||||||
|
And fortify yourself in your decay
|
||||||
|
With means more blessed than my barren rhyme?
|
||||||
|
Now stand you on the top of happy hours,
|
||||||
|
And many maiden gardens yet unset
|
||||||
|
With virtuous wish would bear your living flowers,
|
||||||
|
Much liker than your painted counterfeit:
|
||||||
|
So should the lines of life that life repair,
|
||||||
|
Which this, Time's pencil, or my pupil pen,
|
||||||
|
Neither in inward worth nor outward fair,
|
||||||
|
Can make you live yourself in eyes of men.
|
||||||
|
To give away yourself keeps yourself still,
|
||||||
|
And you must live, drawn by your own sweet skill.
|
||||||
|
Who will believe my verse in time to come,
|
||||||
|
If it were fill'd with your most high deserts?
|
||||||
|
Though yet, heaven knows, it is but as a tomb
|
||||||
|
Which hides your life and shows not half your parts.
|
||||||
|
If I could write the beauty of your eyes
|
||||||
|
And in fresh numbers number all your graces,
|
||||||
|
The age to come would say 'This poet lies:
|
||||||
|
Such heavenly touches ne'er touch'd earthly faces.'
|
||||||
|
So should my papers yellow'd with their age
|
||||||
|
Be scorn'd like old men of less truth than tongue,
|
||||||
|
And your true rights be term'd a poet's rage
|
||||||
|
And stretched metre of an antique song:
|
||||||
|
But were some child of yours alive that time,
|
||||||
|
You should live twice; in it and in my rhyme.
|
||||||
|
Shall I compare thee to a summer's day?
|
||||||
|
Thou art more lovely and more temperate:
|
||||||
|
Rough winds do shake the darling buds of May,
|
||||||
|
And summer's lease hath all too short a date:
|
||||||
|
Sometime too hot the eye of heaven shines,
|
||||||
|
And often is his gold complexion dimm'd;
|
||||||
|
And every fair from fair sometime declines,
|
||||||
|
By chance or nature's changing course untrimm'd;
|
||||||
|
But thy eternal summer shall not fade
|
||||||
|
Nor lose possession of that fair thou owest;
|
||||||
|
Nor shall Death brag thou wander'st in his shade,
|
||||||
|
When in eternal lines to time thou growest:
|
||||||
|
So long as men can breathe or eyes can see,
|
||||||
|
So long lives this and this gives life to thee.
|
||||||
|
Devouring Time, blunt thou the lion's paws,
|
||||||
|
And make the earth devour her own sweet brood;
|
||||||
|
Pluck the keen teeth from the fierce tiger's jaws,
|
||||||
|
And burn the long-lived phoenix in her blood;
|
||||||
|
Make glad and sorry seasons as thou fleets,
|
||||||
|
And do whate'er thou wilt, swift-footed Time,
|
||||||
|
To the wide world and all her fading sweets;
|
||||||
|
But I forbid thee one most heinous crime:
|
||||||
|
O, carve not with thy hours my love's fair brow,
|
||||||
|
Nor draw no lines there with thine antique pen;
|
||||||
|
Him in thy course untainted do allow
|
||||||
|
For beauty's pattern to succeeding men.
|
||||||
|
Yet, do thy worst, old Time: despite thy wrong,
|
||||||
|
My love shall in my verse ever live young.
|
||||||
|
A woman's face with Nature's own hand painted
|
||||||
|
Hast thou, the master-mistress of my passion;
|
||||||
|
A woman's gentle heart, but not acquainted
|
||||||
|
With shifting change, as is false women's fashion;
|
||||||
|
An eye more bright than theirs, less false in rolling,
|
||||||
|
Gilding the object whereupon it gazeth;
|
||||||
|
A man in hue, all 'hues' in his controlling,
|
||||||
|
Much steals men's eyes and women's souls amazeth.
|
||||||
|
And for a woman wert thou first created;
|
||||||
|
Till Nature, as she wrought thee, fell a-doting,
|
||||||
|
And by addition me of thee defeated,
|
||||||
|
By adding one thing to my purpose nothing.
|
||||||
|
But since she prick'd thee out for women's pleasure,
|
||||||
|
Mine be thy love and thy love's use their treasure.
|
||||||
|
So is it not with me as with that Muse
|
||||||
|
Stirr'd by a painted beauty to his verse,
|
||||||
|
Who heaven itself for ornament doth use
|
||||||
|
And every fair with his fair doth rehearse
|
||||||
|
Making a couplement of proud compare,
|
||||||
|
With sun and moon, with earth and sea's rich gems,
|
||||||
|
With April's first-born flowers, and all things rare
|
||||||
|
That heaven's air in this huge rondure hems.
|
||||||
|
O' let me, true in love, but truly write,
|
||||||
|
And then believe me, my love is as fair
|
||||||
|
As any mother's child, though not so bright
|
||||||
|
As those gold candles fix'd in heaven's air:
|
||||||
|
Let them say more than like of hearsay well;
|
||||||
|
I will not praise that purpose not to sell.
|
||||||
|
My glass shall not persuade me I am old,
|
||||||
|
So long as youth and thou are of one date;
|
||||||
|
But when in thee time's furrows I behold,
|
||||||
|
Then look I death my days should expiate.
|
||||||
|
For all that beauty that doth cover thee
|
||||||
|
Is but the seemly raiment of my heart,
|
||||||
|
Which in thy breast doth live, as thine in me:
|
||||||
|
How can I then be elder than thou art?
|
||||||
|
O, therefore, love, be of thyself so wary
|
||||||
|
As I, not for myself, but for thee will;
|
||||||
|
Bearing thy heart, which I will keep so chary
|
||||||
|
As tender nurse her babe from faring ill.
|
||||||
|
Presume not on thy heart when mine is slain;
|
||||||
|
Thou gavest me thine, not to give back again.
|
||||||
|
As an unperfect actor on the stage
|
||||||
|
Who with his fear is put besides his part,
|
||||||
|
Or some fierce thing replete with too much rage,
|
||||||
|
Whose strength's abundance weakens his own heart.
|
||||||
|
So I, for fear of trust, forget to say
|
||||||
|
The perfect ceremony of love's rite,
|
||||||
|
And in mine own love's strength seem to decay,
|
||||||
|
O'ercharged with burden of mine own love's might.
|
||||||
|
O, let my books be then the eloquence
|
||||||
|
And dumb presagers of my speaking breast,
|
||||||
|
Who plead for love and look for recompense
|
||||||
|
More than that tongue that more hath more express'd.
|
||||||
|
O, learn to read what silent love hath writ:
|
||||||
|
To hear with eyes belongs to love's fine wit.
|
||||||
|
Mine eye hath play'd the painter and hath stell'd
|
||||||
|
Thy beauty's form in table of my heart;
|
||||||
|
My body is the frame wherein 'tis held,
|
||||||
|
And perspective it is the painter's art.
|
||||||
|
For through the painter must you see his skill,
|
||||||
|
To find where your true image pictured lies;
|
||||||
|
Which in my bosom's shop is hanging still,
|
||||||
|
That hath his windows glazed with thine eyes.
|
||||||
|
Now see what good turns eyes for eyes have done:
|
||||||
|
Mine eyes have drawn thy shape, and thine for me
|
||||||
|
Are windows to my breast, where-through the sun
|
||||||
|
Delights to peep, to gaze therein on thee;
|
||||||
|
Yet eyes this cunning want to grace their art;
|
||||||
|
They draw but what they see, know not the heart.
|
||||||
|
Let those who are in favour with their stars
|
||||||
|
Of public honour and proud titles boast,
|
||||||
|
Whilst I, whom fortune of such triumph bars,
|
||||||
|
Unlook'd for joy in that I honour most.
|
||||||
|
Great princes' favourites their fair leaves spread
|
||||||
|
But as the marigold at the sun's eye,
|
||||||
|
And in themselves their pride lies buried,
|
||||||
|
For at a frown they in their glory die.
|
||||||
|
The painful warrior famoused for fight,
|
||||||
|
After a thousand victories once foil'd,
|
||||||
|
Is from the book of honour razed quite,
|
||||||
|
And all the rest forgot for which he toil'd:
|
||||||
|
Then happy I, that love and am beloved
|
||||||
|
Where I may not remove nor be removed.
|
||||||
|
Lord of my love, to whom in vassalage
|
||||||
|
Thy merit hath my duty strongly knit,
|
||||||
|
To thee I send this written embassage,
|
||||||
|
To witness duty, not to show my wit:
|
||||||
|
Duty so great, which wit so poor as mine
|
||||||
|
May make seem bare, in wanting words to show it,
|
||||||
|
But that I hope some good conceit of thine
|
||||||
|
In thy soul's thought, all naked, will bestow it;
|
||||||
|
Till whatsoever star that guides my moving
|
||||||
|
Points on me graciously with fair aspect
|
||||||
|
And puts apparel on my tatter'd loving,
|
||||||
|
To show me worthy of thy sweet respect:
|
||||||
|
Then may I dare to boast how I do love thee;
|
||||||
|
Till then not show my head where thou mayst prove me.
|
||||||
|
Weary with toil, I haste me to my bed,
|
||||||
|
The dear repose for limbs with travel tired;
|
||||||
|
But then begins a journey in my head,
|
||||||
|
To work my mind, when body's work's expired:
|
||||||
|
For then my thoughts, from far where I abide,
|
||||||
|
Intend a zealous pilgrimage to thee,
|
||||||
|
And keep my drooping eyelids open wide,
|
||||||
|
Looking on darkness which the blind do see
|
||||||
|
Save that my soul's imaginary sight
|
||||||
|
Presents thy shadow to my sightless view,
|
||||||
|
Which, like a jewel hung in ghastly night,
|
||||||
|
Makes black night beauteous and her old face new.
|
||||||
|
Lo! thus, by day my limbs, by night my mind,
|
||||||
|
For thee and for myself no quiet find.
|
||||||
|
How can I then return in happy plight,
|
||||||
|
That am debarr'd the benefit of rest?
|
||||||
|
When day's oppression is not eased by night,
|
||||||
|
But day by night, and night by day, oppress'd?
|
||||||
|
And each, though enemies to either's reign,
|
||||||
|
Do in consent shake hands to torture me;
|
||||||
|
The one by toil, the other to complain
|
||||||
|
How far I toil, still farther off from thee.
|
||||||
|
I tell the day, to please them thou art bright
|
||||||
|
And dost him grace when clouds do blot the heaven:
|
||||||
|
So flatter I the swart-complexion'd night,
|
||||||
|
When sparkling stars twire not thou gild'st the even.
|
||||||
|
But day doth daily draw my sorrows longer
|
||||||
|
And night doth nightly make grief's strength seem stronger.
|
||||||
|
When, in disgrace with fortune and men's eyes,
|
||||||
|
I all alone beweep my outcast state
|
||||||
|
And trouble deal heaven with my bootless cries
|
||||||
|
And look upon myself and curse my fate,
|
||||||
|
Wishing me like to one more rich in hope,
|
||||||
|
Featured like him, like him with friends possess'd,
|
||||||
|
Desiring this man's art and that man's scope,
|
||||||
|
With what I most enjoy contented least;
|
||||||
|
Yet in these thoughts myself almost despising,
|
||||||
|
Haply I think on thee, and then my state,
|
||||||
|
Like to the lark at break of day arising
|
||||||
|
From sullen earth, sings hymns at heaven's gate;
|
||||||
|
For thy sweet love remember'd such wealth brings
|
||||||
|
That then I scorn to change my state with kings.
|
||||||
|
When to the sessions of sweet silent thought
|
||||||
|
I summon up remembrance of things past,
|
||||||
|
I sigh the lack of many a thing I sought,
|
||||||
|
And with old woes new wail my dear time's waste:
|
||||||
|
Then can I drown an eye, unused to flow,
|
||||||
|
For precious friends hid in death's dateless night,
|
||||||
|
And weep afresh love's long since cancell'd woe,
|
||||||
|
And moan the expense of many a vanish'd sight:
|
||||||
|
Then can I grieve at grievances foregone,
|
||||||
|
And heavily from woe to woe tell o'er
|
||||||
|
The sad account of fore-bemoaned moan,
|
||||||
|
Which I new pay as if not paid before.
|
||||||
|
But if the while I think on thee, dear friend,
|
||||||
|
All losses are restored and sorrows end.
|
||||||
|
Thy bosom is endeared with all hearts,
|
||||||
|
Which I by lacking have supposed dead,
|
||||||
|
And there reigns love and all love's loving parts,
|
||||||
|
And all those friends which I thought buried.
|
||||||
|
How many a holy and obsequious tear
|
||||||
|
Hath dear religious love stol'n from mine eye
|
||||||
|
As interest of the dead, which now appear
|
||||||
|
But things removed that hidden in thee lie!
|
||||||
|
Thou art the grave where buried love doth live,
|
||||||
|
Hung with the trophies of my lovers gone,
|
||||||
|
Who all their parts of me to thee did give;
|
||||||
|
That due of many now is thine alone:
|
||||||
|
Their images I loved I view in thee,
|
||||||
|
And thou, all they, hast all the all of me.
|
||||||
|
If thou survive my well-contented day,
|
||||||
|
When that churl Death my bones with dust shall cover,
|
||||||
|
And shalt by fortune once more re-survey
|
||||||
|
These poor rude lines of thy deceased lover,
|
||||||
|
Compare them with the bettering of the time,
|
||||||
|
And though they be outstripp'd by every pen,
|
||||||
|
Reserve them for my love, not for their rhyme,
|
||||||
|
Exceeded by the height of happier men.
|
||||||
|
O, then vouchsafe me but this loving thought:
|
||||||
|
'Had my friend's Muse grown with this growing age,
|
||||||
|
A dearer birth than this his love had brought,
|
||||||
|
To march in ranks of better equipage:
|
||||||
|
But since he died and poets better prove,
|
||||||
|
Theirs for their style I'll read, his for his love.'
|
||||||
|
Full many a glorious morning have I seen
|
||||||
|
Flatter the mountain-tops with sovereign eye,
|
||||||
|
Kissing with golden face the meadows green,
|
||||||
|
Gilding pale streams with heavenly alchemy;
|
||||||
|
Anon permit the basest clouds to ride
|
||||||
|
With ugly rack on his celestial face,
|
||||||
|
And from the forlorn world his visage hide,
|
||||||
|
Stealing unseen to west with this disgrace:
|
||||||
|
Even so my sun one early morn did shine
|
||||||
|
With all triumphant splendor on my brow;
|
||||||
|
But out, alack! he was but one hour mine;
|
||||||
|
The region cloud hath mask'd him from me now.
|
||||||
|
Yet him for this my love no whit disdaineth;
|
||||||
|
Suns of the world may stain when heaven's sun staineth.
|
||||||
|
Why didst thou promise such a beauteous day,
|
||||||
|
And make me travel forth without my cloak,
|
||||||
|
To let base clouds o'ertake me in my way,
|
||||||
|
Hiding thy bravery in their rotten smoke?
|
||||||
|
'Tis not enough that through the cloud thou break,
|
||||||
|
To dry the rain on my storm-beaten face,
|
||||||
|
For no man well of such a salve can speak
|
||||||
|
That heals the wound and cures not the disgrace:
|
||||||
|
Nor can thy shame give physic to my grief;
|
||||||
|
Though thou repent, yet I have still the loss:
|
||||||
|
The offender's sorrow lends but weak relief
|
||||||
|
To him that bears the strong offence's cross.
|
||||||
|
Ah! but those tears are pearl which thy love sheds,
|
||||||
|
And they are rich and ransom all ill deeds.
|
||||||
|
No more be grieved at that which thou hast done:
|
||||||
|
Roses have thorns, and silver fountains mud;
|
||||||
|
Clouds and eclipses stain both moon and sun,
|
||||||
|
And loathsome canker lives in sweetest bud.
|
||||||
|
All men make faults, and even I in this,
|
||||||
|
Authorizing thy trespass with compare,
|
||||||
|
Myself corrupting, salving thy amiss,
|
||||||
|
Excusing thy sins more than thy sins are;
|
||||||
|
For to thy sensual fault I bring in sense--
|
||||||
|
Thy adverse party is thy advocate--
|
||||||
|
And 'gainst myself a lawful plea commence:
|
||||||
|
Such civil war is in my love and hate
|
||||||
|
That I an accessary needs must be
|
||||||
|
To that sweet thief which sourly robs from me.
|
||||||
|
Let me confess that we two must be twain,
|
||||||
|
Although our undivided loves are one:
|
||||||
|
So shall those blots that do with me remain
|
||||||
|
Without thy help by me be borne alone.
|
||||||
|
In our two loves there is but one respect,
|
||||||
|
Though in our lives a separable spite,
|
||||||
|
Which though it alter not love's sole effect,
|
||||||
|
Yet doth it steal sweet hours from love's delight.
|
||||||
|
I may not evermore acknowledge thee,
|
||||||
|
Lest my bewailed guilt should do thee shame,
|
||||||
|
Nor thou with public kindness honour me,
|
||||||
|
Unless thou take that honour from thy name:
|
||||||
|
But do not so; I love thee in such sort
|
||||||
|
As, thou being mine, mine is thy good report.
|
||||||
|
As a decrepit father takes delight
|
||||||
|
To see his active child do deeds of youth,
|
||||||
|
So I, made lame by fortune's dearest spite,
|
||||||
|
Take all my comfort of thy worth and truth.
|
||||||
|
For whether beauty, birth, or wealth, or wit,
|
||||||
|
Or any of these all, or all, or more,
|
||||||
|
Entitled in thy parts do crowned sit,
|
||||||
|
I make my love engrafted to this store:
|
||||||
|
So then I am not lame, poor, nor despised,
|
||||||
|
Whilst that this shadow doth such substance give
|
||||||
|
That I in thy abundance am sufficed
|
||||||
|
And by a part of all thy glory live.
|
||||||
|
Look, what is best, that best I wish in thee:
|
||||||
|
This wish I have; then ten times happy me!
|
||||||
114
cmake/cpu_extension.cmake
Normal file
114
cmake/cpu_extension.cmake
Normal file
@ -0,0 +1,114 @@
|
|||||||
|
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||||
|
|
||||||
|
#
|
||||||
|
# Define environment variables for special configurations
|
||||||
|
#
|
||||||
|
if(DEFINED ENV{VLLM_CPU_AVX512BF16})
|
||||||
|
set(ENABLE_AVX512BF16 ON)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
include_directories("${CMAKE_SOURCE_DIR}/csrc")
|
||||||
|
|
||||||
|
#
|
||||||
|
# Check the compile flags
|
||||||
|
#
|
||||||
|
list(APPEND CXX_COMPILE_FLAGS
|
||||||
|
"-fopenmp"
|
||||||
|
"-DVLLM_CPU_EXTENSION")
|
||||||
|
|
||||||
|
execute_process(COMMAND cat /proc/cpuinfo
|
||||||
|
RESULT_VARIABLE CPUINFO_RET
|
||||||
|
OUTPUT_VARIABLE CPUINFO)
|
||||||
|
|
||||||
|
if (NOT CPUINFO_RET EQUAL 0)
|
||||||
|
message(FATAL_ERROR "Failed to check CPU features via /proc/cpuinfo")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
function (find_isa CPUINFO TARGET OUT)
|
||||||
|
string(FIND ${CPUINFO} ${TARGET} ISA_FOUND)
|
||||||
|
if(NOT ISA_FOUND EQUAL -1)
|
||||||
|
set(${OUT} ON PARENT_SCOPE)
|
||||||
|
else()
|
||||||
|
set(${OUT} OFF PARENT_SCOPE)
|
||||||
|
endif()
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
function (is_avx512_disabled OUT)
|
||||||
|
set(DISABLE_AVX512 $ENV{VLLM_CPU_DISABLE_AVX512})
|
||||||
|
if(DISABLE_AVX512 AND DISABLE_AVX512 STREQUAL "true")
|
||||||
|
set(${OUT} ON PARENT_SCOPE)
|
||||||
|
else()
|
||||||
|
set(${OUT} OFF PARENT_SCOPE)
|
||||||
|
endif()
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
is_avx512_disabled(AVX512_DISABLED)
|
||||||
|
|
||||||
|
find_isa(${CPUINFO} "avx2" AVX2_FOUND)
|
||||||
|
find_isa(${CPUINFO} "avx512f" AVX512_FOUND)
|
||||||
|
find_isa(${CPUINFO} "POWER10" POWER10_FOUND)
|
||||||
|
find_isa(${CPUINFO} "POWER9" POWER9_FOUND)
|
||||||
|
|
||||||
|
if (AVX512_FOUND AND NOT AVX512_DISABLED)
|
||||||
|
list(APPEND CXX_COMPILE_FLAGS
|
||||||
|
"-mavx512f"
|
||||||
|
"-mavx512vl"
|
||||||
|
"-mavx512bw"
|
||||||
|
"-mavx512dq")
|
||||||
|
|
||||||
|
find_isa(${CPUINFO} "avx512_bf16" AVX512BF16_FOUND)
|
||||||
|
if (AVX512BF16_FOUND OR ENABLE_AVX512BF16)
|
||||||
|
if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND
|
||||||
|
CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 12.3)
|
||||||
|
list(APPEND CXX_COMPILE_FLAGS "-mavx512bf16")
|
||||||
|
else()
|
||||||
|
message(WARNING "Disable AVX512-BF16 ISA support, requires gcc/g++ >= 12.3")
|
||||||
|
endif()
|
||||||
|
else()
|
||||||
|
message(WARNING "Disable AVX512-BF16 ISA support, no avx512_bf16 found in local CPU flags." " If cross-compilation is required, please set env VLLM_CPU_AVX512BF16=1.")
|
||||||
|
endif()
|
||||||
|
elseif (AVX2_FOUND)
|
||||||
|
list(APPEND CXX_COMPILE_FLAGS "-mavx2")
|
||||||
|
message(WARNING "vLLM CPU backend using AVX2 ISA")
|
||||||
|
elseif (POWER9_FOUND OR POWER10_FOUND)
|
||||||
|
message(STATUS "PowerPC detected")
|
||||||
|
# Check for PowerPC VSX support
|
||||||
|
list(APPEND CXX_COMPILE_FLAGS
|
||||||
|
"-mvsx"
|
||||||
|
"-mcpu=native"
|
||||||
|
"-mtune=native")
|
||||||
|
else()
|
||||||
|
message(FATAL_ERROR "vLLM CPU backend requires AVX512 or AVX2 or Power9+ ISA support.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
message(STATUS "CPU extension compile flags: ${CXX_COMPILE_FLAGS}")
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# Define extension targets
|
||||||
|
#
|
||||||
|
|
||||||
|
#
|
||||||
|
# _C extension
|
||||||
|
#
|
||||||
|
set(VLLM_EXT_SRC
|
||||||
|
"csrc/cpu/activation.cpp"
|
||||||
|
"csrc/cpu/attention.cpp"
|
||||||
|
"csrc/cpu/cache.cpp"
|
||||||
|
"csrc/cpu/layernorm.cpp"
|
||||||
|
"csrc/cpu/pos_encoding.cpp"
|
||||||
|
"csrc/cpu/torch_bindings.cpp")
|
||||||
|
|
||||||
|
define_gpu_extension_target(
|
||||||
|
_C
|
||||||
|
DESTINATION vllm
|
||||||
|
LANGUAGE CXX
|
||||||
|
SOURCES ${VLLM_EXT_SRC}
|
||||||
|
COMPILE_FLAGS ${CXX_COMPILE_FLAGS}
|
||||||
|
USE_SABI 3
|
||||||
|
WITH_SOABI
|
||||||
|
)
|
||||||
|
|
||||||
|
add_custom_target(default)
|
||||||
|
message(STATUS "Enabling C extension.")
|
||||||
|
add_dependencies(default _C)
|
||||||
73
cmake/hipify.py
Executable file
73
cmake/hipify.py
Executable file
@ -0,0 +1,73 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
#
|
||||||
|
# A command line tool for running pytorch's hipify preprocessor on CUDA
|
||||||
|
# source files.
|
||||||
|
#
|
||||||
|
# See https://github.com/ROCm/hipify_torch
|
||||||
|
# and <torch install dir>/utils/hipify/hipify_python.py
|
||||||
|
#
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
from torch.utils.hipify.hipify_python import hipify
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
|
||||||
|
# Project directory where all the source + include files live.
|
||||||
|
parser.add_argument(
|
||||||
|
"-p",
|
||||||
|
"--project_dir",
|
||||||
|
help="The project directory.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Directory where hipified files are written.
|
||||||
|
parser.add_argument(
|
||||||
|
"-o",
|
||||||
|
"--output_dir",
|
||||||
|
help="The output directory.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Source files to convert.
|
||||||
|
parser.add_argument("sources",
|
||||||
|
help="Source files to hipify.",
|
||||||
|
nargs="*",
|
||||||
|
default=[])
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
# Limit include scope to project_dir only
|
||||||
|
includes = [os.path.join(args.project_dir, '*')]
|
||||||
|
|
||||||
|
# Get absolute path for all source files.
|
||||||
|
extra_files = [os.path.abspath(s) for s in args.sources]
|
||||||
|
|
||||||
|
# Copy sources from project directory to output directory.
|
||||||
|
# The directory might already exist to hold object files so we ignore that.
|
||||||
|
shutil.copytree(args.project_dir, args.output_dir, dirs_exist_ok=True)
|
||||||
|
|
||||||
|
hipify_result = hipify(project_directory=args.project_dir,
|
||||||
|
output_directory=args.output_dir,
|
||||||
|
header_include_dirs=[],
|
||||||
|
includes=includes,
|
||||||
|
extra_files=extra_files,
|
||||||
|
show_detailed=True,
|
||||||
|
is_pytorch_extension=True,
|
||||||
|
hipify_extra_files_only=True)
|
||||||
|
|
||||||
|
hipified_sources = []
|
||||||
|
for source in args.sources:
|
||||||
|
s_abs = os.path.abspath(source)
|
||||||
|
hipified_s_abs = (hipify_result[s_abs].hipified_path if
|
||||||
|
(s_abs in hipify_result
|
||||||
|
and hipify_result[s_abs].hipified_path is not None)
|
||||||
|
else s_abs)
|
||||||
|
hipified_sources.append(hipified_s_abs)
|
||||||
|
|
||||||
|
assert (len(hipified_sources) == len(args.sources))
|
||||||
|
|
||||||
|
# Print hipified source files.
|
||||||
|
print("\n".join(hipified_sources))
|
||||||
366
cmake/utils.cmake
Normal file
366
cmake/utils.cmake
Normal file
@ -0,0 +1,366 @@
|
|||||||
|
#
|
||||||
|
# Attempt to find the python package that uses the same python executable as
|
||||||
|
# `EXECUTABLE` and is one of the `SUPPORTED_VERSIONS`.
|
||||||
|
#
|
||||||
|
macro (find_python_from_executable EXECUTABLE SUPPORTED_VERSIONS)
|
||||||
|
file(REAL_PATH ${EXECUTABLE} EXECUTABLE)
|
||||||
|
set(Python_EXECUTABLE ${EXECUTABLE})
|
||||||
|
find_package(Python COMPONENTS Interpreter Development.Module Development.SABIModule)
|
||||||
|
if (NOT Python_FOUND)
|
||||||
|
message(FATAL_ERROR "Unable to find python matching: ${EXECUTABLE}.")
|
||||||
|
endif()
|
||||||
|
set(_VER "${Python_VERSION_MAJOR}.${Python_VERSION_MINOR}")
|
||||||
|
set(_SUPPORTED_VERSIONS_LIST ${SUPPORTED_VERSIONS} ${ARGN})
|
||||||
|
if (NOT _VER IN_LIST _SUPPORTED_VERSIONS_LIST)
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"Python version (${_VER}) is not one of the supported versions: "
|
||||||
|
"${_SUPPORTED_VERSIONS_LIST}.")
|
||||||
|
endif()
|
||||||
|
message(STATUS "Found python matching: ${EXECUTABLE}.")
|
||||||
|
endmacro()
|
||||||
|
|
||||||
|
#
|
||||||
|
# Run `EXPR` in python. The standard output of python is stored in `OUT` and
|
||||||
|
# has trailing whitespace stripped. If an error is encountered when running
|
||||||
|
# python, a fatal message `ERR_MSG` is issued.
|
||||||
|
#
|
||||||
|
function (run_python OUT EXPR ERR_MSG)
|
||||||
|
execute_process(
|
||||||
|
COMMAND
|
||||||
|
"${Python_EXECUTABLE}" "-c" "${EXPR}"
|
||||||
|
OUTPUT_VARIABLE PYTHON_OUT
|
||||||
|
RESULT_VARIABLE PYTHON_ERROR_CODE
|
||||||
|
ERROR_VARIABLE PYTHON_STDERR
|
||||||
|
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||||
|
|
||||||
|
if(NOT PYTHON_ERROR_CODE EQUAL 0)
|
||||||
|
message(FATAL_ERROR "${ERR_MSG}: ${PYTHON_STDERR}")
|
||||||
|
endif()
|
||||||
|
set(${OUT} ${PYTHON_OUT} PARENT_SCOPE)
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
# Run `EXPR` in python after importing `PKG`. Use the result of this to extend
|
||||||
|
# `CMAKE_PREFIX_PATH` so the torch cmake configuration can be imported.
|
||||||
|
macro (append_cmake_prefix_path PKG EXPR)
|
||||||
|
run_python(_PREFIX_PATH
|
||||||
|
"import ${PKG}; print(${EXPR})" "Failed to locate ${PKG} path")
|
||||||
|
list(APPEND CMAKE_PREFIX_PATH ${_PREFIX_PATH})
|
||||||
|
endmacro()
|
||||||
|
|
||||||
|
#
|
||||||
|
# Add a target named `hipify${NAME}` that runs the hipify preprocessor on a set
|
||||||
|
# of CUDA source files. The names of the corresponding "hipified" sources are
|
||||||
|
# stored in `OUT_SRCS`.
|
||||||
|
#
|
||||||
|
function (hipify_sources_target OUT_SRCS NAME ORIG_SRCS)
|
||||||
|
#
|
||||||
|
# Split into C++ and non-C++ (i.e. CUDA) sources.
|
||||||
|
#
|
||||||
|
set(SRCS ${ORIG_SRCS})
|
||||||
|
set(CXX_SRCS ${ORIG_SRCS})
|
||||||
|
list(FILTER SRCS EXCLUDE REGEX "\.(cc)|(cpp)$")
|
||||||
|
list(FILTER CXX_SRCS INCLUDE REGEX "\.(cc)|(cpp)$")
|
||||||
|
|
||||||
|
#
|
||||||
|
# Generate ROCm/HIP source file names from CUDA file names.
|
||||||
|
# Since HIP files are generated code, they will appear in the build area
|
||||||
|
# `CMAKE_CURRENT_BINARY_DIR` directory rather than the original csrc dir.
|
||||||
|
#
|
||||||
|
set(HIP_SRCS)
|
||||||
|
foreach (SRC ${SRCS})
|
||||||
|
string(REGEX REPLACE "\.cu$" "\.hip" SRC ${SRC})
|
||||||
|
string(REGEX REPLACE "cuda" "hip" SRC ${SRC})
|
||||||
|
list(APPEND HIP_SRCS "${CMAKE_CURRENT_BINARY_DIR}/${SRC}")
|
||||||
|
endforeach()
|
||||||
|
|
||||||
|
set(CSRC_BUILD_DIR ${CMAKE_CURRENT_BINARY_DIR}/csrc)
|
||||||
|
add_custom_target(
|
||||||
|
hipify${NAME}
|
||||||
|
COMMAND ${CMAKE_SOURCE_DIR}/cmake/hipify.py -p ${CMAKE_SOURCE_DIR}/csrc -o ${CSRC_BUILD_DIR} ${SRCS}
|
||||||
|
DEPENDS ${CMAKE_SOURCE_DIR}/cmake/hipify.py ${SRCS}
|
||||||
|
BYPRODUCTS ${HIP_SRCS}
|
||||||
|
COMMENT "Running hipify on ${NAME} extension source files.")
|
||||||
|
|
||||||
|
# Swap out original extension sources with hipified sources.
|
||||||
|
list(APPEND HIP_SRCS ${CXX_SRCS})
|
||||||
|
set(${OUT_SRCS} ${HIP_SRCS} PARENT_SCOPE)
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
#
|
||||||
|
# Get additional GPU compiler flags from torch.
|
||||||
|
#
|
||||||
|
function (get_torch_gpu_compiler_flags OUT_GPU_FLAGS GPU_LANG)
|
||||||
|
if (${GPU_LANG} STREQUAL "CUDA")
|
||||||
|
#
|
||||||
|
# Get common NVCC flags from torch.
|
||||||
|
#
|
||||||
|
run_python(GPU_FLAGS
|
||||||
|
"from torch.utils.cpp_extension import COMMON_NVCC_FLAGS; print(';'.join(COMMON_NVCC_FLAGS))"
|
||||||
|
"Failed to determine torch nvcc compiler flags")
|
||||||
|
|
||||||
|
if (CUDA_VERSION VERSION_GREATER_EQUAL 11.8)
|
||||||
|
list(APPEND GPU_FLAGS "-DENABLE_FP8")
|
||||||
|
endif()
|
||||||
|
if (CUDA_VERSION VERSION_GREATER_EQUAL 12.0)
|
||||||
|
list(REMOVE_ITEM GPU_FLAGS
|
||||||
|
"-D__CUDA_NO_HALF_OPERATORS__"
|
||||||
|
"-D__CUDA_NO_HALF_CONVERSIONS__"
|
||||||
|
"-D__CUDA_NO_BFLOAT16_CONVERSIONS__"
|
||||||
|
"-D__CUDA_NO_HALF2_OPERATORS__")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
elseif(${GPU_LANG} STREQUAL "HIP")
|
||||||
|
#
|
||||||
|
# Get common HIP/HIPCC flags from torch.
|
||||||
|
#
|
||||||
|
run_python(GPU_FLAGS
|
||||||
|
"import torch.utils.cpp_extension as t; print(';'.join(t.COMMON_HIP_FLAGS + t.COMMON_HIPCC_FLAGS))"
|
||||||
|
"Failed to determine torch nvcc compiler flags")
|
||||||
|
|
||||||
|
list(APPEND GPU_FLAGS
|
||||||
|
"-DUSE_ROCM"
|
||||||
|
"-DENABLE_FP8"
|
||||||
|
"-U__HIP_NO_HALF_CONVERSIONS__"
|
||||||
|
"-U__HIP_NO_HALF_OPERATORS__"
|
||||||
|
"-fno-gpu-rdc")
|
||||||
|
|
||||||
|
endif()
|
||||||
|
set(${OUT_GPU_FLAGS} ${GPU_FLAGS} PARENT_SCOPE)
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
# Macro for converting a `gencode` version number to a cmake version number.
|
||||||
|
macro(string_to_ver OUT_VER IN_STR)
|
||||||
|
string(REGEX REPLACE "\([0-9]+\)\([0-9]\)" "\\1.\\2" ${OUT_VER} ${IN_STR})
|
||||||
|
endmacro()
|
||||||
|
|
||||||
|
#
|
||||||
|
# Override the GPU architectures detected by cmake/torch and filter them by
|
||||||
|
# `GPU_SUPPORTED_ARCHES`. Sets the final set of architectures in
|
||||||
|
# `GPU_ARCHES`.
|
||||||
|
#
|
||||||
|
# Note: this is defined as a macro since it updates `CMAKE_CUDA_FLAGS`.
|
||||||
|
#
|
||||||
|
macro(override_gpu_arches GPU_ARCHES GPU_LANG GPU_SUPPORTED_ARCHES)
|
||||||
|
set(_GPU_SUPPORTED_ARCHES_LIST ${GPU_SUPPORTED_ARCHES} ${ARGN})
|
||||||
|
message(STATUS "${GPU_LANG} supported arches: ${_GPU_SUPPORTED_ARCHES_LIST}")
|
||||||
|
|
||||||
|
if (${GPU_LANG} STREQUAL "HIP")
|
||||||
|
#
|
||||||
|
# `GPU_ARCHES` controls the `--offload-arch` flags.
|
||||||
|
#
|
||||||
|
# If PYTORCH_ROCM_ARCH env variable exists, then we take it as a list,
|
||||||
|
# if not, then we use CMAKE_HIP_ARCHITECTURES which was generated by calling
|
||||||
|
# "rocm_agent_enumerator" in "enable_language(HIP)"
|
||||||
|
# (in file Modules/CMakeDetermineHIPCompiler.cmake)
|
||||||
|
#
|
||||||
|
if(DEFINED ENV{PYTORCH_ROCM_ARCH})
|
||||||
|
set(HIP_ARCHITECTURES $ENV{PYTORCH_ROCM_ARCH})
|
||||||
|
else()
|
||||||
|
set(HIP_ARCHITECTURES ${CMAKE_HIP_ARCHITECTURES})
|
||||||
|
endif()
|
||||||
|
#
|
||||||
|
# Find the intersection of the supported + detected architectures to
|
||||||
|
# set the module architecture flags.
|
||||||
|
#
|
||||||
|
set(${GPU_ARCHES})
|
||||||
|
foreach (_ARCH ${HIP_ARCHITECTURES})
|
||||||
|
if (_ARCH IN_LIST _GPU_SUPPORTED_ARCHES_LIST)
|
||||||
|
list(APPEND ${GPU_ARCHES} ${_ARCH})
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
|
||||||
|
if(NOT ${GPU_ARCHES})
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"None of the detected ROCm architectures: ${HIP_ARCHITECTURES} is"
|
||||||
|
" supported. Supported ROCm architectures are: ${_GPU_SUPPORTED_ARCHES_LIST}.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
elseif(${GPU_LANG} STREQUAL "CUDA")
|
||||||
|
#
|
||||||
|
# Setup/process CUDA arch flags.
|
||||||
|
#
|
||||||
|
# The torch cmake setup hardcodes the detected architecture flags in
|
||||||
|
# `CMAKE_CUDA_FLAGS`. Since `CMAKE_CUDA_FLAGS` is a "global" variable, it
|
||||||
|
# can't modified on a per-target basis, e.g. for the `punica` extension.
|
||||||
|
# So, all the `-gencode` flags need to be extracted and removed from
|
||||||
|
# `CMAKE_CUDA_FLAGS` for processing so they can be passed by another method.
|
||||||
|
# Since it's not possible to use `target_compiler_options` for adding target
|
||||||
|
# specific `-gencode` arguments, the target's `CUDA_ARCHITECTURES` property
|
||||||
|
# must be used instead. This requires repackaging the architecture flags
|
||||||
|
# into a format that cmake expects for `CUDA_ARCHITECTURES`.
|
||||||
|
#
|
||||||
|
# This is a bit fragile in that it depends on torch using `-gencode` as opposed
|
||||||
|
# to one of the other nvcc options to specify architectures.
|
||||||
|
#
|
||||||
|
# Note: torch uses the `TORCH_CUDA_ARCH_LIST` environment variable to override
|
||||||
|
# detected architectures.
|
||||||
|
#
|
||||||
|
message(DEBUG "initial CMAKE_CUDA_FLAGS: ${CMAKE_CUDA_FLAGS}")
|
||||||
|
|
||||||
|
# Extract all `-gencode` flags from `CMAKE_CUDA_FLAGS`
|
||||||
|
string(REGEX MATCHALL "-gencode arch=[^ ]+" _CUDA_ARCH_FLAGS
|
||||||
|
${CMAKE_CUDA_FLAGS})
|
||||||
|
|
||||||
|
# Remove all `-gencode` flags from `CMAKE_CUDA_FLAGS` since they will be modified
|
||||||
|
# and passed back via the `CUDA_ARCHITECTURES` property.
|
||||||
|
string(REGEX REPLACE "-gencode arch=[^ ]+ *" "" CMAKE_CUDA_FLAGS
|
||||||
|
${CMAKE_CUDA_FLAGS})
|
||||||
|
|
||||||
|
# If this error is triggered, it might mean that torch has changed how it sets
|
||||||
|
# up nvcc architecture code generation flags.
|
||||||
|
if (NOT _CUDA_ARCH_FLAGS)
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"Could not find any architecture related code generation flags in "
|
||||||
|
"CMAKE_CUDA_FLAGS. (${CMAKE_CUDA_FLAGS})")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
message(DEBUG "final CMAKE_CUDA_FLAGS: ${CMAKE_CUDA_FLAGS}")
|
||||||
|
message(DEBUG "arch flags: ${_CUDA_ARCH_FLAGS}")
|
||||||
|
|
||||||
|
# Initialize the architecture lists to empty.
|
||||||
|
set(${GPU_ARCHES})
|
||||||
|
|
||||||
|
# Process each `gencode` flag.
|
||||||
|
foreach(_ARCH ${_CUDA_ARCH_FLAGS})
|
||||||
|
# For each flag, extract the version number and whether it refers to PTX
|
||||||
|
# or native code.
|
||||||
|
# Note: if a regex matches then `CMAKE_MATCH_1` holds the binding
|
||||||
|
# for that match.
|
||||||
|
|
||||||
|
string(REGEX MATCH "arch=compute_\([0-9]+a?\)" _COMPUTE ${_ARCH})
|
||||||
|
if (_COMPUTE)
|
||||||
|
set(_COMPUTE ${CMAKE_MATCH_1})
|
||||||
|
endif()
|
||||||
|
|
||||||
|
string(REGEX MATCH "code=sm_\([0-9]+a?\)" _SM ${_ARCH})
|
||||||
|
if (_SM)
|
||||||
|
set(_SM ${CMAKE_MATCH_1})
|
||||||
|
endif()
|
||||||
|
|
||||||
|
string(REGEX MATCH "code=compute_\([0-9]+a?\)" _CODE ${_ARCH})
|
||||||
|
if (_CODE)
|
||||||
|
set(_CODE ${CMAKE_MATCH_1})
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Make sure the virtual architecture can be matched.
|
||||||
|
if (NOT _COMPUTE)
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"Could not determine virtual architecture from: ${_ARCH}.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# One of sm_ or compute_ must exist.
|
||||||
|
if ((NOT _SM) AND (NOT _CODE))
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"Could not determine a codegen architecture from: ${_ARCH}.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (_SM)
|
||||||
|
# -real suffix let CMake to only generate elf code for the kernels.
|
||||||
|
# we want this, otherwise the added ptx (default) will increase binary size.
|
||||||
|
set(_VIRT "-real")
|
||||||
|
set(_CODE_ARCH ${_SM})
|
||||||
|
else()
|
||||||
|
# -virtual suffix let CMake to generate ptx code for the kernels.
|
||||||
|
set(_VIRT "-virtual")
|
||||||
|
set(_CODE_ARCH ${_CODE})
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Check if the current version is in the supported arch list.
|
||||||
|
string_to_ver(_CODE_VER ${_CODE_ARCH})
|
||||||
|
if (NOT _CODE_VER IN_LIST _GPU_SUPPORTED_ARCHES_LIST)
|
||||||
|
message(STATUS "discarding unsupported CUDA arch ${_VER}.")
|
||||||
|
continue()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Add it to the arch list.
|
||||||
|
list(APPEND ${GPU_ARCHES} "${_CODE_ARCH}${_VIRT}")
|
||||||
|
endforeach()
|
||||||
|
endif()
|
||||||
|
message(STATUS "${GPU_LANG} target arches: ${${GPU_ARCHES}}")
|
||||||
|
endmacro()
|
||||||
|
|
||||||
|
#
|
||||||
|
# Define a target named `GPU_MOD_NAME` for a single extension. The
|
||||||
|
# arguments are:
|
||||||
|
#
|
||||||
|
# DESTINATION <dest> - Module destination directory.
|
||||||
|
# LANGUAGE <lang> - The GPU language for this module, e.g CUDA, HIP,
|
||||||
|
# etc.
|
||||||
|
# SOURCES <sources> - List of source files relative to CMakeLists.txt
|
||||||
|
# directory.
|
||||||
|
#
|
||||||
|
# Optional arguments:
|
||||||
|
#
|
||||||
|
# ARCHITECTURES <arches> - A list of target GPU architectures in cmake
|
||||||
|
# format.
|
||||||
|
# Refer `CMAKE_CUDA_ARCHITECTURES` documentation
|
||||||
|
# and `CMAKE_HIP_ARCHITECTURES` for more info.
|
||||||
|
# ARCHITECTURES will use cmake's defaults if
|
||||||
|
# not provided.
|
||||||
|
# COMPILE_FLAGS <flags> - Extra compiler flags passed to NVCC/hip.
|
||||||
|
# INCLUDE_DIRECTORIES <dirs> - Extra include directories.
|
||||||
|
# LIBRARIES <libraries> - Extra link libraries.
|
||||||
|
# WITH_SOABI - Generate library with python SOABI suffix name.
|
||||||
|
# USE_SABI <version> - Use python stable api <version>
|
||||||
|
#
|
||||||
|
# Note: optimization level/debug info is set via cmake build type.
|
||||||
|
#
|
||||||
|
function (define_gpu_extension_target GPU_MOD_NAME)
|
||||||
|
cmake_parse_arguments(PARSE_ARGV 1
|
||||||
|
GPU
|
||||||
|
"WITH_SOABI"
|
||||||
|
"DESTINATION;LANGUAGE;USE_SABI"
|
||||||
|
"SOURCES;ARCHITECTURES;COMPILE_FLAGS;INCLUDE_DIRECTORIES;LIBRARIES")
|
||||||
|
|
||||||
|
# Add hipify preprocessing step when building with HIP/ROCm.
|
||||||
|
if (GPU_LANGUAGE STREQUAL "HIP")
|
||||||
|
hipify_sources_target(GPU_SOURCES ${GPU_MOD_NAME} "${GPU_SOURCES}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (GPU_WITH_SOABI)
|
||||||
|
set(GPU_WITH_SOABI WITH_SOABI)
|
||||||
|
else()
|
||||||
|
set(GPU_WITH_SOABI)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (GPU_USE_SABI)
|
||||||
|
Python_add_library(${GPU_MOD_NAME} MODULE USE_SABI ${GPU_USE_SABI} ${GPU_WITH_SOABI} "${GPU_SOURCES}")
|
||||||
|
else()
|
||||||
|
Python_add_library(${GPU_MOD_NAME} MODULE ${GPU_WITH_SOABI} "${GPU_SOURCES}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (GPU_LANGUAGE STREQUAL "HIP")
|
||||||
|
# Make this target dependent on the hipify preprocessor step.
|
||||||
|
add_dependencies(${GPU_MOD_NAME} hipify${GPU_MOD_NAME})
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (GPU_ARCHITECTURES)
|
||||||
|
set_target_properties(${GPU_MOD_NAME} PROPERTIES
|
||||||
|
${GPU_LANGUAGE}_ARCHITECTURES "${GPU_ARCHITECTURES}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set_property(TARGET ${GPU_MOD_NAME} PROPERTY CXX_STANDARD 17)
|
||||||
|
|
||||||
|
target_compile_options(${GPU_MOD_NAME} PRIVATE
|
||||||
|
$<$<COMPILE_LANGUAGE:${GPU_LANGUAGE}>:${GPU_COMPILE_FLAGS}>)
|
||||||
|
|
||||||
|
target_compile_definitions(${GPU_MOD_NAME} PRIVATE
|
||||||
|
"-DTORCH_EXTENSION_NAME=${GPU_MOD_NAME}")
|
||||||
|
|
||||||
|
target_include_directories(${GPU_MOD_NAME} PRIVATE csrc
|
||||||
|
${GPU_INCLUDE_DIRECTORIES})
|
||||||
|
|
||||||
|
target_link_libraries(${GPU_MOD_NAME} PRIVATE torch ${torch_python_LIBRARY}
|
||||||
|
${GPU_LIBRARIES})
|
||||||
|
|
||||||
|
# Don't use `TORCH_LIBRARIES` for CUDA since it pulls in a bunch of
|
||||||
|
# dependencies that are not necessary and may not be installed.
|
||||||
|
if (GPU_LANGUAGE STREQUAL "CUDA")
|
||||||
|
target_link_libraries(${GPU_MOD_NAME} PRIVATE ${CUDA_CUDA_LIB}
|
||||||
|
${CUDA_LIBRARIES})
|
||||||
|
else()
|
||||||
|
target_link_libraries(${GPU_MOD_NAME} PRIVATE ${TORCH_LIBRARIES})
|
||||||
|
endif()
|
||||||
|
|
||||||
|
install(TARGETS ${GPU_MOD_NAME} LIBRARY DESTINATION ${GPU_DESTINATION})
|
||||||
|
endfunction()
|
||||||
728
collect_env.py
Normal file
728
collect_env.py
Normal file
@ -0,0 +1,728 @@
|
|||||||
|
# ruff: noqa
|
||||||
|
# code borrowed from https://github.com/pytorch/pytorch/blob/main/torch/utils/collect_env.py
|
||||||
|
|
||||||
|
# Unlike the rest of the PyTorch this file must be python2 compliant.
|
||||||
|
# This script outputs relevant system environment info
|
||||||
|
# Run it with `python collect_env.py` or `python -m torch.utils.collect_env`
|
||||||
|
import datetime
|
||||||
|
import locale
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from collections import namedtuple
|
||||||
|
|
||||||
|
try:
|
||||||
|
import torch
|
||||||
|
TORCH_AVAILABLE = True
|
||||||
|
except (ImportError, NameError, AttributeError, OSError):
|
||||||
|
TORCH_AVAILABLE = False
|
||||||
|
|
||||||
|
# System Environment Information
|
||||||
|
SystemEnv = namedtuple(
|
||||||
|
'SystemEnv',
|
||||||
|
[
|
||||||
|
'torch_version',
|
||||||
|
'is_debug_build',
|
||||||
|
'cuda_compiled_version',
|
||||||
|
'gcc_version',
|
||||||
|
'clang_version',
|
||||||
|
'cmake_version',
|
||||||
|
'os',
|
||||||
|
'libc_version',
|
||||||
|
'python_version',
|
||||||
|
'python_platform',
|
||||||
|
'is_cuda_available',
|
||||||
|
'cuda_runtime_version',
|
||||||
|
'cuda_module_loading',
|
||||||
|
'nvidia_driver_version',
|
||||||
|
'nvidia_gpu_models',
|
||||||
|
'cudnn_version',
|
||||||
|
'pip_version', # 'pip' or 'pip3'
|
||||||
|
'pip_packages',
|
||||||
|
'conda_packages',
|
||||||
|
'hip_compiled_version',
|
||||||
|
'hip_runtime_version',
|
||||||
|
'miopen_runtime_version',
|
||||||
|
'caching_allocator_config',
|
||||||
|
'is_xnnpack_available',
|
||||||
|
'cpu_info',
|
||||||
|
'rocm_version', # vllm specific field
|
||||||
|
'neuron_sdk_version', # vllm specific field
|
||||||
|
'vllm_version', # vllm specific field
|
||||||
|
'vllm_build_flags', # vllm specific field
|
||||||
|
'gpu_topo', # vllm specific field
|
||||||
|
])
|
||||||
|
|
||||||
|
DEFAULT_CONDA_PATTERNS = {
|
||||||
|
"torch",
|
||||||
|
"numpy",
|
||||||
|
"cudatoolkit",
|
||||||
|
"soumith",
|
||||||
|
"mkl",
|
||||||
|
"magma",
|
||||||
|
"triton",
|
||||||
|
"optree",
|
||||||
|
"nccl",
|
||||||
|
"transformers",
|
||||||
|
}
|
||||||
|
|
||||||
|
DEFAULT_PIP_PATTERNS = {
|
||||||
|
"torch",
|
||||||
|
"numpy",
|
||||||
|
"mypy",
|
||||||
|
"flake8",
|
||||||
|
"triton",
|
||||||
|
"optree",
|
||||||
|
"onnx",
|
||||||
|
"nccl",
|
||||||
|
"transformers",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def run(command):
|
||||||
|
"""Return (return-code, stdout, stderr)."""
|
||||||
|
shell = True if type(command) is str else False
|
||||||
|
p = subprocess.Popen(command,
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.PIPE,
|
||||||
|
shell=shell)
|
||||||
|
raw_output, raw_err = p.communicate()
|
||||||
|
rc = p.returncode
|
||||||
|
if get_platform() == 'win32':
|
||||||
|
enc = 'oem'
|
||||||
|
else:
|
||||||
|
enc = locale.getpreferredencoding()
|
||||||
|
output = raw_output.decode(enc)
|
||||||
|
err = raw_err.decode(enc)
|
||||||
|
return rc, output.strip(), err.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def run_and_read_all(run_lambda, command):
|
||||||
|
"""Run command using run_lambda; reads and returns entire output if rc is 0."""
|
||||||
|
rc, out, _ = run_lambda(command)
|
||||||
|
if rc != 0:
|
||||||
|
return None
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def run_and_parse_first_match(run_lambda, command, regex):
|
||||||
|
"""Run command using run_lambda, returns the first regex match if it exists."""
|
||||||
|
rc, out, _ = run_lambda(command)
|
||||||
|
if rc != 0:
|
||||||
|
return None
|
||||||
|
match = re.search(regex, out)
|
||||||
|
if match is None:
|
||||||
|
return None
|
||||||
|
return match.group(1)
|
||||||
|
|
||||||
|
|
||||||
|
def run_and_return_first_line(run_lambda, command):
|
||||||
|
"""Run command using run_lambda and returns first line if output is not empty."""
|
||||||
|
rc, out, _ = run_lambda(command)
|
||||||
|
if rc != 0:
|
||||||
|
return None
|
||||||
|
return out.split('\n')[0]
|
||||||
|
|
||||||
|
|
||||||
|
def get_conda_packages(run_lambda, patterns=None):
|
||||||
|
if patterns is None:
|
||||||
|
patterns = DEFAULT_CONDA_PATTERNS
|
||||||
|
conda = os.environ.get('CONDA_EXE', 'conda')
|
||||||
|
out = run_and_read_all(run_lambda, "{} list".format(conda))
|
||||||
|
if out is None:
|
||||||
|
return out
|
||||||
|
|
||||||
|
return "\n".join(line for line in out.splitlines()
|
||||||
|
if not line.startswith("#") and any(name in line
|
||||||
|
for name in patterns))
|
||||||
|
|
||||||
|
|
||||||
|
def get_gcc_version(run_lambda):
|
||||||
|
return run_and_parse_first_match(run_lambda, 'gcc --version', r'gcc (.*)')
|
||||||
|
|
||||||
|
|
||||||
|
def get_clang_version(run_lambda):
|
||||||
|
return run_and_parse_first_match(run_lambda, 'clang --version',
|
||||||
|
r'clang version (.*)')
|
||||||
|
|
||||||
|
|
||||||
|
def get_cmake_version(run_lambda):
|
||||||
|
return run_and_parse_first_match(run_lambda, 'cmake --version',
|
||||||
|
r'cmake (.*)')
|
||||||
|
|
||||||
|
|
||||||
|
def get_nvidia_driver_version(run_lambda):
|
||||||
|
if get_platform() == 'darwin':
|
||||||
|
cmd = 'kextstat | grep -i cuda'
|
||||||
|
return run_and_parse_first_match(run_lambda, cmd,
|
||||||
|
r'com[.]nvidia[.]CUDA [(](.*?)[)]')
|
||||||
|
smi = get_nvidia_smi()
|
||||||
|
return run_and_parse_first_match(run_lambda, smi,
|
||||||
|
r'Driver Version: (.*?) ')
|
||||||
|
|
||||||
|
|
||||||
|
def get_gpu_info(run_lambda):
|
||||||
|
if get_platform() == 'darwin' or (TORCH_AVAILABLE and hasattr(
|
||||||
|
torch.version, 'hip') and torch.version.hip is not None):
|
||||||
|
if TORCH_AVAILABLE and torch.cuda.is_available():
|
||||||
|
if torch.version.hip is not None:
|
||||||
|
prop = torch.cuda.get_device_properties(0)
|
||||||
|
if hasattr(prop, "gcnArchName"):
|
||||||
|
gcnArch = " ({})".format(prop.gcnArchName)
|
||||||
|
else:
|
||||||
|
gcnArch = "NoGCNArchNameOnOldPyTorch"
|
||||||
|
else:
|
||||||
|
gcnArch = ""
|
||||||
|
return torch.cuda.get_device_name(None) + gcnArch
|
||||||
|
return None
|
||||||
|
smi = get_nvidia_smi()
|
||||||
|
uuid_regex = re.compile(r' \(UUID: .+?\)')
|
||||||
|
rc, out, _ = run_lambda(smi + ' -L')
|
||||||
|
if rc != 0:
|
||||||
|
return None
|
||||||
|
# Anonymize GPUs by removing their UUID
|
||||||
|
return re.sub(uuid_regex, '', out)
|
||||||
|
|
||||||
|
|
||||||
|
def get_running_cuda_version(run_lambda):
|
||||||
|
return run_and_parse_first_match(run_lambda, 'nvcc --version',
|
||||||
|
r'release .+ V(.*)')
|
||||||
|
|
||||||
|
|
||||||
|
def get_cudnn_version(run_lambda):
|
||||||
|
"""Return a list of libcudnn.so; it's hard to tell which one is being used."""
|
||||||
|
if get_platform() == 'win32':
|
||||||
|
system_root = os.environ.get('SYSTEMROOT', 'C:\\Windows')
|
||||||
|
cuda_path = os.environ.get('CUDA_PATH', "%CUDA_PATH%")
|
||||||
|
where_cmd = os.path.join(system_root, 'System32', 'where')
|
||||||
|
cudnn_cmd = '{} /R "{}\\bin" cudnn*.dll'.format(where_cmd, cuda_path)
|
||||||
|
elif get_platform() == 'darwin':
|
||||||
|
# CUDA libraries and drivers can be found in /usr/local/cuda/. See
|
||||||
|
# https://docs.nvidia.com/cuda/cuda-installation-guide-mac-os-x/index.html#install
|
||||||
|
# https://docs.nvidia.com/deeplearning/sdk/cudnn-install/index.html#installmac
|
||||||
|
# Use CUDNN_LIBRARY when cudnn library is installed elsewhere.
|
||||||
|
cudnn_cmd = 'ls /usr/local/cuda/lib/libcudnn*'
|
||||||
|
else:
|
||||||
|
cudnn_cmd = 'ldconfig -p | grep libcudnn | rev | cut -d" " -f1 | rev'
|
||||||
|
rc, out, _ = run_lambda(cudnn_cmd)
|
||||||
|
# find will return 1 if there are permission errors or if not found
|
||||||
|
if len(out) == 0 or (rc != 1 and rc != 0):
|
||||||
|
l = os.environ.get('CUDNN_LIBRARY')
|
||||||
|
if l is not None and os.path.isfile(l):
|
||||||
|
return os.path.realpath(l)
|
||||||
|
return None
|
||||||
|
files_set = set()
|
||||||
|
for fn in out.split('\n'):
|
||||||
|
fn = os.path.realpath(fn) # eliminate symbolic links
|
||||||
|
if os.path.isfile(fn):
|
||||||
|
files_set.add(fn)
|
||||||
|
if not files_set:
|
||||||
|
return None
|
||||||
|
# Alphabetize the result because the order is non-deterministic otherwise
|
||||||
|
files = sorted(files_set)
|
||||||
|
if len(files) == 1:
|
||||||
|
return files[0]
|
||||||
|
result = '\n'.join(files)
|
||||||
|
return 'Probably one of the following:\n{}'.format(result)
|
||||||
|
|
||||||
|
|
||||||
|
def get_nvidia_smi():
|
||||||
|
# Note: nvidia-smi is currently available only on Windows and Linux
|
||||||
|
smi = 'nvidia-smi'
|
||||||
|
if get_platform() == 'win32':
|
||||||
|
system_root = os.environ.get('SYSTEMROOT', 'C:\\Windows')
|
||||||
|
program_files_root = os.environ.get('PROGRAMFILES',
|
||||||
|
'C:\\Program Files')
|
||||||
|
legacy_path = os.path.join(program_files_root, 'NVIDIA Corporation',
|
||||||
|
'NVSMI', smi)
|
||||||
|
new_path = os.path.join(system_root, 'System32', smi)
|
||||||
|
smis = [new_path, legacy_path]
|
||||||
|
for candidate_smi in smis:
|
||||||
|
if os.path.exists(candidate_smi):
|
||||||
|
smi = '"{}"'.format(candidate_smi)
|
||||||
|
break
|
||||||
|
return smi
|
||||||
|
|
||||||
|
|
||||||
|
def get_rocm_version(run_lambda):
|
||||||
|
"""Returns the ROCm version if available, otherwise 'N/A'."""
|
||||||
|
return run_and_parse_first_match(run_lambda, 'hipcc --version',
|
||||||
|
r'HIP version: (\S+)')
|
||||||
|
|
||||||
|
|
||||||
|
def get_neuron_sdk_version(run_lambda):
|
||||||
|
# Adapted from your install script
|
||||||
|
try:
|
||||||
|
result = run_lambda(["neuron-ls"])
|
||||||
|
return result if result[0] == 0 else 'N/A'
|
||||||
|
except Exception:
|
||||||
|
return 'N/A'
|
||||||
|
|
||||||
|
|
||||||
|
def get_vllm_version():
|
||||||
|
try:
|
||||||
|
import vllm
|
||||||
|
return vllm.__version__
|
||||||
|
except ImportError:
|
||||||
|
return 'N/A'
|
||||||
|
|
||||||
|
|
||||||
|
def summarize_vllm_build_flags():
|
||||||
|
# This could be a static method if the flags are constant, or dynamic if you need to check environment variables, etc.
|
||||||
|
return 'CUDA Archs: {}; ROCm: {}; Neuron: {}'.format(
|
||||||
|
os.environ.get('TORCH_CUDA_ARCH_LIST', 'Not Set'),
|
||||||
|
'Enabled' if os.environ.get('ROCM_HOME') else 'Disabled',
|
||||||
|
'Enabled' if os.environ.get('NEURON_CORES') else 'Disabled',
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_gpu_topo(run_lambda):
|
||||||
|
if get_platform() == 'linux':
|
||||||
|
return run_and_read_all(run_lambda, 'nvidia-smi topo -m')
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# example outputs of CPU infos
|
||||||
|
# * linux
|
||||||
|
# Architecture: x86_64
|
||||||
|
# CPU op-mode(s): 32-bit, 64-bit
|
||||||
|
# Address sizes: 46 bits physical, 48 bits virtual
|
||||||
|
# Byte Order: Little Endian
|
||||||
|
# CPU(s): 128
|
||||||
|
# On-line CPU(s) list: 0-127
|
||||||
|
# Vendor ID: GenuineIntel
|
||||||
|
# Model name: Intel(R) Xeon(R) Platinum 8375C CPU @ 2.90GHz
|
||||||
|
# CPU family: 6
|
||||||
|
# Model: 106
|
||||||
|
# Thread(s) per core: 2
|
||||||
|
# Core(s) per socket: 32
|
||||||
|
# Socket(s): 2
|
||||||
|
# Stepping: 6
|
||||||
|
# BogoMIPS: 5799.78
|
||||||
|
# Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr
|
||||||
|
# sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon rep_good nopl
|
||||||
|
# xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq monitor ssse3 fma cx16
|
||||||
|
# pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand
|
||||||
|
# hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced
|
||||||
|
# fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid avx512f avx512dq rdseed adx smap
|
||||||
|
# avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1
|
||||||
|
# xsaves wbnoinvd ida arat avx512vbmi pku ospke avx512_vbmi2 gfni vaes vpclmulqdq
|
||||||
|
# avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid md_clear flush_l1d arch_capabilities
|
||||||
|
# Virtualization features:
|
||||||
|
# Hypervisor vendor: KVM
|
||||||
|
# Virtualization type: full
|
||||||
|
# Caches (sum of all):
|
||||||
|
# L1d: 3 MiB (64 instances)
|
||||||
|
# L1i: 2 MiB (64 instances)
|
||||||
|
# L2: 80 MiB (64 instances)
|
||||||
|
# L3: 108 MiB (2 instances)
|
||||||
|
# NUMA:
|
||||||
|
# NUMA node(s): 2
|
||||||
|
# NUMA node0 CPU(s): 0-31,64-95
|
||||||
|
# NUMA node1 CPU(s): 32-63,96-127
|
||||||
|
# Vulnerabilities:
|
||||||
|
# Itlb multihit: Not affected
|
||||||
|
# L1tf: Not affected
|
||||||
|
# Mds: Not affected
|
||||||
|
# Meltdown: Not affected
|
||||||
|
# Mmio stale data: Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
|
||||||
|
# Retbleed: Not affected
|
||||||
|
# Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
|
||||||
|
# Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization
|
||||||
|
# Spectre v2: Mitigation; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
|
||||||
|
# Srbds: Not affected
|
||||||
|
# Tsx async abort: Not affected
|
||||||
|
# * win32
|
||||||
|
# Architecture=9
|
||||||
|
# CurrentClockSpeed=2900
|
||||||
|
# DeviceID=CPU0
|
||||||
|
# Family=179
|
||||||
|
# L2CacheSize=40960
|
||||||
|
# L2CacheSpeed=
|
||||||
|
# Manufacturer=GenuineIntel
|
||||||
|
# MaxClockSpeed=2900
|
||||||
|
# Name=Intel(R) Xeon(R) Platinum 8375C CPU @ 2.90GHz
|
||||||
|
# ProcessorType=3
|
||||||
|
# Revision=27142
|
||||||
|
#
|
||||||
|
# Architecture=9
|
||||||
|
# CurrentClockSpeed=2900
|
||||||
|
# DeviceID=CPU1
|
||||||
|
# Family=179
|
||||||
|
# L2CacheSize=40960
|
||||||
|
# L2CacheSpeed=
|
||||||
|
# Manufacturer=GenuineIntel
|
||||||
|
# MaxClockSpeed=2900
|
||||||
|
# Name=Intel(R) Xeon(R) Platinum 8375C CPU @ 2.90GHz
|
||||||
|
# ProcessorType=3
|
||||||
|
# Revision=27142
|
||||||
|
|
||||||
|
|
||||||
|
def get_cpu_info(run_lambda):
|
||||||
|
rc, out, err = 0, '', ''
|
||||||
|
if get_platform() == 'linux':
|
||||||
|
rc, out, err = run_lambda('lscpu')
|
||||||
|
elif get_platform() == 'win32':
|
||||||
|
rc, out, err = run_lambda(
|
||||||
|
'wmic cpu get Name,Manufacturer,Family,Architecture,ProcessorType,DeviceID, \
|
||||||
|
CurrentClockSpeed,MaxClockSpeed,L2CacheSize,L2CacheSpeed,Revision /VALUE'
|
||||||
|
)
|
||||||
|
elif get_platform() == 'darwin':
|
||||||
|
rc, out, err = run_lambda("sysctl -n machdep.cpu.brand_string")
|
||||||
|
cpu_info = 'None'
|
||||||
|
if rc == 0:
|
||||||
|
cpu_info = out
|
||||||
|
else:
|
||||||
|
cpu_info = err
|
||||||
|
return cpu_info
|
||||||
|
|
||||||
|
|
||||||
|
def get_platform():
|
||||||
|
if sys.platform.startswith('linux'):
|
||||||
|
return 'linux'
|
||||||
|
elif sys.platform.startswith('win32'):
|
||||||
|
return 'win32'
|
||||||
|
elif sys.platform.startswith('cygwin'):
|
||||||
|
return 'cygwin'
|
||||||
|
elif sys.platform.startswith('darwin'):
|
||||||
|
return 'darwin'
|
||||||
|
else:
|
||||||
|
return sys.platform
|
||||||
|
|
||||||
|
|
||||||
|
def get_mac_version(run_lambda):
|
||||||
|
return run_and_parse_first_match(run_lambda, 'sw_vers -productVersion',
|
||||||
|
r'(.*)')
|
||||||
|
|
||||||
|
|
||||||
|
def get_windows_version(run_lambda):
|
||||||
|
system_root = os.environ.get('SYSTEMROOT', 'C:\\Windows')
|
||||||
|
wmic_cmd = os.path.join(system_root, 'System32', 'Wbem', 'wmic')
|
||||||
|
findstr_cmd = os.path.join(system_root, 'System32', 'findstr')
|
||||||
|
return run_and_read_all(
|
||||||
|
run_lambda,
|
||||||
|
'{} os get Caption | {} /v Caption'.format(wmic_cmd, findstr_cmd))
|
||||||
|
|
||||||
|
|
||||||
|
def get_lsb_version(run_lambda):
|
||||||
|
return run_and_parse_first_match(run_lambda, 'lsb_release -a',
|
||||||
|
r'Description:\t(.*)')
|
||||||
|
|
||||||
|
|
||||||
|
def check_release_file(run_lambda):
|
||||||
|
return run_and_parse_first_match(run_lambda, 'cat /etc/*-release',
|
||||||
|
r'PRETTY_NAME="(.*)"')
|
||||||
|
|
||||||
|
|
||||||
|
def get_os(run_lambda):
|
||||||
|
from platform import machine
|
||||||
|
platform = get_platform()
|
||||||
|
|
||||||
|
if platform == 'win32' or platform == 'cygwin':
|
||||||
|
return get_windows_version(run_lambda)
|
||||||
|
|
||||||
|
if platform == 'darwin':
|
||||||
|
version = get_mac_version(run_lambda)
|
||||||
|
if version is None:
|
||||||
|
return None
|
||||||
|
return 'macOS {} ({})'.format(version, machine())
|
||||||
|
|
||||||
|
if platform == 'linux':
|
||||||
|
# Ubuntu/Debian based
|
||||||
|
desc = get_lsb_version(run_lambda)
|
||||||
|
if desc is not None:
|
||||||
|
return '{} ({})'.format(desc, machine())
|
||||||
|
|
||||||
|
# Try reading /etc/*-release
|
||||||
|
desc = check_release_file(run_lambda)
|
||||||
|
if desc is not None:
|
||||||
|
return '{} ({})'.format(desc, machine())
|
||||||
|
|
||||||
|
return '{} ({})'.format(platform, machine())
|
||||||
|
|
||||||
|
# Unknown platform
|
||||||
|
return platform
|
||||||
|
|
||||||
|
|
||||||
|
def get_python_platform():
|
||||||
|
import platform
|
||||||
|
return platform.platform()
|
||||||
|
|
||||||
|
|
||||||
|
def get_libc_version():
|
||||||
|
import platform
|
||||||
|
if get_platform() != 'linux':
|
||||||
|
return 'N/A'
|
||||||
|
return '-'.join(platform.libc_ver())
|
||||||
|
|
||||||
|
|
||||||
|
def get_pip_packages(run_lambda, patterns=None):
|
||||||
|
"""Return `pip list` output. Note: will also find conda-installed pytorch and numpy packages."""
|
||||||
|
if patterns is None:
|
||||||
|
patterns = DEFAULT_PIP_PATTERNS
|
||||||
|
|
||||||
|
# People generally have `pip` as `pip` or `pip3`
|
||||||
|
# But here it is invoked as `python -mpip`
|
||||||
|
def run_with_pip(pip):
|
||||||
|
out = run_and_read_all(run_lambda, pip + ["list", "--format=freeze"])
|
||||||
|
return "\n".join(line for line in out.splitlines()
|
||||||
|
if any(name in line for name in patterns))
|
||||||
|
|
||||||
|
pip_version = 'pip3' if sys.version[0] == '3' else 'pip'
|
||||||
|
out = run_with_pip([sys.executable, '-mpip'])
|
||||||
|
|
||||||
|
return pip_version, out
|
||||||
|
|
||||||
|
|
||||||
|
def get_cachingallocator_config():
|
||||||
|
ca_config = os.environ.get('PYTORCH_CUDA_ALLOC_CONF', '')
|
||||||
|
return ca_config
|
||||||
|
|
||||||
|
|
||||||
|
def get_cuda_module_loading_config():
|
||||||
|
if TORCH_AVAILABLE and torch.cuda.is_available():
|
||||||
|
torch.cuda.init()
|
||||||
|
config = os.environ.get('CUDA_MODULE_LOADING', '')
|
||||||
|
return config
|
||||||
|
else:
|
||||||
|
return "N/A"
|
||||||
|
|
||||||
|
|
||||||
|
def is_xnnpack_available():
|
||||||
|
if TORCH_AVAILABLE:
|
||||||
|
import torch.backends.xnnpack
|
||||||
|
return str(
|
||||||
|
torch.backends.xnnpack.enabled) # type: ignore[attr-defined]
|
||||||
|
else:
|
||||||
|
return "N/A"
|
||||||
|
|
||||||
|
|
||||||
|
def get_env_info():
|
||||||
|
run_lambda = run
|
||||||
|
pip_version, pip_list_output = get_pip_packages(run_lambda)
|
||||||
|
|
||||||
|
if TORCH_AVAILABLE:
|
||||||
|
version_str = torch.__version__
|
||||||
|
debug_mode_str = str(torch.version.debug)
|
||||||
|
cuda_available_str = str(torch.cuda.is_available())
|
||||||
|
cuda_version_str = torch.version.cuda
|
||||||
|
if not hasattr(torch.version,
|
||||||
|
'hip') or torch.version.hip is None: # cuda version
|
||||||
|
hip_compiled_version = hip_runtime_version = miopen_runtime_version = 'N/A'
|
||||||
|
else: # HIP version
|
||||||
|
|
||||||
|
def get_version_or_na(cfg, prefix):
|
||||||
|
_lst = [s.rsplit(None, 1)[-1] for s in cfg if prefix in s]
|
||||||
|
return _lst[0] if _lst else 'N/A'
|
||||||
|
|
||||||
|
cfg = torch._C._show_config().split('\n')
|
||||||
|
hip_runtime_version = get_version_or_na(cfg, 'HIP Runtime')
|
||||||
|
miopen_runtime_version = get_version_or_na(cfg, 'MIOpen')
|
||||||
|
cuda_version_str = 'N/A'
|
||||||
|
hip_compiled_version = torch.version.hip
|
||||||
|
else:
|
||||||
|
version_str = debug_mode_str = cuda_available_str = cuda_version_str = 'N/A'
|
||||||
|
hip_compiled_version = hip_runtime_version = miopen_runtime_version = 'N/A'
|
||||||
|
|
||||||
|
sys_version = sys.version.replace("\n", " ")
|
||||||
|
|
||||||
|
conda_packages = get_conda_packages(run_lambda)
|
||||||
|
|
||||||
|
rocm_version = get_rocm_version(run_lambda)
|
||||||
|
neuron_sdk_version = get_neuron_sdk_version(run_lambda)
|
||||||
|
vllm_version = get_vllm_version()
|
||||||
|
vllm_build_flags = summarize_vllm_build_flags()
|
||||||
|
gpu_topo = get_gpu_topo(run_lambda)
|
||||||
|
|
||||||
|
return SystemEnv(
|
||||||
|
torch_version=version_str,
|
||||||
|
is_debug_build=debug_mode_str,
|
||||||
|
python_version='{} ({}-bit runtime)'.format(
|
||||||
|
sys_version,
|
||||||
|
sys.maxsize.bit_length() + 1),
|
||||||
|
python_platform=get_python_platform(),
|
||||||
|
is_cuda_available=cuda_available_str,
|
||||||
|
cuda_compiled_version=cuda_version_str,
|
||||||
|
cuda_runtime_version=get_running_cuda_version(run_lambda),
|
||||||
|
cuda_module_loading=get_cuda_module_loading_config(),
|
||||||
|
nvidia_gpu_models=get_gpu_info(run_lambda),
|
||||||
|
nvidia_driver_version=get_nvidia_driver_version(run_lambda),
|
||||||
|
cudnn_version=get_cudnn_version(run_lambda),
|
||||||
|
hip_compiled_version=hip_compiled_version,
|
||||||
|
hip_runtime_version=hip_runtime_version,
|
||||||
|
miopen_runtime_version=miopen_runtime_version,
|
||||||
|
pip_version=pip_version,
|
||||||
|
pip_packages=pip_list_output,
|
||||||
|
conda_packages=conda_packages,
|
||||||
|
os=get_os(run_lambda),
|
||||||
|
libc_version=get_libc_version(),
|
||||||
|
gcc_version=get_gcc_version(run_lambda),
|
||||||
|
clang_version=get_clang_version(run_lambda),
|
||||||
|
cmake_version=get_cmake_version(run_lambda),
|
||||||
|
caching_allocator_config=get_cachingallocator_config(),
|
||||||
|
is_xnnpack_available=is_xnnpack_available(),
|
||||||
|
cpu_info=get_cpu_info(run_lambda),
|
||||||
|
rocm_version=rocm_version,
|
||||||
|
neuron_sdk_version=neuron_sdk_version,
|
||||||
|
vllm_version=vllm_version,
|
||||||
|
vllm_build_flags=vllm_build_flags,
|
||||||
|
gpu_topo=gpu_topo,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
env_info_fmt = """
|
||||||
|
PyTorch version: {torch_version}
|
||||||
|
Is debug build: {is_debug_build}
|
||||||
|
CUDA used to build PyTorch: {cuda_compiled_version}
|
||||||
|
ROCM used to build PyTorch: {hip_compiled_version}
|
||||||
|
|
||||||
|
OS: {os}
|
||||||
|
GCC version: {gcc_version}
|
||||||
|
Clang version: {clang_version}
|
||||||
|
CMake version: {cmake_version}
|
||||||
|
Libc version: {libc_version}
|
||||||
|
|
||||||
|
Python version: {python_version}
|
||||||
|
Python platform: {python_platform}
|
||||||
|
Is CUDA available: {is_cuda_available}
|
||||||
|
CUDA runtime version: {cuda_runtime_version}
|
||||||
|
CUDA_MODULE_LOADING set to: {cuda_module_loading}
|
||||||
|
GPU models and configuration: {nvidia_gpu_models}
|
||||||
|
Nvidia driver version: {nvidia_driver_version}
|
||||||
|
cuDNN version: {cudnn_version}
|
||||||
|
HIP runtime version: {hip_runtime_version}
|
||||||
|
MIOpen runtime version: {miopen_runtime_version}
|
||||||
|
Is XNNPACK available: {is_xnnpack_available}
|
||||||
|
|
||||||
|
CPU:
|
||||||
|
{cpu_info}
|
||||||
|
|
||||||
|
Versions of relevant libraries:
|
||||||
|
{pip_packages}
|
||||||
|
{conda_packages}
|
||||||
|
""".strip()
|
||||||
|
|
||||||
|
# both the above code and the following code use `strip()` to
|
||||||
|
# remove leading/trailing whitespaces, so we need to add a newline
|
||||||
|
# in between to separate the two sections
|
||||||
|
env_info_fmt += "\n"
|
||||||
|
|
||||||
|
env_info_fmt += """
|
||||||
|
ROCM Version: {rocm_version}
|
||||||
|
Neuron SDK Version: {neuron_sdk_version}
|
||||||
|
vLLM Version: {vllm_version}
|
||||||
|
vLLM Build Flags:
|
||||||
|
{vllm_build_flags}
|
||||||
|
GPU Topology:
|
||||||
|
{gpu_topo}
|
||||||
|
""".strip()
|
||||||
|
|
||||||
|
|
||||||
|
def pretty_str(envinfo):
|
||||||
|
|
||||||
|
def replace_nones(dct, replacement='Could not collect'):
|
||||||
|
for key in dct.keys():
|
||||||
|
if dct[key] is not None:
|
||||||
|
continue
|
||||||
|
dct[key] = replacement
|
||||||
|
return dct
|
||||||
|
|
||||||
|
def replace_bools(dct, true='Yes', false='No'):
|
||||||
|
for key in dct.keys():
|
||||||
|
if dct[key] is True:
|
||||||
|
dct[key] = true
|
||||||
|
elif dct[key] is False:
|
||||||
|
dct[key] = false
|
||||||
|
return dct
|
||||||
|
|
||||||
|
def prepend(text, tag='[prepend]'):
|
||||||
|
lines = text.split('\n')
|
||||||
|
updated_lines = [tag + line for line in lines]
|
||||||
|
return '\n'.join(updated_lines)
|
||||||
|
|
||||||
|
def replace_if_empty(text, replacement='No relevant packages'):
|
||||||
|
if text is not None and len(text) == 0:
|
||||||
|
return replacement
|
||||||
|
return text
|
||||||
|
|
||||||
|
def maybe_start_on_next_line(string):
|
||||||
|
# If `string` is multiline, prepend a \n to it.
|
||||||
|
if string is not None and len(string.split('\n')) > 1:
|
||||||
|
return '\n{}\n'.format(string)
|
||||||
|
return string
|
||||||
|
|
||||||
|
mutable_dict = envinfo._asdict()
|
||||||
|
|
||||||
|
# If nvidia_gpu_models is multiline, start on the next line
|
||||||
|
mutable_dict['nvidia_gpu_models'] = \
|
||||||
|
maybe_start_on_next_line(envinfo.nvidia_gpu_models)
|
||||||
|
|
||||||
|
# If the machine doesn't have CUDA, report some fields as 'No CUDA'
|
||||||
|
dynamic_cuda_fields = [
|
||||||
|
'cuda_runtime_version',
|
||||||
|
'nvidia_gpu_models',
|
||||||
|
'nvidia_driver_version',
|
||||||
|
]
|
||||||
|
all_cuda_fields = dynamic_cuda_fields + ['cudnn_version']
|
||||||
|
all_dynamic_cuda_fields_missing = all(mutable_dict[field] is None
|
||||||
|
for field in dynamic_cuda_fields)
|
||||||
|
if TORCH_AVAILABLE and not torch.cuda.is_available(
|
||||||
|
) and all_dynamic_cuda_fields_missing:
|
||||||
|
for field in all_cuda_fields:
|
||||||
|
mutable_dict[field] = 'No CUDA'
|
||||||
|
if envinfo.cuda_compiled_version is None:
|
||||||
|
mutable_dict['cuda_compiled_version'] = 'None'
|
||||||
|
|
||||||
|
# Replace True with Yes, False with No
|
||||||
|
mutable_dict = replace_bools(mutable_dict)
|
||||||
|
|
||||||
|
# Replace all None objects with 'Could not collect'
|
||||||
|
mutable_dict = replace_nones(mutable_dict)
|
||||||
|
|
||||||
|
# If either of these are '', replace with 'No relevant packages'
|
||||||
|
mutable_dict['pip_packages'] = replace_if_empty(
|
||||||
|
mutable_dict['pip_packages'])
|
||||||
|
mutable_dict['conda_packages'] = replace_if_empty(
|
||||||
|
mutable_dict['conda_packages'])
|
||||||
|
|
||||||
|
# Tag conda and pip packages with a prefix
|
||||||
|
# If they were previously None, they'll show up as ie '[conda] Could not collect'
|
||||||
|
if mutable_dict['pip_packages']:
|
||||||
|
mutable_dict['pip_packages'] = prepend(
|
||||||
|
mutable_dict['pip_packages'], '[{}] '.format(envinfo.pip_version))
|
||||||
|
if mutable_dict['conda_packages']:
|
||||||
|
mutable_dict['conda_packages'] = prepend(
|
||||||
|
mutable_dict['conda_packages'], '[conda] ')
|
||||||
|
mutable_dict['cpu_info'] = envinfo.cpu_info
|
||||||
|
return env_info_fmt.format(**mutable_dict)
|
||||||
|
|
||||||
|
|
||||||
|
def get_pretty_env_info():
|
||||||
|
return pretty_str(get_env_info())
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print("Collecting environment information...")
|
||||||
|
output = get_pretty_env_info()
|
||||||
|
print(output)
|
||||||
|
|
||||||
|
if TORCH_AVAILABLE and hasattr(torch, 'utils') and hasattr(
|
||||||
|
torch.utils, '_crash_handler'):
|
||||||
|
minidump_dir = torch.utils._crash_handler.DEFAULT_MINIDUMP_DIR
|
||||||
|
if sys.platform == "linux" and os.path.exists(minidump_dir):
|
||||||
|
dumps = [
|
||||||
|
os.path.join(minidump_dir, dump)
|
||||||
|
for dump in os.listdir(minidump_dir)
|
||||||
|
]
|
||||||
|
latest = max(dumps, key=os.path.getctime)
|
||||||
|
ctime = os.path.getctime(latest)
|
||||||
|
creation_time = datetime.datetime.fromtimestamp(ctime).strftime(
|
||||||
|
'%Y-%m-%d %H:%M:%S')
|
||||||
|
msg = "\n*** Detected a minidump at {} created on {}, ".format(latest, creation_time) + \
|
||||||
|
"if this is related to your bug please include it when you file a report ***"
|
||||||
|
print(msg, file=sys.stderr)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@ -1,5 +1,5 @@
|
|||||||
#include <ATen/cuda/CUDAContext.h>
|
#include <ATen/cuda/CUDAContext.h>
|
||||||
#include <torch/extension.h>
|
#include <torch/all.h>
|
||||||
#include <c10/cuda/CUDAGuard.h>
|
#include <c10/cuda/CUDAGuard.h>
|
||||||
|
|
||||||
#include <cmath>
|
#include <cmath>
|
||||||
@ -10,11 +10,11 @@
|
|||||||
namespace vllm {
|
namespace vllm {
|
||||||
|
|
||||||
// Activation and gating kernel template.
|
// Activation and gating kernel template.
|
||||||
template<typename scalar_t, scalar_t (*ACT_FN)(const scalar_t&)>
|
template <typename scalar_t, scalar_t (*ACT_FN)(const scalar_t&)>
|
||||||
__global__ void act_and_mul_kernel(
|
__global__ void act_and_mul_kernel(
|
||||||
scalar_t* __restrict__ out, // [..., d]
|
scalar_t* __restrict__ out, // [..., d]
|
||||||
const scalar_t* __restrict__ input, // [..., 2, d]
|
const scalar_t* __restrict__ input, // [..., 2, d]
|
||||||
const int d) {
|
const int d) {
|
||||||
const int64_t token_idx = blockIdx.x;
|
const int64_t token_idx = blockIdx.x;
|
||||||
for (int64_t idx = threadIdx.x; idx < d; idx += blockDim.x) {
|
for (int64_t idx = threadIdx.x; idx < d; idx += blockDim.x) {
|
||||||
const scalar_t x = VLLM_LDG(&input[token_idx * 2 * d + idx]);
|
const scalar_t x = VLLM_LDG(&input[token_idx * 2 * d + idx]);
|
||||||
@ -23,64 +23,78 @@ __global__ void act_and_mul_kernel(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename T>
|
template <typename T>
|
||||||
__device__ __forceinline__ T silu_kernel(const T& x) {
|
__device__ __forceinline__ T silu_kernel(const T& x) {
|
||||||
// x * sigmoid(x)
|
// x * sigmoid(x)
|
||||||
return (T) (((float) x) / (1.0f + expf((float) -x)));
|
return (T)(((float)x) / (1.0f + expf((float)-x)));
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename T>
|
template <typename T>
|
||||||
__device__ __forceinline__ T gelu_kernel(const T& x) {
|
__device__ __forceinline__ T gelu_kernel(const T& x) {
|
||||||
// Equivalent to PyTorch GELU with 'none' approximation.
|
// Equivalent to PyTorch GELU with 'none' approximation.
|
||||||
// Refer to:
|
// Refer to:
|
||||||
// https://github.com/pytorch/pytorch/blob/8ac9b20d4b090c213799e81acf48a55ea8d437d6/aten/src/ATen/native/cuda/ActivationGeluKernel.cu#L38
|
// https://github.com/pytorch/pytorch/blob/8ac9b20d4b090c213799e81acf48a55ea8d437d6/aten/src/ATen/native/cuda/ActivationGeluKernel.cu#L36-L38
|
||||||
const float f = (float) x;
|
const float f = (float)x;
|
||||||
constexpr float ALPHA = M_SQRT1_2;
|
constexpr float ALPHA = M_SQRT1_2;
|
||||||
return (T) (f * 0.5f * (1.0f + ::erf(f * ALPHA)));
|
return (T)(f * 0.5f * (1.0f + ::erf(f * ALPHA)));
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace vllm
|
template <typename T>
|
||||||
|
__device__ __forceinline__ T gelu_tanh_kernel(const T& x) {
|
||||||
|
// Equivalent to PyTorch GELU with 'tanh' approximation.
|
||||||
|
// Refer to:
|
||||||
|
// https://github.com/pytorch/pytorch/blob/8ac9b20d4b090c213799e81acf48a55ea8d437d6/aten/src/ATen/native/cuda/ActivationGeluKernel.cu#L25-L30
|
||||||
|
const float f = (float)x;
|
||||||
|
constexpr float BETA = M_SQRT2 * M_2_SQRTPI * 0.5f;
|
||||||
|
constexpr float KAPPA = 0.044715;
|
||||||
|
float x_cube = f * f * f;
|
||||||
|
float inner = BETA * (f + KAPPA * x_cube);
|
||||||
|
return (T)(0.5f * f * (1.0f + ::tanhf(inner)));
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace vllm
|
||||||
|
|
||||||
// Launch activation and gating kernel.
|
// Launch activation and gating kernel.
|
||||||
#define LAUNCH_ACTIVATION_GATE_KERNEL(KERNEL) \
|
#define LAUNCH_ACTIVATION_GATE_KERNEL(KERNEL) \
|
||||||
int d = input.size(-1) / 2; \
|
int d = input.size(-1) / 2; \
|
||||||
int64_t num_tokens = input.numel() / input.size(-1); \
|
int64_t num_tokens = input.numel() / input.size(-1); \
|
||||||
dim3 grid(num_tokens); \
|
dim3 grid(num_tokens); \
|
||||||
dim3 block(std::min(d, 1024)); \
|
dim3 block(std::min(d, 1024)); \
|
||||||
const at::cuda::OptionalCUDAGuard device_guard(device_of(input)); \
|
const at::cuda::OptionalCUDAGuard device_guard(device_of(input)); \
|
||||||
const cudaStream_t stream = at::cuda::getCurrentCUDAStream(); \
|
const cudaStream_t stream = at::cuda::getCurrentCUDAStream(); \
|
||||||
VLLM_DISPATCH_FLOATING_TYPES( \
|
VLLM_DISPATCH_FLOATING_TYPES( \
|
||||||
input.scalar_type(), \
|
input.scalar_type(), "act_and_mul_kernel", [&] { \
|
||||||
"act_and_mul_kernel", \
|
vllm::act_and_mul_kernel<scalar_t, KERNEL<scalar_t>> \
|
||||||
[&] { \
|
<<<grid, block, 0, stream>>>(out.data_ptr<scalar_t>(), \
|
||||||
vllm::act_and_mul_kernel<scalar_t, KERNEL<scalar_t>><<<grid, block, 0, stream>>>( \
|
input.data_ptr<scalar_t>(), d); \
|
||||||
out.data_ptr<scalar_t>(), \
|
});
|
||||||
input.data_ptr<scalar_t>(), \
|
|
||||||
d); \
|
|
||||||
});
|
|
||||||
|
|
||||||
void silu_and_mul(
|
void silu_and_mul(torch::Tensor& out, // [..., d]
|
||||||
torch::Tensor& out, // [..., d]
|
torch::Tensor& input) // [..., 2 * d]
|
||||||
torch::Tensor& input) // [..., 2 * d]
|
|
||||||
{
|
{
|
||||||
LAUNCH_ACTIVATION_GATE_KERNEL(vllm::silu_kernel);
|
LAUNCH_ACTIVATION_GATE_KERNEL(vllm::silu_kernel);
|
||||||
}
|
}
|
||||||
|
|
||||||
void gelu_and_mul(
|
void gelu_and_mul(torch::Tensor& out, // [..., d]
|
||||||
torch::Tensor& out, // [..., d]
|
torch::Tensor& input) // [..., 2 * d]
|
||||||
torch::Tensor& input) // [..., 2 * d]
|
|
||||||
{
|
{
|
||||||
LAUNCH_ACTIVATION_GATE_KERNEL(vllm::gelu_kernel);
|
LAUNCH_ACTIVATION_GATE_KERNEL(vllm::gelu_kernel);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void gelu_tanh_and_mul(torch::Tensor& out, // [..., d]
|
||||||
|
torch::Tensor& input) // [..., 2 * d]
|
||||||
|
{
|
||||||
|
LAUNCH_ACTIVATION_GATE_KERNEL(vllm::gelu_tanh_kernel);
|
||||||
|
}
|
||||||
|
|
||||||
namespace vllm {
|
namespace vllm {
|
||||||
|
|
||||||
// Element-wise activation kernel template.
|
// Element-wise activation kernel template.
|
||||||
template<typename scalar_t, scalar_t (*ACT_FN)(const scalar_t&)>
|
template <typename scalar_t, scalar_t (*ACT_FN)(const scalar_t&)>
|
||||||
__global__ void activation_kernel(
|
__global__ void activation_kernel(
|
||||||
scalar_t* __restrict__ out, // [..., d]
|
scalar_t* __restrict__ out, // [..., d]
|
||||||
const scalar_t* __restrict__ input, // [..., d]
|
const scalar_t* __restrict__ input, // [..., d]
|
||||||
const int d) {
|
const int d) {
|
||||||
const int64_t token_idx = blockIdx.x;
|
const int64_t token_idx = blockIdx.x;
|
||||||
for (int64_t idx = threadIdx.x; idx < d; idx += blockDim.x) {
|
for (int64_t idx = threadIdx.x; idx < d; idx += blockDim.x) {
|
||||||
const scalar_t x = VLLM_LDG(&input[token_idx * d + idx]);
|
const scalar_t x = VLLM_LDG(&input[token_idx * d + idx]);
|
||||||
@ -88,54 +102,61 @@ __global__ void activation_kernel(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace vllm
|
} // namespace vllm
|
||||||
|
|
||||||
// Launch element-wise activation kernel.
|
// Launch element-wise activation kernel.
|
||||||
#define LAUNCH_ACTIVATION_KERNEL(KERNEL) \
|
#define LAUNCH_ACTIVATION_KERNEL(KERNEL) \
|
||||||
int d = input.size(-1); \
|
int d = input.size(-1); \
|
||||||
int64_t num_tokens = input.numel() / d; \
|
int64_t num_tokens = input.numel() / d; \
|
||||||
dim3 grid(num_tokens); \
|
dim3 grid(num_tokens); \
|
||||||
dim3 block(std::min(d, 1024)); \
|
dim3 block(std::min(d, 1024)); \
|
||||||
const at::cuda::OptionalCUDAGuard device_guard(device_of(input)); \
|
const at::cuda::OptionalCUDAGuard device_guard(device_of(input)); \
|
||||||
const cudaStream_t stream = at::cuda::getCurrentCUDAStream(); \
|
const cudaStream_t stream = at::cuda::getCurrentCUDAStream(); \
|
||||||
VLLM_DISPATCH_FLOATING_TYPES( \
|
VLLM_DISPATCH_FLOATING_TYPES(input.scalar_type(), "activation_kernel", [&] { \
|
||||||
input.scalar_type(), \
|
vllm::activation_kernel<scalar_t, KERNEL<scalar_t>> \
|
||||||
"activation_kernel", \
|
<<<grid, block, 0, stream>>>(out.data_ptr<scalar_t>(), \
|
||||||
[&] { \
|
input.data_ptr<scalar_t>(), d); \
|
||||||
vllm::activation_kernel<scalar_t, KERNEL<scalar_t>><<<grid, block, 0, stream>>>( \
|
});
|
||||||
out.data_ptr<scalar_t>(), \
|
|
||||||
input.data_ptr<scalar_t>(), \
|
|
||||||
d); \
|
|
||||||
});
|
|
||||||
|
|
||||||
namespace vllm {
|
namespace vllm {
|
||||||
|
|
||||||
template<typename T>
|
template <typename T>
|
||||||
__device__ __forceinline__ T gelu_new_kernel(const T& x) {
|
__device__ __forceinline__ T gelu_new_kernel(const T& x) {
|
||||||
const float x3 = (float) (x * x * x);
|
const float x3 = (float)(x * x * x);
|
||||||
const T t = (T) tanhf((T) (0.79788456f * (float) (x + (T) (0.044715f * x3))));
|
const T t = (T)tanhf((T)(0.79788456f * (float)(x + (T)(0.044715f * x3))));
|
||||||
return ((T) 0.5) * x * (((T) 1.0) + t);
|
return ((T)0.5) * x * (((T)1.0) + t);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename T>
|
template <typename T>
|
||||||
__device__ __forceinline__ T gelu_fast_kernel(const T& x) {
|
__device__ __forceinline__ T gelu_fast_kernel(const T& x) {
|
||||||
const float f = (float) x;
|
const float f = (float)x;
|
||||||
const T t = (T) tanhf(((T) (f * 0.79788456f)) * (((T) 1.0) + (T) (0.044715f * f) * x));
|
const T t =
|
||||||
return ((T) 0.5) * x * (((T) 1.0) + t);
|
(T)tanhf(((T)(f * 0.79788456f)) * (((T)1.0) + (T)(0.044715f * f) * x));
|
||||||
|
return ((T)0.5) * x * (((T)1.0) + t);
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace vllm
|
template <typename T>
|
||||||
|
__device__ __forceinline__ T gelu_quick_kernel(const T& x) {
|
||||||
|
// x * sigmoid(1.702 * x)
|
||||||
|
return (T)(((float)x) / (1.0f + expf(-1.702f * (float)x)));
|
||||||
|
}
|
||||||
|
|
||||||
void gelu_new(
|
} // namespace vllm
|
||||||
torch::Tensor& out, // [..., d]
|
|
||||||
torch::Tensor& input) // [..., d]
|
void gelu_new(torch::Tensor& out, // [..., d]
|
||||||
|
torch::Tensor& input) // [..., d]
|
||||||
{
|
{
|
||||||
LAUNCH_ACTIVATION_KERNEL(vllm::gelu_new_kernel);
|
LAUNCH_ACTIVATION_KERNEL(vllm::gelu_new_kernel);
|
||||||
}
|
}
|
||||||
|
|
||||||
void gelu_fast(
|
void gelu_fast(torch::Tensor& out, // [..., d]
|
||||||
torch::Tensor& out, // [..., d]
|
torch::Tensor& input) // [..., d]
|
||||||
torch::Tensor& input) // [..., d]
|
|
||||||
{
|
{
|
||||||
LAUNCH_ACTIVATION_KERNEL(vllm::gelu_fast_kernel);
|
LAUNCH_ACTIVATION_KERNEL(vllm::gelu_fast_kernel);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void gelu_quick(torch::Tensor& out, // [..., d]
|
||||||
|
torch::Tensor& input) // [..., d]
|
||||||
|
{
|
||||||
|
LAUNCH_ACTIVATION_KERNEL(vllm::gelu_quick_kernel);
|
||||||
|
}
|
||||||
|
|||||||
@ -4,4 +4,4 @@
|
|||||||
#include "dtype_float16.cuh"
|
#include "dtype_float16.cuh"
|
||||||
#include "dtype_float32.cuh"
|
#include "dtype_float32.cuh"
|
||||||
#include "dtype_bfloat16.cuh"
|
#include "dtype_bfloat16.cuh"
|
||||||
#include "dtype_fp8_e5m2.cuh"
|
#include "dtype_fp8.cuh"
|
||||||
|
|||||||
@ -1,5 +1,6 @@
|
|||||||
/*
|
/*
|
||||||
* Adapted from https://github.com/NVIDIA/FasterTransformer/blob/release/v5.3_tag/src/fastertransformer/kernels/decoder_masked_multihead_attention_utils.h
|
* Adapted from
|
||||||
|
* https://github.com/NVIDIA/FasterTransformer/blob/release/v5.3_tag/src/fastertransformer/kernels/decoder_masked_multihead_attention_utils.h
|
||||||
* Copyright (c) 2023, The vLLM team.
|
* Copyright (c) 2023, The vLLM team.
|
||||||
* Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
|
* Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
|
||||||
*
|
*
|
||||||
@ -22,31 +23,31 @@
|
|||||||
namespace vllm {
|
namespace vllm {
|
||||||
|
|
||||||
// A vector type to store Q, K, V elements.
|
// A vector type to store Q, K, V elements.
|
||||||
template<typename T, int VEC_SIZE>
|
template <typename T, int VEC_SIZE>
|
||||||
struct Vec {};
|
struct Vec {};
|
||||||
|
|
||||||
// A vector type to store FP32 accumulators.
|
// A vector type to store FP32 accumulators.
|
||||||
template<typename T>
|
template <typename T>
|
||||||
struct FloatVec {};
|
struct FloatVec {};
|
||||||
|
|
||||||
// Template vector operations.
|
// Template vector operations.
|
||||||
template<typename Acc, typename A, typename B>
|
template <typename Acc, typename A, typename B>
|
||||||
inline __device__ Acc mul(A a, B b);
|
inline __device__ Acc mul(A a, B b);
|
||||||
|
|
||||||
template<typename T>
|
template <typename T>
|
||||||
inline __device__ float sum(T v);
|
inline __device__ float sum(T v);
|
||||||
|
|
||||||
template<typename T>
|
template <typename T>
|
||||||
inline __device__ float dot(T a, T b) {
|
inline __device__ float dot(T a, T b) {
|
||||||
return sum(mul<T, T, T>(a, b));
|
return sum(mul<T, T, T>(a, b));
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename A, typename T>
|
template <typename A, typename T>
|
||||||
inline __device__ float dot(T a, T b) {
|
inline __device__ float dot(T a, T b) {
|
||||||
return sum(mul<A, T, T>(a, b));
|
return sum(mul<A, T, T>(a, b));
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename T>
|
template <typename T>
|
||||||
inline __device__ void zero(T& dst) {
|
inline __device__ void zero(T& dst) {
|
||||||
constexpr int WORDS = sizeof(T) / 4;
|
constexpr int WORDS = sizeof(T) / 4;
|
||||||
union {
|
union {
|
||||||
@ -61,4 +62,4 @@ inline __device__ void zero(T& dst) {
|
|||||||
dst = tmp.raw;
|
dst = tmp.raw;
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace vllm
|
} // namespace vllm
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@ -1,5 +1,6 @@
|
|||||||
/*
|
/*
|
||||||
* Adapted from https://github.com/NVIDIA/FasterTransformer/blob/release/v5.3_tag/src/fastertransformer/kernels/decoder_masked_multihead_attention/decoder_masked_multihead_attention_template.hpp
|
* Adapted from
|
||||||
|
* https://github.com/NVIDIA/FasterTransformer/blob/release/v5.3_tag/src/fastertransformer/kernels/decoder_masked_multihead_attention/decoder_masked_multihead_attention_template.hpp
|
||||||
* Copyright (c) 2023, The vLLM team.
|
* Copyright (c) 2023, The vLLM team.
|
||||||
* Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
|
* Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
|
||||||
*
|
*
|
||||||
@ -26,7 +27,7 @@
|
|||||||
namespace vllm {
|
namespace vllm {
|
||||||
|
|
||||||
// Q*K^T operation.
|
// Q*K^T operation.
|
||||||
template<int THREAD_GROUP_SIZE, typename Vec, int N>
|
template <int THREAD_GROUP_SIZE, typename Vec, int N>
|
||||||
inline __device__ float qk_dot_(const Vec (&q)[N], const Vec (&k)[N]) {
|
inline __device__ float qk_dot_(const Vec (&q)[N], const Vec (&k)[N]) {
|
||||||
using A_vec = typename FloatVec<Vec>::Type;
|
using A_vec = typename FloatVec<Vec>::Type;
|
||||||
// Compute the parallel products for Q*K^T (treat vector lanes separately).
|
// Compute the parallel products for Q*K^T (treat vector lanes separately).
|
||||||
@ -45,12 +46,12 @@ inline __device__ float qk_dot_(const Vec (&q)[N], const Vec (&k)[N]) {
|
|||||||
return qk;
|
return qk;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename T, int THREAD_GROUP_SIZE>
|
template <typename T, int THREAD_GROUP_SIZE>
|
||||||
struct Qk_dot {
|
struct Qk_dot {
|
||||||
template<typename Vec, int N>
|
template <typename Vec, int N>
|
||||||
static inline __device__ float dot(const Vec (&q)[N], const Vec (&k)[N]) {
|
static inline __device__ float dot(const Vec (&q)[N], const Vec (&k)[N]) {
|
||||||
return qk_dot_<THREAD_GROUP_SIZE>(q, k);
|
return qk_dot_<THREAD_GROUP_SIZE>(q, k);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace vllm
|
} // namespace vllm
|
||||||
|
|||||||
@ -1,6 +1,8 @@
|
|||||||
/*
|
/*
|
||||||
* Adapted from https://github.com/NVIDIA/FasterTransformer/blob/release/v5.3_tag/src/fastertransformer/kernels/decoder_masked_multihead_attention/decoder_masked_multihead_attention_template.hpp
|
* Adapted from
|
||||||
* and https://github.com/NVIDIA/FasterTransformer/blob/release/v5.3_tag/src/fastertransformer/kernels/decoder_masked_multihead_attention_utils.h
|
* https://github.com/NVIDIA/FasterTransformer/blob/release/v5.3_tag/src/fastertransformer/kernels/decoder_masked_multihead_attention/decoder_masked_multihead_attention_template.hpp
|
||||||
|
* and
|
||||||
|
* https://github.com/NVIDIA/FasterTransformer/blob/release/v5.3_tag/src/fastertransformer/kernels/decoder_masked_multihead_attention_utils.h
|
||||||
* Copyright (c) 2023, The vLLM team.
|
* Copyright (c) 2023, The vLLM team.
|
||||||
* Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
|
* Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
|
||||||
*
|
*
|
||||||
@ -28,8 +30,8 @@
|
|||||||
#include <hip/hip_bf16.h>
|
#include <hip/hip_bf16.h>
|
||||||
#include <hip/hip_fp16.h>
|
#include <hip/hip_fp16.h>
|
||||||
|
|
||||||
typedef __hip_bfloat162 __nv_bfloat162;
|
typedef __hip_bfloat162 __nv_bfloat162;
|
||||||
typedef __hip_bfloat16 __nv_bfloat16;
|
typedef __hip_bfloat16 __nv_bfloat16;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#include <stdint.h>
|
#include <stdint.h>
|
||||||
@ -50,37 +52,37 @@ struct bf16_8_t {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// BF16 vector types for Q, K, V.
|
// BF16 vector types for Q, K, V.
|
||||||
template<>
|
template <>
|
||||||
struct Vec<__nv_bfloat16, 1> {
|
struct Vec<__nv_bfloat16, 1> {
|
||||||
using Type = __nv_bfloat16;
|
using Type = __nv_bfloat16;
|
||||||
};
|
};
|
||||||
template<>
|
template <>
|
||||||
struct Vec<__nv_bfloat16, 2> {
|
struct Vec<__nv_bfloat16, 2> {
|
||||||
using Type = __nv_bfloat162;
|
using Type = __nv_bfloat162;
|
||||||
};
|
};
|
||||||
template<>
|
template <>
|
||||||
struct Vec<__nv_bfloat16, 4> {
|
struct Vec<__nv_bfloat16, 4> {
|
||||||
using Type = bf16_4_t;
|
using Type = bf16_4_t;
|
||||||
};
|
};
|
||||||
template<>
|
template <>
|
||||||
struct Vec<__nv_bfloat16, 8> {
|
struct Vec<__nv_bfloat16, 8> {
|
||||||
using Type = bf16_8_t;
|
using Type = bf16_8_t;
|
||||||
};
|
};
|
||||||
|
|
||||||
// FP32 accumulator vector types corresponding to Vec.
|
// FP32 accumulator vector types corresponding to Vec.
|
||||||
template<>
|
template <>
|
||||||
struct FloatVec<__nv_bfloat16> {
|
struct FloatVec<__nv_bfloat16> {
|
||||||
using Type = float;
|
using Type = float;
|
||||||
};
|
};
|
||||||
template<>
|
template <>
|
||||||
struct FloatVec<__nv_bfloat162> {
|
struct FloatVec<__nv_bfloat162> {
|
||||||
using Type = float2;
|
using Type = float2;
|
||||||
};
|
};
|
||||||
template<>
|
template <>
|
||||||
struct FloatVec<bf16_4_t> {
|
struct FloatVec<bf16_4_t> {
|
||||||
using Type = Float4_;
|
using Type = Float4_;
|
||||||
};
|
};
|
||||||
template<>
|
template <>
|
||||||
struct FloatVec<bf16_8_t> {
|
struct FloatVec<bf16_8_t> {
|
||||||
using Type = Float8_;
|
using Type = Float8_;
|
||||||
};
|
};
|
||||||
@ -108,9 +110,9 @@ inline __device__ __nv_bfloat16 add(__nv_bfloat16 a, __nv_bfloat16 b) {
|
|||||||
assert(false);
|
assert(false);
|
||||||
#else
|
#else
|
||||||
#ifndef USE_ROCM
|
#ifndef USE_ROCM
|
||||||
return a + b;
|
return a + b;
|
||||||
#else
|
#else
|
||||||
return __hadd(a, b);
|
return __hadd(a, b);
|
||||||
#endif
|
#endif
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
@ -161,7 +163,7 @@ inline __device__ Float8_ add(bf16_8_t a, Float8_ fb) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Vector multiplication.
|
// Vector multiplication.
|
||||||
template<>
|
template <>
|
||||||
inline __device__ __nv_bfloat16 mul(__nv_bfloat16 a, __nv_bfloat16 b) {
|
inline __device__ __nv_bfloat16 mul(__nv_bfloat16 a, __nv_bfloat16 b) {
|
||||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
|
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
|
||||||
assert(false);
|
assert(false);
|
||||||
@ -170,7 +172,7 @@ inline __device__ __nv_bfloat16 mul(__nv_bfloat16 a, __nv_bfloat16 b) {
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ __nv_bfloat162 mul(__nv_bfloat162 a, __nv_bfloat162 b) {
|
inline __device__ __nv_bfloat162 mul(__nv_bfloat162 a, __nv_bfloat162 b) {
|
||||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
|
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
|
||||||
assert(false);
|
assert(false);
|
||||||
@ -179,12 +181,12 @@ inline __device__ __nv_bfloat162 mul(__nv_bfloat162 a, __nv_bfloat162 b) {
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ __nv_bfloat162 mul(__nv_bfloat16 a, __nv_bfloat162 b) {
|
inline __device__ __nv_bfloat162 mul(__nv_bfloat16 a, __nv_bfloat162 b) {
|
||||||
return mul<__nv_bfloat162, __nv_bfloat162, __nv_bfloat162>(bf162bf162(a), b);
|
return mul<__nv_bfloat162, __nv_bfloat162, __nv_bfloat162>(bf162bf162(a), b);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ bf16_4_t mul(bf16_4_t a, bf16_4_t b) {
|
inline __device__ bf16_4_t mul(bf16_4_t a, bf16_4_t b) {
|
||||||
bf16_4_t c;
|
bf16_4_t c;
|
||||||
c.x = mul<__nv_bfloat162, __nv_bfloat162, __nv_bfloat162>(a.x, b.x);
|
c.x = mul<__nv_bfloat162, __nv_bfloat162, __nv_bfloat162>(a.x, b.x);
|
||||||
@ -192,7 +194,7 @@ inline __device__ bf16_4_t mul(bf16_4_t a, bf16_4_t b) {
|
|||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ bf16_4_t mul(__nv_bfloat16 a, bf16_4_t b) {
|
inline __device__ bf16_4_t mul(__nv_bfloat16 a, bf16_4_t b) {
|
||||||
__nv_bfloat162 s = bf162bf162(a);
|
__nv_bfloat162 s = bf162bf162(a);
|
||||||
bf16_4_t c;
|
bf16_4_t c;
|
||||||
@ -201,7 +203,7 @@ inline __device__ bf16_4_t mul(__nv_bfloat16 a, bf16_4_t b) {
|
|||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ bf16_8_t mul(bf16_8_t a, bf16_8_t b) {
|
inline __device__ bf16_8_t mul(bf16_8_t a, bf16_8_t b) {
|
||||||
bf16_8_t c;
|
bf16_8_t c;
|
||||||
c.x = mul<__nv_bfloat162, __nv_bfloat162, __nv_bfloat162>(a.x, b.x);
|
c.x = mul<__nv_bfloat162, __nv_bfloat162, __nv_bfloat162>(a.x, b.x);
|
||||||
@ -211,7 +213,7 @@ inline __device__ bf16_8_t mul(bf16_8_t a, bf16_8_t b) {
|
|||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ bf16_8_t mul(__nv_bfloat16 a, bf16_8_t b) {
|
inline __device__ bf16_8_t mul(__nv_bfloat16 a, bf16_8_t b) {
|
||||||
__nv_bfloat162 s = bf162bf162(a);
|
__nv_bfloat162 s = bf162bf162(a);
|
||||||
bf16_8_t c;
|
bf16_8_t c;
|
||||||
@ -222,26 +224,26 @@ inline __device__ bf16_8_t mul(__nv_bfloat16 a, bf16_8_t b) {
|
|||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float mul(__nv_bfloat16 a, __nv_bfloat16 b) {
|
inline __device__ float mul(__nv_bfloat16 a, __nv_bfloat16 b) {
|
||||||
float fa = __bfloat162float(a);
|
float fa = __bfloat162float(a);
|
||||||
float fb = __bfloat162float(b);
|
float fb = __bfloat162float(b);
|
||||||
return fa * fb;
|
return fa * fb;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float2 mul(__nv_bfloat162 a, __nv_bfloat162 b) {
|
inline __device__ float2 mul(__nv_bfloat162 a, __nv_bfloat162 b) {
|
||||||
float2 fa = bf1622float2(a);
|
float2 fa = bf1622float2(a);
|
||||||
float2 fb = bf1622float2(b);
|
float2 fb = bf1622float2(b);
|
||||||
return mul<float2, float2, float2>(fa, fb);
|
return mul<float2, float2, float2>(fa, fb);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float2 mul(__nv_bfloat16 a, __nv_bfloat162 b) {
|
inline __device__ float2 mul(__nv_bfloat16 a, __nv_bfloat162 b) {
|
||||||
return mul<float2, __nv_bfloat162, __nv_bfloat162>(bf162bf162(a), b);
|
return mul<float2, __nv_bfloat162, __nv_bfloat162>(bf162bf162(a), b);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ Float4_ mul(bf16_4_t a, bf16_4_t b) {
|
inline __device__ Float4_ mul(bf16_4_t a, bf16_4_t b) {
|
||||||
Float4_ fc;
|
Float4_ fc;
|
||||||
fc.x = mul<float2, __nv_bfloat162, __nv_bfloat162>(a.x, b.x);
|
fc.x = mul<float2, __nv_bfloat162, __nv_bfloat162>(a.x, b.x);
|
||||||
@ -249,7 +251,7 @@ inline __device__ Float4_ mul(bf16_4_t a, bf16_4_t b) {
|
|||||||
return fc;
|
return fc;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ Float4_ mul(__nv_bfloat16 a, bf16_4_t b) {
|
inline __device__ Float4_ mul(__nv_bfloat16 a, bf16_4_t b) {
|
||||||
__nv_bfloat162 s = bf162bf162(a);
|
__nv_bfloat162 s = bf162bf162(a);
|
||||||
Float4_ fc;
|
Float4_ fc;
|
||||||
@ -258,7 +260,7 @@ inline __device__ Float4_ mul(__nv_bfloat16 a, bf16_4_t b) {
|
|||||||
return fc;
|
return fc;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ Float8_ mul(bf16_8_t a, bf16_8_t b) {
|
inline __device__ Float8_ mul(bf16_8_t a, bf16_8_t b) {
|
||||||
Float8_ fc;
|
Float8_ fc;
|
||||||
fc.x = mul<float2, __nv_bfloat162, __nv_bfloat162>(a.x, b.x);
|
fc.x = mul<float2, __nv_bfloat162, __nv_bfloat162>(a.x, b.x);
|
||||||
@ -268,7 +270,7 @@ inline __device__ Float8_ mul(bf16_8_t a, bf16_8_t b) {
|
|||||||
return fc;
|
return fc;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ Float8_ mul(__nv_bfloat16 a, bf16_8_t b) {
|
inline __device__ Float8_ mul(__nv_bfloat16 a, bf16_8_t b) {
|
||||||
__nv_bfloat162 s = bf162bf162(a);
|
__nv_bfloat162 s = bf162bf162(a);
|
||||||
Float8_ fc;
|
Float8_ fc;
|
||||||
@ -280,7 +282,8 @@ inline __device__ Float8_ mul(__nv_bfloat16 a, bf16_8_t b) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Vector fused multiply-add.
|
// Vector fused multiply-add.
|
||||||
inline __device__ __nv_bfloat162 fma(__nv_bfloat162 a, __nv_bfloat162 b, __nv_bfloat162 c) {
|
inline __device__ __nv_bfloat162 fma(__nv_bfloat162 a, __nv_bfloat162 b,
|
||||||
|
__nv_bfloat162 c) {
|
||||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
|
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
|
||||||
assert(false);
|
assert(false);
|
||||||
#else
|
#else
|
||||||
@ -288,7 +291,8 @@ inline __device__ __nv_bfloat162 fma(__nv_bfloat162 a, __nv_bfloat162 b, __nv_bf
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
inline __device__ __nv_bfloat162 fma(__nv_bfloat16 a, __nv_bfloat162 b, __nv_bfloat162 c) {
|
inline __device__ __nv_bfloat162 fma(__nv_bfloat16 a, __nv_bfloat162 b,
|
||||||
|
__nv_bfloat162 c) {
|
||||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
|
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
|
||||||
assert(false);
|
assert(false);
|
||||||
#else
|
#else
|
||||||
@ -379,23 +383,23 @@ inline __device__ Float8_ fma(__nv_bfloat16 a, bf16_8_t b, Float8_ fc) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Vector sum.
|
// Vector sum.
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float sum(__nv_bfloat16 v) {
|
inline __device__ float sum(__nv_bfloat16 v) {
|
||||||
return __bfloat162float(v);
|
return __bfloat162float(v);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float sum(__nv_bfloat162 v) {
|
inline __device__ float sum(__nv_bfloat162 v) {
|
||||||
float2 vf = bf1622float2(v);
|
float2 vf = bf1622float2(v);
|
||||||
return vf.x + vf.y;
|
return vf.x + vf.y;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float sum(bf16_4_t v) {
|
inline __device__ float sum(bf16_4_t v) {
|
||||||
return sum(v.x) + sum(v.y);
|
return sum(v.x) + sum(v.y);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float sum(bf16_8_t v) {
|
inline __device__ float sum(bf16_8_t v) {
|
||||||
return sum(v.x) + sum(v.y) + sum(v.z) + sum(v.w);
|
return sum(v.x) + sum(v.y) + sum(v.z) + sum(v.w);
|
||||||
}
|
}
|
||||||
@ -448,4 +452,4 @@ inline __device__ void zero(__nv_bfloat16& dst) {
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace vllm
|
} // namespace vllm
|
||||||
|
|||||||
@ -1,6 +1,8 @@
|
|||||||
/*
|
/*
|
||||||
* Adapted from https://github.com/NVIDIA/FasterTransformer/blob/release/v5.3_tag/src/fastertransformer/kernels/decoder_masked_multihead_attention/decoder_masked_multihead_attention_template.hpp
|
* Adapted from
|
||||||
* and https://github.com/NVIDIA/FasterTransformer/blob/release/v5.3_tag/src/fastertransformer/kernels/decoder_masked_multihead_attention_utils.h
|
* https://github.com/NVIDIA/FasterTransformer/blob/release/v5.3_tag/src/fastertransformer/kernels/decoder_masked_multihead_attention/decoder_masked_multihead_attention_template.hpp
|
||||||
|
* and
|
||||||
|
* https://github.com/NVIDIA/FasterTransformer/blob/release/v5.3_tag/src/fastertransformer/kernels/decoder_masked_multihead_attention_utils.h
|
||||||
* Copyright (c) 2023, The vLLM team.
|
* Copyright (c) 2023, The vLLM team.
|
||||||
* Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
|
* Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
|
||||||
*
|
*
|
||||||
@ -30,37 +32,37 @@
|
|||||||
namespace vllm {
|
namespace vllm {
|
||||||
|
|
||||||
// FP16 vector types for Q, K, V.
|
// FP16 vector types for Q, K, V.
|
||||||
template<>
|
template <>
|
||||||
struct Vec<uint16_t, 1> {
|
struct Vec<uint16_t, 1> {
|
||||||
using Type = uint16_t;
|
using Type = uint16_t;
|
||||||
};
|
};
|
||||||
template<>
|
template <>
|
||||||
struct Vec<uint16_t, 2> {
|
struct Vec<uint16_t, 2> {
|
||||||
using Type = uint32_t;
|
using Type = uint32_t;
|
||||||
};
|
};
|
||||||
template<>
|
template <>
|
||||||
struct Vec<uint16_t, 4> {
|
struct Vec<uint16_t, 4> {
|
||||||
using Type = uint2;
|
using Type = uint2;
|
||||||
};
|
};
|
||||||
template<>
|
template <>
|
||||||
struct Vec<uint16_t, 8> {
|
struct Vec<uint16_t, 8> {
|
||||||
using Type = uint4;
|
using Type = uint4;
|
||||||
};
|
};
|
||||||
|
|
||||||
// FP32 accumulator vector types corresponding to Vec.
|
// FP32 accumulator vector types corresponding to Vec.
|
||||||
template<>
|
template <>
|
||||||
struct FloatVec<uint16_t> {
|
struct FloatVec<uint16_t> {
|
||||||
using Type = float;
|
using Type = float;
|
||||||
};
|
};
|
||||||
template<>
|
template <>
|
||||||
struct FloatVec<uint32_t> {
|
struct FloatVec<uint32_t> {
|
||||||
using Type = float2;
|
using Type = float2;
|
||||||
};
|
};
|
||||||
template<>
|
template <>
|
||||||
struct FloatVec<uint2> {
|
struct FloatVec<uint2> {
|
||||||
using Type = Float4_;
|
using Type = Float4_;
|
||||||
};
|
};
|
||||||
template<>
|
template <>
|
||||||
struct FloatVec<uint4> {
|
struct FloatVec<uint4> {
|
||||||
using Type = Float8_;
|
using Type = Float8_;
|
||||||
};
|
};
|
||||||
@ -73,8 +75,8 @@ inline __device__ uint32_t h0_h0(uint16_t a) {
|
|||||||
return b;
|
return b;
|
||||||
#else
|
#else
|
||||||
union {
|
union {
|
||||||
uint32_t u32;
|
uint32_t u32;
|
||||||
uint16_t u16[2];
|
uint16_t u16[2];
|
||||||
} tmp;
|
} tmp;
|
||||||
tmp.u16[0] = a;
|
tmp.u16[0] = a;
|
||||||
tmp.u16[1] = a;
|
tmp.u16[1] = a;
|
||||||
@ -130,10 +132,12 @@ inline __device__ uint32_t float2_to_half2(float2 f) {
|
|||||||
} tmp;
|
} tmp;
|
||||||
#ifndef USE_ROCM
|
#ifndef USE_ROCM
|
||||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
|
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
|
||||||
asm volatile("cvt.rn.f16x2.f32 %0, %1, %2;\n" : "=r"(tmp.u32) : "f"(f.y), "f"(f.x));
|
asm volatile("cvt.rn.f16x2.f32 %0, %1, %2;\n"
|
||||||
|
: "=r"(tmp.u32)
|
||||||
|
: "f"(f.y), "f"(f.x));
|
||||||
#else
|
#else
|
||||||
asm volatile("cvt.rn.f16.f32 %0, %1;\n" : "=h"(tmp.u16[0]) : "f"(f.x));
|
asm volatile("cvt.rn.f16.f32 %0, %1;\n" : "=h"(tmp.u16[0]) : "f"(f.x));
|
||||||
asm volatile("cvt.rn.f16.f32 %0, %1;\n" : "=h"(tmp.u16[1]) : "f"(f.y));
|
asm volatile("cvt.rn.f16.f32 %0, %1;\n" : "=h"(tmp.u16[1]) : "f"(f.y));
|
||||||
#endif
|
#endif
|
||||||
#else
|
#else
|
||||||
tmp.u16[0] = float_to_half(f.x);
|
tmp.u16[0] = float_to_half(f.x);
|
||||||
@ -201,7 +205,7 @@ inline __device__ Float8_ add(uint4 a, Float8_ fb) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Vector multiplication.
|
// Vector multiplication.
|
||||||
template<>
|
template <>
|
||||||
inline __device__ uint16_t mul(uint16_t a, uint16_t b) {
|
inline __device__ uint16_t mul(uint16_t a, uint16_t b) {
|
||||||
uint16_t c;
|
uint16_t c;
|
||||||
#ifndef USE_ROCM
|
#ifndef USE_ROCM
|
||||||
@ -212,7 +216,7 @@ inline __device__ uint16_t mul(uint16_t a, uint16_t b) {
|
|||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ uint32_t mul(uint32_t a, uint32_t b) {
|
inline __device__ uint32_t mul(uint32_t a, uint32_t b) {
|
||||||
uint32_t c;
|
uint32_t c;
|
||||||
#ifndef USE_ROCM
|
#ifndef USE_ROCM
|
||||||
@ -223,12 +227,12 @@ inline __device__ uint32_t mul(uint32_t a, uint32_t b) {
|
|||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ uint32_t mul(uint16_t a, uint32_t b) {
|
inline __device__ uint32_t mul(uint16_t a, uint32_t b) {
|
||||||
return mul<uint32_t, uint32_t, uint32_t>(h0_h0(a), b);
|
return mul<uint32_t, uint32_t, uint32_t>(h0_h0(a), b);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ uint2 mul(uint2 a, uint2 b) {
|
inline __device__ uint2 mul(uint2 a, uint2 b) {
|
||||||
uint2 c;
|
uint2 c;
|
||||||
c.x = mul<uint32_t, uint32_t, uint32_t>(a.x, b.x);
|
c.x = mul<uint32_t, uint32_t, uint32_t>(a.x, b.x);
|
||||||
@ -236,7 +240,7 @@ inline __device__ uint2 mul(uint2 a, uint2 b) {
|
|||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ uint2 mul(uint16_t a, uint2 b) {
|
inline __device__ uint2 mul(uint16_t a, uint2 b) {
|
||||||
uint32_t s = h0_h0(a);
|
uint32_t s = h0_h0(a);
|
||||||
uint2 c;
|
uint2 c;
|
||||||
@ -245,7 +249,7 @@ inline __device__ uint2 mul(uint16_t a, uint2 b) {
|
|||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ uint4 mul(uint4 a, uint4 b) {
|
inline __device__ uint4 mul(uint4 a, uint4 b) {
|
||||||
uint4 c;
|
uint4 c;
|
||||||
c.x = mul<uint32_t, uint32_t, uint32_t>(a.x, b.x);
|
c.x = mul<uint32_t, uint32_t, uint32_t>(a.x, b.x);
|
||||||
@ -255,7 +259,7 @@ inline __device__ uint4 mul(uint4 a, uint4 b) {
|
|||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ uint4 mul(uint16_t a, uint4 b) {
|
inline __device__ uint4 mul(uint16_t a, uint4 b) {
|
||||||
uint32_t s = h0_h0(a);
|
uint32_t s = h0_h0(a);
|
||||||
uint4 c;
|
uint4 c;
|
||||||
@ -266,26 +270,26 @@ inline __device__ uint4 mul(uint16_t a, uint4 b) {
|
|||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float mul(uint16_t a, uint16_t b) {
|
inline __device__ float mul(uint16_t a, uint16_t b) {
|
||||||
float fa = half_to_float(a);
|
float fa = half_to_float(a);
|
||||||
float fb = half_to_float(b);
|
float fb = half_to_float(b);
|
||||||
return fa * fb;
|
return fa * fb;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float2 mul(uint32_t a, uint32_t b) {
|
inline __device__ float2 mul(uint32_t a, uint32_t b) {
|
||||||
float2 fa = half2_to_float2(a);
|
float2 fa = half2_to_float2(a);
|
||||||
float2 fb = half2_to_float2(b);
|
float2 fb = half2_to_float2(b);
|
||||||
return mul<float2, float2, float2>(fa, fb);
|
return mul<float2, float2, float2>(fa, fb);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float2 mul(uint16_t a, uint32_t b) {
|
inline __device__ float2 mul(uint16_t a, uint32_t b) {
|
||||||
return mul<float2, uint32_t, uint32_t>(h0_h0(a), b);
|
return mul<float2, uint32_t, uint32_t>(h0_h0(a), b);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ Float4_ mul(uint2 a, uint2 b) {
|
inline __device__ Float4_ mul(uint2 a, uint2 b) {
|
||||||
Float4_ fc;
|
Float4_ fc;
|
||||||
fc.x = mul<float2, uint32_t, uint32_t>(a.x, b.x);
|
fc.x = mul<float2, uint32_t, uint32_t>(a.x, b.x);
|
||||||
@ -293,7 +297,7 @@ inline __device__ Float4_ mul(uint2 a, uint2 b) {
|
|||||||
return fc;
|
return fc;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ Float4_ mul(uint16_t a, uint2 b) {
|
inline __device__ Float4_ mul(uint16_t a, uint2 b) {
|
||||||
uint32_t s = h0_h0(a);
|
uint32_t s = h0_h0(a);
|
||||||
Float4_ fc;
|
Float4_ fc;
|
||||||
@ -302,7 +306,7 @@ inline __device__ Float4_ mul(uint16_t a, uint2 b) {
|
|||||||
return fc;
|
return fc;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ Float8_ mul(uint4 a, uint4 b) {
|
inline __device__ Float8_ mul(uint4 a, uint4 b) {
|
||||||
Float8_ fc;
|
Float8_ fc;
|
||||||
fc.x = mul<float2, uint32_t, uint32_t>(a.x, b.x);
|
fc.x = mul<float2, uint32_t, uint32_t>(a.x, b.x);
|
||||||
@ -312,7 +316,7 @@ inline __device__ Float8_ mul(uint4 a, uint4 b) {
|
|||||||
return fc;
|
return fc;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ Float8_ mul(uint16_t a, uint4 b) {
|
inline __device__ Float8_ mul(uint16_t a, uint4 b) {
|
||||||
uint32_t s = h0_h0(a);
|
uint32_t s = h0_h0(a);
|
||||||
Float8_ fc;
|
Float8_ fc;
|
||||||
@ -327,9 +331,13 @@ inline __device__ Float8_ mul(uint16_t a, uint4 b) {
|
|||||||
inline __device__ uint32_t fma(uint32_t a, uint32_t b, uint32_t c) {
|
inline __device__ uint32_t fma(uint32_t a, uint32_t b, uint32_t c) {
|
||||||
uint32_t d;
|
uint32_t d;
|
||||||
#ifndef USE_ROCM
|
#ifndef USE_ROCM
|
||||||
asm volatile("fma.rn.f16x2 %0, %1, %2, %3;\n" : "=r"(d) : "r"(a), "r"(b), "r"(c));
|
asm volatile("fma.rn.f16x2 %0, %1, %2, %3;\n"
|
||||||
|
: "=r"(d)
|
||||||
|
: "r"(a), "r"(b), "r"(c));
|
||||||
#else
|
#else
|
||||||
asm volatile("v_pk_fma_f16 %0, %1, %2, %3;\n" : "=v"(d) : "v"(a), "v"(b), "v"(c));
|
asm volatile("v_pk_fma_f16 %0, %1, %2, %3;\n"
|
||||||
|
: "=v"(d)
|
||||||
|
: "v"(a), "v"(b), "v"(c));
|
||||||
#endif
|
#endif
|
||||||
return d;
|
return d;
|
||||||
}
|
}
|
||||||
@ -423,24 +431,24 @@ inline __device__ Float8_ fma(uint16_t a, uint4 b, Float8_ fc) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Vector sum.
|
// Vector sum.
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float sum(uint16_t v) {
|
inline __device__ float sum(uint16_t v) {
|
||||||
return half_to_float(v);
|
return half_to_float(v);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float sum(uint32_t v) {
|
inline __device__ float sum(uint32_t v) {
|
||||||
float2 tmp = half2_to_float2(v);
|
float2 tmp = half2_to_float2(v);
|
||||||
return tmp.x + tmp.y;
|
return tmp.x + tmp.y;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float sum(uint2 v) {
|
inline __device__ float sum(uint2 v) {
|
||||||
uint32_t c = add(v.x, v.y);
|
uint32_t c = add(v.x, v.y);
|
||||||
return sum(c);
|
return sum(c);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float sum(uint4 v) {
|
inline __device__ float sum(uint4 v) {
|
||||||
uint32_t c = add(v.x, v.y);
|
uint32_t c = add(v.x, v.y);
|
||||||
c = add(c, v.z);
|
c = add(c, v.z);
|
||||||
@ -470,13 +478,9 @@ inline __device__ void from_float(uint4& dst, Float8_ src) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// From float16 to float32.
|
// From float16 to float32.
|
||||||
inline __device__ float to_float(uint16_t u) {
|
inline __device__ float to_float(uint16_t u) { return half_to_float(u); }
|
||||||
return half_to_float(u);
|
|
||||||
}
|
|
||||||
|
|
||||||
inline __device__ float2 to_float(uint32_t u) {
|
inline __device__ float2 to_float(uint32_t u) { return half2_to_float2(u); }
|
||||||
return half2_to_float2(u);
|
|
||||||
}
|
|
||||||
|
|
||||||
inline __device__ Float4_ to_float(uint2 u) {
|
inline __device__ Float4_ to_float(uint2 u) {
|
||||||
Float4_ tmp;
|
Float4_ tmp;
|
||||||
@ -495,8 +499,6 @@ inline __device__ Float8_ to_float(uint4 u) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Zero-out a variable.
|
// Zero-out a variable.
|
||||||
inline __device__ void zero(uint16_t& dst) {
|
inline __device__ void zero(uint16_t& dst) { dst = uint16_t(0); }
|
||||||
dst = uint16_t(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace vllm
|
} // namespace vllm
|
||||||
|
|||||||
@ -1,6 +1,8 @@
|
|||||||
/*
|
/*
|
||||||
* Adapted from https://github.com/NVIDIA/FasterTransformer/blob/release/v5.3_tag/src/fastertransformer/kernels/decoder_masked_multihead_attention/decoder_masked_multihead_attention_template.hpp
|
* Adapted from
|
||||||
* and https://github.com/NVIDIA/FasterTransformer/blob/release/v5.3_tag/src/fastertransformer/kernels/decoder_masked_multihead_attention_utils.h
|
* https://github.com/NVIDIA/FasterTransformer/blob/release/v5.3_tag/src/fastertransformer/kernels/decoder_masked_multihead_attention/decoder_masked_multihead_attention_template.hpp
|
||||||
|
* and
|
||||||
|
* https://github.com/NVIDIA/FasterTransformer/blob/release/v5.3_tag/src/fastertransformer/kernels/decoder_masked_multihead_attention_utils.h
|
||||||
* Copyright (c) 2023, The vLLM team.
|
* Copyright (c) 2023, The vLLM team.
|
||||||
* Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
|
* Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
|
||||||
*
|
*
|
||||||
@ -38,37 +40,35 @@ struct Float8_ {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// FP32 vector types for Q, K, V.
|
// FP32 vector types for Q, K, V.
|
||||||
template<>
|
template <>
|
||||||
struct Vec<float, 1> {
|
struct Vec<float, 1> {
|
||||||
using Type = float;
|
using Type = float;
|
||||||
};
|
};
|
||||||
template<>
|
template <>
|
||||||
struct Vec<float, 2> {
|
struct Vec<float, 2> {
|
||||||
using Type = float2;
|
using Type = float2;
|
||||||
};
|
};
|
||||||
template<>
|
template <>
|
||||||
struct Vec<float, 4> {
|
struct Vec<float, 4> {
|
||||||
using Type = float4;
|
using Type = float4;
|
||||||
};
|
};
|
||||||
|
|
||||||
// FP32 accumulator vector types corresponding to Vec.
|
// FP32 accumulator vector types corresponding to Vec.
|
||||||
template<>
|
template <>
|
||||||
struct FloatVec<float> {
|
struct FloatVec<float> {
|
||||||
using Type = float;
|
using Type = float;
|
||||||
};
|
};
|
||||||
template<>
|
template <>
|
||||||
struct FloatVec<float2> {
|
struct FloatVec<float2> {
|
||||||
using Type = float2;
|
using Type = float2;
|
||||||
};
|
};
|
||||||
template<>
|
template <>
|
||||||
struct FloatVec<float4> {
|
struct FloatVec<float4> {
|
||||||
using Type = float4;
|
using Type = float4;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Vector addition.
|
// Vector addition.
|
||||||
inline __device__ float add(float a, float b) {
|
inline __device__ float add(float a, float b) { return a + b; }
|
||||||
return a + b;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline __device__ float2 add(float2 a, float2 b) {
|
inline __device__ float2 add(float2 a, float2 b) {
|
||||||
float2 c;
|
float2 c;
|
||||||
@ -87,12 +87,12 @@ inline __device__ float4 add(float4 a, float4 b) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Vector multiplication.
|
// Vector multiplication.
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float mul<float, float>(float a, float b) {
|
inline __device__ float mul<float, float>(float a, float b) {
|
||||||
return a * b;
|
return a * b;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float2 mul(float2 a, float2 b) {
|
inline __device__ float2 mul(float2 a, float2 b) {
|
||||||
float2 c;
|
float2 c;
|
||||||
c.x = a.x * b.x;
|
c.x = a.x * b.x;
|
||||||
@ -100,7 +100,7 @@ inline __device__ float2 mul(float2 a, float2 b) {
|
|||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float2 mul(float a, float2 b) {
|
inline __device__ float2 mul(float a, float2 b) {
|
||||||
float2 c;
|
float2 c;
|
||||||
c.x = a * b.x;
|
c.x = a * b.x;
|
||||||
@ -108,7 +108,7 @@ inline __device__ float2 mul(float a, float2 b) {
|
|||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float4 mul(float4 a, float4 b) {
|
inline __device__ float4 mul(float4 a, float4 b) {
|
||||||
float4 c;
|
float4 c;
|
||||||
c.x = a.x * b.x;
|
c.x = a.x * b.x;
|
||||||
@ -118,7 +118,7 @@ inline __device__ float4 mul(float4 a, float4 b) {
|
|||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float4 mul(float a, float4 b) {
|
inline __device__ float4 mul(float a, float4 b) {
|
||||||
float4 c;
|
float4 c;
|
||||||
c.x = a * b.x;
|
c.x = a * b.x;
|
||||||
@ -129,9 +129,7 @@ inline __device__ float4 mul(float a, float4 b) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Vector fused multiply-add.
|
// Vector fused multiply-add.
|
||||||
inline __device__ float fma(float a, float b, float c) {
|
inline __device__ float fma(float a, float b, float c) { return a * b + c; }
|
||||||
return a * b + c;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline __device__ float2 fma(float2 a, float2 b, float2 c) {
|
inline __device__ float2 fma(float2 a, float2 b, float2 c) {
|
||||||
float2 d;
|
float2 d;
|
||||||
@ -182,35 +180,33 @@ inline __device__ Float8_ fma(float a, Float8_ b, Float8_ c) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Vector sum.
|
// Vector sum.
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float sum(float v) {
|
inline __device__ float sum(float v) {
|
||||||
return v;
|
return v;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float sum(float2 v) {
|
inline __device__ float sum(float2 v) {
|
||||||
return v.x + v.y;
|
return v.x + v.y;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float sum(float4 v) {
|
inline __device__ float sum(float4 v) {
|
||||||
return v.x + v.y + v.z + v.w;
|
return v.x + v.y + v.z + v.w;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float sum(Float4_ v) {
|
inline __device__ float sum(Float4_ v) {
|
||||||
return v.x.x + v.x.y + v.y.x + v.y.y;
|
return v.x.x + v.x.y + v.y.x + v.y.y;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template <>
|
||||||
inline __device__ float sum(Float8_ v) {
|
inline __device__ float sum(Float8_ v) {
|
||||||
return v.x.x + v.x.y + v.y.x + v.y.y + v.z.x + v.z.y + v.w.x + v.w.y;
|
return v.x.x + v.x.y + v.y.x + v.y.y + v.z.x + v.z.y + v.w.x + v.w.y;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Vector dot product.
|
// Vector dot product.
|
||||||
inline __device__ float dot(float a, float b) {
|
inline __device__ float dot(float a, float b) { return a * b; }
|
||||||
return a * b;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline __device__ float dot(float2 a, float2 b) {
|
inline __device__ float dot(float2 a, float2 b) {
|
||||||
float2 c = mul<float2, float2, float2>(a, b);
|
float2 c = mul<float2, float2, float2>(a, b);
|
||||||
@ -232,42 +228,24 @@ inline __device__ float dot(Float8_ a, Float8_ b) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// From float to float.
|
// From float to float.
|
||||||
inline __device__ void from_float(float& dst, float src) {
|
inline __device__ void from_float(float& dst, float src) { dst = src; }
|
||||||
dst = src;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline __device__ void from_float(float2& dst, float2 src) {
|
inline __device__ void from_float(float2& dst, float2 src) { dst = src; }
|
||||||
dst = src;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline __device__ void from_float(float4& dst, float4 src) {
|
inline __device__ void from_float(float4& dst, float4 src) { dst = src; }
|
||||||
dst = src;
|
|
||||||
}
|
|
||||||
|
|
||||||
// From float to float.
|
// From float to float.
|
||||||
inline __device__ float to_float(float u) {
|
inline __device__ float to_float(float u) { return u; }
|
||||||
return u;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline __device__ float2 to_float(float2 u) {
|
inline __device__ float2 to_float(float2 u) { return u; }
|
||||||
return u;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline __device__ float4 to_float(float4 u) {
|
inline __device__ float4 to_float(float4 u) { return u; }
|
||||||
return u;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline __device__ Float4_ to_float(Float4_ u) {
|
inline __device__ Float4_ to_float(Float4_ u) { return u; }
|
||||||
return u;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline __device__ Float8_ to_float(Float8_ u) {
|
inline __device__ Float8_ to_float(Float8_ u) { return u; }
|
||||||
return u;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Zero-out a variable.
|
// Zero-out a variable.
|
||||||
inline __device__ void zero(float& dst) {
|
inline __device__ void zero(float& dst) { dst = 0.f; }
|
||||||
dst = 0.f;
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace vllm
|
} // namespace vllm
|
||||||
|
|||||||
41
csrc/attention/dtype_fp8.cuh
Normal file
41
csrc/attention/dtype_fp8.cuh
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "attention_generic.cuh"
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
#ifdef ENABLE_FP8
|
||||||
|
#ifndef USE_ROCM
|
||||||
|
#include <cuda_fp8.h>
|
||||||
|
#endif // USE_ROCM
|
||||||
|
#endif // ENABLE_FP8
|
||||||
|
|
||||||
|
namespace vllm {
|
||||||
|
|
||||||
|
enum class Fp8KVCacheDataType {
|
||||||
|
kAuto = 0,
|
||||||
|
kFp8E4M3 = 1,
|
||||||
|
kFp8E5M2 = 2,
|
||||||
|
};
|
||||||
|
|
||||||
|
// fp8 vector types for quantization of kv cache
|
||||||
|
template <>
|
||||||
|
struct Vec<uint8_t, 1> {
|
||||||
|
using Type = uint8_t;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <>
|
||||||
|
struct Vec<uint8_t, 2> {
|
||||||
|
using Type = uint16_t;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <>
|
||||||
|
struct Vec<uint8_t, 4> {
|
||||||
|
using Type = uint32_t;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <>
|
||||||
|
struct Vec<uint8_t, 8> {
|
||||||
|
using Type = uint2;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace vllm
|
||||||
@ -1,35 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include "attention_generic.cuh"
|
|
||||||
|
|
||||||
#include <stdint.h>
|
|
||||||
#ifdef ENABLE_FP8_E5M2
|
|
||||||
#include <cuda_fp8.h>
|
|
||||||
#endif
|
|
||||||
|
|
||||||
namespace vllm {
|
|
||||||
#ifdef ENABLE_FP8_E5M2
|
|
||||||
// fp8 vector types for quantization of kv cache
|
|
||||||
|
|
||||||
template<>
|
|
||||||
struct Vec<uint8_t, 1> {
|
|
||||||
using Type = uint8_t;
|
|
||||||
};
|
|
||||||
|
|
||||||
template<>
|
|
||||||
struct Vec<uint8_t, 2> {
|
|
||||||
using Type = uint16_t;
|
|
||||||
};
|
|
||||||
|
|
||||||
template<>
|
|
||||||
struct Vec<uint8_t, 4> {
|
|
||||||
using Type = uint32_t;
|
|
||||||
};
|
|
||||||
|
|
||||||
template<>
|
|
||||||
struct Vec<uint8_t, 8> {
|
|
||||||
using Type = uint2;
|
|
||||||
};
|
|
||||||
#endif // ENABLE_FP8_E5M2
|
|
||||||
|
|
||||||
} // namespace vllm
|
|
||||||
41
csrc/cache.h
41
csrc/cache.h
@ -1,29 +1,32 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <torch/extension.h>
|
#include <torch/all.h>
|
||||||
|
|
||||||
#include <map>
|
#include <map>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
void swap_blocks(
|
void swap_blocks(torch::Tensor& src, torch::Tensor& dst,
|
||||||
torch::Tensor& src,
|
const torch::Tensor& block_mapping);
|
||||||
torch::Tensor& dst,
|
|
||||||
const std::map<int64_t, int64_t>& block_mapping);
|
|
||||||
|
|
||||||
void copy_blocks(
|
// Note: the key_caches and value_caches vectors are constant but
|
||||||
std::vector<torch::Tensor>& key_caches,
|
// not the Tensors they contain. The vectors need to be const refs
|
||||||
std::vector<torch::Tensor>& value_caches,
|
// in order to satisfy pytorch's C++ operator registration code.
|
||||||
const std::map<int64_t, std::vector<int64_t>>& block_mapping);
|
void copy_blocks(std::vector<torch::Tensor> const& key_caches,
|
||||||
|
std::vector<torch::Tensor> const& value_caches,
|
||||||
|
const torch::Tensor& block_mapping);
|
||||||
|
|
||||||
void reshape_and_cache(
|
void reshape_and_cache(torch::Tensor& key, torch::Tensor& value,
|
||||||
torch::Tensor& key,
|
torch::Tensor& key_cache, torch::Tensor& value_cache,
|
||||||
torch::Tensor& value,
|
torch::Tensor& slot_mapping,
|
||||||
torch::Tensor& key_cache,
|
const std::string& kv_cache_dtype,
|
||||||
torch::Tensor& value_cache,
|
const double kv_scale);
|
||||||
torch::Tensor& slot_mapping,
|
|
||||||
const std::string& kv_cache_dtype);
|
void reshape_and_cache_flash(torch::Tensor& key, torch::Tensor& value,
|
||||||
|
torch::Tensor& key_cache,
|
||||||
|
torch::Tensor& value_cache,
|
||||||
|
torch::Tensor& slot_mapping,
|
||||||
|
const std::string& kv_cache_dtype);
|
||||||
|
|
||||||
// Just for unittest
|
// Just for unittest
|
||||||
void convert_fp8_e5m2(
|
void convert_fp8(torch::Tensor& dst_cache, torch::Tensor& src_cache,
|
||||||
torch::Tensor& src_cache,
|
const double scale, const std::string& kv_cache_dtype);
|
||||||
torch::Tensor& dst_cache);
|
|
||||||
|
|||||||
@ -1,11 +1,14 @@
|
|||||||
#include <torch/extension.h>
|
#include <torch/all.h>
|
||||||
#include <ATen/cuda/CUDAContext.h>
|
#include <ATen/cuda/CUDAContext.h>
|
||||||
#include <c10/cuda/CUDAGuard.h>
|
#include <c10/cuda/CUDAGuard.h>
|
||||||
|
|
||||||
#include "cuda_compat.h"
|
#include "cuda_compat.h"
|
||||||
#include "dispatch_utils.h"
|
#include "dispatch_utils.h"
|
||||||
#ifdef ENABLE_FP8_E5M2
|
|
||||||
#include "quantization/fp8_e5m2_kvcache/quant_utils.cuh"
|
#ifdef USE_ROCM
|
||||||
|
#include "quantization/fp8/amd/quant_utils.cuh"
|
||||||
|
#else
|
||||||
|
#include "quantization/fp8/nvidia/quant_utils.cuh"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
@ -15,20 +18,17 @@
|
|||||||
|
|
||||||
#ifdef USE_ROCM
|
#ifdef USE_ROCM
|
||||||
#include <hip/hip_bf16.h>
|
#include <hip/hip_bf16.h>
|
||||||
typedef __hip_bfloat16 __nv_bfloat16;
|
typedef __hip_bfloat16 __nv_bfloat16;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
void swap_blocks(
|
void swap_blocks(torch::Tensor& src, torch::Tensor& dst,
|
||||||
torch::Tensor& src,
|
const torch::Tensor& block_mapping) {
|
||||||
torch::Tensor& dst,
|
|
||||||
const std::map<int64_t, int64_t>& block_mapping) {
|
|
||||||
torch::Device src_device = src.device();
|
torch::Device src_device = src.device();
|
||||||
torch::Device dst_device = dst.device();
|
torch::Device dst_device = dst.device();
|
||||||
cudaMemcpyKind memcpy_type;
|
cudaMemcpyKind memcpy_type;
|
||||||
if (src_device.is_cuda() && dst_device.is_cuda()) {
|
if (src_device.is_cuda() && dst_device.is_cuda()) {
|
||||||
TORCH_CHECK(
|
TORCH_CHECK(src_device.index() == dst_device.index(),
|
||||||
src_device.index() == dst_device.index(),
|
"src and dst must be on the same GPU");
|
||||||
"src and dst must be on the same GPU");
|
|
||||||
memcpy_type = cudaMemcpyDeviceToDevice;
|
memcpy_type = cudaMemcpyDeviceToDevice;
|
||||||
} else if (src_device.is_cuda() && dst_device.is_cpu()) {
|
} else if (src_device.is_cuda() && dst_device.is_cpu()) {
|
||||||
memcpy_type = cudaMemcpyDeviceToHost;
|
memcpy_type = cudaMemcpyDeviceToHost;
|
||||||
@ -38,41 +38,44 @@ void swap_blocks(
|
|||||||
TORCH_CHECK(false, "Invalid device combination");
|
TORCH_CHECK(false, "Invalid device combination");
|
||||||
}
|
}
|
||||||
|
|
||||||
char *src_ptr = static_cast<char*>(src.data_ptr());
|
// NOTE(youkaichao): keep in mind that `block_mapping` should be
|
||||||
char *dst_ptr = static_cast<char*>(dst.data_ptr());
|
// a cpu tensor, otherwise every `item` call will require a gpu-cpu
|
||||||
|
// synchronization.
|
||||||
|
TORCH_CHECK(block_mapping.device().is_cpu(), "block_mapping must be on CPU");
|
||||||
|
|
||||||
|
char* src_ptr = static_cast<char*>(src.data_ptr());
|
||||||
|
char* dst_ptr = static_cast<char*>(dst.data_ptr());
|
||||||
|
|
||||||
const int64_t block_size_in_bytes = src.element_size() * src[0].numel();
|
const int64_t block_size_in_bytes = src.element_size() * src[0].numel();
|
||||||
const at::cuda::OptionalCUDAGuard device_guard(src_device.is_cuda() ? src_device : dst_device);
|
const at::cuda::OptionalCUDAGuard device_guard(
|
||||||
|
src_device.is_cuda() ? src_device : dst_device);
|
||||||
const cudaStream_t stream = at::cuda::getCurrentCUDAStream();
|
const cudaStream_t stream = at::cuda::getCurrentCUDAStream();
|
||||||
// NOTE(woosuk): This can be slow if the number of blocks is large.
|
// NOTE(woosuk): This can be slow if the number of blocks is large.
|
||||||
for (const auto& pair : block_mapping) {
|
const int64_t num_blocks = block_mapping.size(0);
|
||||||
int64_t src_block_number = pair.first;
|
for (size_t i = 0; i < num_blocks; i++) {
|
||||||
int64_t dst_block_number = pair.second;
|
int64_t src_block_number = block_mapping[i][0].item<int64_t>();
|
||||||
|
int64_t dst_block_number = block_mapping[i][1].item<int64_t>();
|
||||||
int64_t src_offset = src_block_number * block_size_in_bytes;
|
int64_t src_offset = src_block_number * block_size_in_bytes;
|
||||||
int64_t dst_offset = dst_block_number * block_size_in_bytes;
|
int64_t dst_offset = dst_block_number * block_size_in_bytes;
|
||||||
cudaMemcpyAsync(
|
cudaMemcpyAsync(dst_ptr + dst_offset, src_ptr + src_offset,
|
||||||
dst_ptr + dst_offset,
|
block_size_in_bytes, memcpy_type, stream);
|
||||||
src_ptr + src_offset,
|
|
||||||
block_size_in_bytes,
|
|
||||||
memcpy_type,
|
|
||||||
stream);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
namespace vllm {
|
namespace vllm {
|
||||||
|
|
||||||
// Grid: (num_layers, num_pairs)
|
// Grid: (num_layers, num_pairs)
|
||||||
template<typename scalar_t>
|
template <typename scalar_t>
|
||||||
__global__ void copy_blocks_kernel(
|
__global__ void copy_blocks_kernel(int64_t* key_cache_ptrs,
|
||||||
int64_t* key_cache_ptrs,
|
int64_t* value_cache_ptrs,
|
||||||
int64_t* value_cache_ptrs,
|
const int64_t* __restrict__ block_mapping,
|
||||||
const int64_t* __restrict__ block_mapping,
|
const int numel_per_block) {
|
||||||
const int numel_per_block) {
|
|
||||||
const int layer_idx = blockIdx.x;
|
const int layer_idx = blockIdx.x;
|
||||||
const int pair_idx = blockIdx.y;
|
const int pair_idx = blockIdx.y;
|
||||||
|
|
||||||
scalar_t* key_cache = reinterpret_cast<scalar_t*>(key_cache_ptrs[layer_idx]);
|
scalar_t* key_cache = reinterpret_cast<scalar_t*>(key_cache_ptrs[layer_idx]);
|
||||||
scalar_t* value_cache = reinterpret_cast<scalar_t*>(value_cache_ptrs[layer_idx]);
|
scalar_t* value_cache =
|
||||||
|
reinterpret_cast<scalar_t*>(value_cache_ptrs[layer_idx]);
|
||||||
int64_t src_block_number = block_mapping[2 * pair_idx];
|
int64_t src_block_number = block_mapping[2 * pair_idx];
|
||||||
int64_t dst_block_number = block_mapping[2 * pair_idx + 1];
|
int64_t dst_block_number = block_mapping[2 * pair_idx + 1];
|
||||||
|
|
||||||
@ -90,12 +93,14 @@ __global__ void copy_blocks_kernel(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace vllm
|
} // namespace vllm
|
||||||
|
|
||||||
void copy_blocks(
|
// Note: the key_caches and value_caches vectors are constant but
|
||||||
std::vector<torch::Tensor>& key_caches,
|
// not the Tensors they contain. The vectors need to be const refs
|
||||||
std::vector<torch::Tensor>& value_caches,
|
// in order to satisfy pytorch's C++ operator registration code.
|
||||||
const std::map<int64_t, std::vector<int64_t>>& block_mapping) {
|
void copy_blocks(std::vector<torch::Tensor> const& key_caches,
|
||||||
|
std::vector<torch::Tensor> const& value_caches,
|
||||||
|
const torch::Tensor& block_mapping) {
|
||||||
int num_layers = key_caches.size();
|
int num_layers = key_caches.size();
|
||||||
TORCH_CHECK(num_layers == value_caches.size());
|
TORCH_CHECK(num_layers == value_caches.size());
|
||||||
if (num_layers == 0) {
|
if (num_layers == 0) {
|
||||||
@ -109,29 +114,23 @@ void copy_blocks(
|
|||||||
int64_t key_cache_ptrs[num_layers];
|
int64_t key_cache_ptrs[num_layers];
|
||||||
int64_t value_cache_ptrs[num_layers];
|
int64_t value_cache_ptrs[num_layers];
|
||||||
for (int layer_idx = 0; layer_idx < num_layers; ++layer_idx) {
|
for (int layer_idx = 0; layer_idx < num_layers; ++layer_idx) {
|
||||||
key_cache_ptrs[layer_idx] = reinterpret_cast<int64_t>(key_caches[layer_idx].data_ptr());
|
key_cache_ptrs[layer_idx] =
|
||||||
value_cache_ptrs[layer_idx] = reinterpret_cast<int64_t>(value_caches[layer_idx].data_ptr());
|
reinterpret_cast<int64_t>(key_caches[layer_idx].data_ptr());
|
||||||
|
value_cache_ptrs[layer_idx] =
|
||||||
|
reinterpret_cast<int64_t>(value_caches[layer_idx].data_ptr());
|
||||||
}
|
}
|
||||||
// Create block mapping array.
|
|
||||||
std::vector<int64_t> block_mapping_vec;
|
// block_mapping is a 2D tensor with shape (num_pairs, 2).
|
||||||
for (const auto& pair : block_mapping) {
|
int num_pairs = block_mapping.size(0);
|
||||||
int64_t src_block_number = pair.first;
|
|
||||||
for (int64_t dst_block_number : pair.second) {
|
|
||||||
block_mapping_vec.push_back(src_block_number);
|
|
||||||
block_mapping_vec.push_back(dst_block_number);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
int64_t* block_mapping_array = block_mapping_vec.data();
|
|
||||||
int num_pairs = block_mapping_vec.size() / 2;
|
|
||||||
|
|
||||||
// Move the data structures to the GPU.
|
// Move the data structures to the GPU.
|
||||||
// NOTE: This synchronizes the CPU and GPU.
|
// NOTE: This synchronizes the CPU and GPU.
|
||||||
torch::Tensor key_cache_ptrs_tensor = torch::from_blob(
|
torch::Tensor key_cache_ptrs_tensor =
|
||||||
key_cache_ptrs, {num_layers}, torch::kInt64).to(cache_device);
|
torch::from_blob(key_cache_ptrs, {num_layers}, torch::kInt64)
|
||||||
torch::Tensor value_cache_ptrs_tensor = torch::from_blob(
|
.to(cache_device);
|
||||||
value_cache_ptrs, {num_layers}, torch::kInt64).to(cache_device);
|
torch::Tensor value_cache_ptrs_tensor =
|
||||||
torch::Tensor block_mapping_tensor = torch::from_blob(
|
torch::from_blob(value_cache_ptrs, {num_layers}, torch::kInt64)
|
||||||
block_mapping_array, {2 * num_pairs}, torch::kInt64).to(cache_device);
|
.to(cache_device);
|
||||||
|
|
||||||
// Launch the kernel.
|
// Launch the kernel.
|
||||||
const int numel_per_block = key_caches[0][0].numel();
|
const int numel_per_block = key_caches[0][0].numel();
|
||||||
@ -140,30 +139,28 @@ void copy_blocks(
|
|||||||
const at::cuda::OptionalCUDAGuard device_guard(cache_device);
|
const at::cuda::OptionalCUDAGuard device_guard(cache_device);
|
||||||
const cudaStream_t stream = at::cuda::getCurrentCUDAStream();
|
const cudaStream_t stream = at::cuda::getCurrentCUDAStream();
|
||||||
VLLM_DISPATCH_FLOATING_AND_BYTE_TYPES(
|
VLLM_DISPATCH_FLOATING_AND_BYTE_TYPES(
|
||||||
key_caches[0].scalar_type(), "copy_blocks_kernel", ([&] {
|
key_caches[0].scalar_type(), "copy_blocks_kernel", ([&] {
|
||||||
vllm::copy_blocks_kernel<scalar_t><<<grid, block, 0, stream>>>(
|
vllm::copy_blocks_kernel<scalar_t><<<grid, block, 0, stream>>>(
|
||||||
key_cache_ptrs_tensor.data_ptr<int64_t>(),
|
key_cache_ptrs_tensor.data_ptr<int64_t>(),
|
||||||
value_cache_ptrs_tensor.data_ptr<int64_t>(),
|
value_cache_ptrs_tensor.data_ptr<int64_t>(),
|
||||||
block_mapping_tensor.data_ptr<int64_t>(),
|
block_mapping.data_ptr<int64_t>(), numel_per_block);
|
||||||
numel_per_block);
|
}));
|
||||||
}));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
namespace vllm {
|
namespace vllm {
|
||||||
|
|
||||||
template<typename scalar_t, typename cache_t, bool is_fp8_e5m2_kv_cache>
|
template <typename scalar_t, typename cache_t, Fp8KVCacheDataType kv_dt>
|
||||||
__global__ void reshape_and_cache_kernel(
|
__global__ void reshape_and_cache_kernel(
|
||||||
const scalar_t* __restrict__ key, // [num_tokens, num_heads, head_size]
|
const scalar_t* __restrict__ key, // [num_tokens, num_heads, head_size]
|
||||||
const scalar_t* __restrict__ value, // [num_tokens, num_heads, head_size]
|
const scalar_t* __restrict__ value, // [num_tokens, num_heads, head_size]
|
||||||
cache_t* __restrict__ key_cache, // [num_blocks, num_heads, head_size/x, block_size, x]
|
cache_t* __restrict__ key_cache, // [num_blocks, num_heads, head_size/x,
|
||||||
cache_t* __restrict__ value_cache, // [num_blocks, num_heads, head_size, block_size]
|
// block_size, x]
|
||||||
const int64_t* __restrict__ slot_mapping, // [num_tokens]
|
cache_t* __restrict__ value_cache, // [num_blocks, num_heads, head_size,
|
||||||
const int key_stride,
|
// block_size]
|
||||||
const int value_stride,
|
const int64_t* __restrict__ slot_mapping, // [num_tokens]
|
||||||
const int num_heads,
|
const int key_stride, const int value_stride, const int num_heads,
|
||||||
const int head_size,
|
const int head_size, const int block_size, const int x,
|
||||||
const int block_size,
|
const float kv_scale) {
|
||||||
const int x) {
|
|
||||||
const int64_t token_idx = blockIdx.x;
|
const int64_t token_idx = blockIdx.x;
|
||||||
const int64_t slot_idx = slot_mapping[token_idx];
|
const int64_t slot_idx = slot_mapping[token_idx];
|
||||||
if (slot_idx < 0) {
|
if (slot_idx < 0) {
|
||||||
@ -184,55 +181,84 @@ __global__ void reshape_and_cache_kernel(
|
|||||||
const int x_idx = head_offset / x;
|
const int x_idx = head_offset / x;
|
||||||
const int x_offset = head_offset % x;
|
const int x_offset = head_offset % x;
|
||||||
|
|
||||||
const int64_t tgt_key_idx = block_idx * num_heads * (head_size / x) * block_size * x
|
const int64_t tgt_key_idx =
|
||||||
+ head_idx * (head_size / x) * block_size * x
|
block_idx * num_heads * (head_size / x) * block_size * x +
|
||||||
+ x_idx * block_size * x
|
head_idx * (head_size / x) * block_size * x + x_idx * block_size * x +
|
||||||
+ block_offset * x
|
block_offset * x + x_offset;
|
||||||
+ x_offset;
|
const int64_t tgt_value_idx =
|
||||||
const int64_t tgt_value_idx = block_idx * num_heads * head_size * block_size
|
block_idx * num_heads * head_size * block_size +
|
||||||
+ head_idx * head_size * block_size
|
head_idx * head_size * block_size + head_offset * block_size +
|
||||||
+ head_offset * block_size
|
block_offset;
|
||||||
+ block_offset;
|
|
||||||
scalar_t tgt_key = key[src_key_idx];
|
scalar_t tgt_key = key[src_key_idx];
|
||||||
scalar_t tgt_value = value[src_value_idx];
|
scalar_t tgt_value = value[src_value_idx];
|
||||||
if constexpr (is_fp8_e5m2_kv_cache) {
|
if constexpr (kv_dt == Fp8KVCacheDataType::kAuto) {
|
||||||
#ifdef ENABLE_FP8_E5M2
|
|
||||||
key_cache[tgt_key_idx] = fp8_e5m2_unscaled::vec_conversion<uint8_t, scalar_t>(tgt_key);
|
|
||||||
value_cache[tgt_value_idx] = fp8_e5m2_unscaled::vec_conversion<uint8_t, scalar_t>(tgt_value);
|
|
||||||
#else
|
|
||||||
assert(false);
|
|
||||||
#endif
|
|
||||||
} else {
|
|
||||||
key_cache[tgt_key_idx] = tgt_key;
|
key_cache[tgt_key_idx] = tgt_key;
|
||||||
value_cache[tgt_value_idx] = tgt_value;
|
value_cache[tgt_value_idx] = tgt_value;
|
||||||
|
} else {
|
||||||
|
key_cache[tgt_key_idx] =
|
||||||
|
fp8::scaled_convert<cache_t, scalar_t, kv_dt>(tgt_key, kv_scale);
|
||||||
|
value_cache[tgt_value_idx] =
|
||||||
|
fp8::scaled_convert<cache_t, scalar_t, kv_dt>(tgt_value, kv_scale);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace vllm
|
template <typename scalar_t>
|
||||||
|
__global__ void reshape_and_cache_flash_kernel(
|
||||||
|
const scalar_t* __restrict__ key, // [num_tokens, num_heads, head_size]
|
||||||
|
const scalar_t* __restrict__ value, // [num_tokens, num_heads, head_size]
|
||||||
|
scalar_t* __restrict__ k_cache, // [num_blocks, block_size, num_heads,
|
||||||
|
// head_size]
|
||||||
|
scalar_t* __restrict__ v_cache, // [num_blocks, block_size, num_heads,
|
||||||
|
// head_size]
|
||||||
|
const int64_t* __restrict__ slot_mapping, // [num_tokens]
|
||||||
|
const int block_stride, const int key_stride, const int value_stride,
|
||||||
|
const int num_heads, const int head_size, const int block_size) {
|
||||||
|
const int64_t token_idx = blockIdx.x;
|
||||||
|
const int64_t slot_idx = slot_mapping[token_idx];
|
||||||
|
// NOTE: slot_idx can be -1 if the token is padded
|
||||||
|
if (slot_idx < 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const int64_t block_idx = slot_idx / block_size;
|
||||||
|
const int64_t block_offset = slot_idx % block_size;
|
||||||
|
const int n = num_heads * head_size;
|
||||||
|
for (int i = threadIdx.x; i < n; i += blockDim.x) {
|
||||||
|
const int64_t src_key_idx = token_idx * key_stride + i;
|
||||||
|
const int64_t src_value_idx = token_idx * value_stride + i;
|
||||||
|
const int head_idx = i / head_size;
|
||||||
|
const int head_offset = i % head_size;
|
||||||
|
const int64_t tgt_value_idx = block_idx * block_stride +
|
||||||
|
block_offset * num_heads * head_size +
|
||||||
|
head_idx * head_size + head_offset;
|
||||||
|
k_cache[tgt_value_idx] = key[src_key_idx];
|
||||||
|
v_cache[tgt_value_idx] = value[src_value_idx];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} // namespace vllm
|
||||||
|
|
||||||
#define CALL_RESHAPE_AND_CACHE(KV_T, CACHE_T, IS_FP8_E5M2_KV_CACHE) \
|
// KV_T is the stored data type of kv-cache.
|
||||||
vllm::reshape_and_cache_kernel<KV_T, CACHE_T, IS_FP8_E5M2_KV_CACHE><<<grid, block, 0, stream>>>( \
|
// CACHE_T is the data type of key and value tensors.
|
||||||
reinterpret_cast<KV_T*>(key.data_ptr()), \
|
// KV_DTYPE is the real data type of kv-cache.
|
||||||
reinterpret_cast<KV_T*>(value.data_ptr()), \
|
#define CALL_RESHAPE_AND_CACHE(KV_T, CACHE_T, KV_DTYPE) \
|
||||||
reinterpret_cast<CACHE_T*>(key_cache.data_ptr()), \
|
vllm::reshape_and_cache_kernel<KV_T, CACHE_T, KV_DTYPE> \
|
||||||
reinterpret_cast<CACHE_T*>(value_cache.data_ptr()), \
|
<<<grid, block, 0, stream>>>( \
|
||||||
slot_mapping.data_ptr<int64_t>(), \
|
reinterpret_cast<KV_T*>(key.data_ptr()), \
|
||||||
key_stride, \
|
reinterpret_cast<KV_T*>(value.data_ptr()), \
|
||||||
value_stride, \
|
reinterpret_cast<CACHE_T*>(key_cache.data_ptr()), \
|
||||||
num_heads, \
|
reinterpret_cast<CACHE_T*>(value_cache.data_ptr()), \
|
||||||
head_size, \
|
slot_mapping.data_ptr<int64_t>(), key_stride, value_stride, \
|
||||||
block_size, \
|
num_heads, head_size, block_size, x, kv_scale);
|
||||||
x);
|
|
||||||
|
|
||||||
void reshape_and_cache(
|
void reshape_and_cache(
|
||||||
torch::Tensor& key, // [num_tokens, num_heads, head_size]
|
torch::Tensor& key, // [num_tokens, num_heads, head_size]
|
||||||
torch::Tensor& value, // [num_tokens, num_heads, head_size]
|
torch::Tensor& value, // [num_tokens, num_heads, head_size]
|
||||||
torch::Tensor& key_cache, // [num_blocks, num_heads, head_size/x, block_size, x]
|
torch::Tensor&
|
||||||
torch::Tensor& value_cache, // [num_blocks, num_heads, head_size, block_size]
|
key_cache, // [num_blocks, num_heads, head_size/x, block_size, x]
|
||||||
torch::Tensor& slot_mapping, // [num_tokens]
|
torch::Tensor&
|
||||||
const std::string& kv_cache_dtype)
|
value_cache, // [num_blocks, num_heads, head_size, block_size]
|
||||||
{
|
torch::Tensor& slot_mapping, // [num_tokens]
|
||||||
|
const std::string& kv_cache_dtype, const double kv_scale) {
|
||||||
int num_tokens = key.size(0);
|
int num_tokens = key.size(0);
|
||||||
int num_heads = key.size(1);
|
int num_heads = key.size(1);
|
||||||
int head_size = key.size(2);
|
int head_size = key.size(2);
|
||||||
@ -246,57 +272,80 @@ void reshape_and_cache(
|
|||||||
dim3 block(std::min(num_heads * head_size, 512));
|
dim3 block(std::min(num_heads * head_size, 512));
|
||||||
const at::cuda::OptionalCUDAGuard device_guard(device_of(key));
|
const at::cuda::OptionalCUDAGuard device_guard(device_of(key));
|
||||||
const cudaStream_t stream = at::cuda::getCurrentCUDAStream();
|
const cudaStream_t stream = at::cuda::getCurrentCUDAStream();
|
||||||
if (kv_cache_dtype == "auto") {
|
|
||||||
if (key.dtype() == at::ScalarType::Float) {
|
DISPATCH_BY_KV_CACHE_DTYPE(key.dtype(), kv_cache_dtype,
|
||||||
CALL_RESHAPE_AND_CACHE(float, float, false);
|
CALL_RESHAPE_AND_CACHE)
|
||||||
} else if (key.dtype() == at::ScalarType::Half) {
|
}
|
||||||
CALL_RESHAPE_AND_CACHE(uint16_t, uint16_t, false);
|
|
||||||
} else if (key.dtype() == at::ScalarType::BFloat16) {
|
void reshape_and_cache_flash(
|
||||||
CALL_RESHAPE_AND_CACHE(__nv_bfloat16, __nv_bfloat16, false);
|
torch::Tensor& key, // [num_tokens, num_heads, head_size]
|
||||||
}
|
torch::Tensor& value, // [num_tokens, num_heads, head_size]
|
||||||
} else if (kv_cache_dtype == "fp8_e5m2") {
|
torch::Tensor& k_cache, // [num_blocks, block_size, num_heads, head_size]
|
||||||
if (key.dtype() == at::ScalarType::Float) {
|
torch::Tensor& v_cache, // [num_blocks, block_size, num_heads, head_size]
|
||||||
CALL_RESHAPE_AND_CACHE(float, uint8_t, true);
|
torch::Tensor& slot_mapping, // [num_tokens]
|
||||||
} else if (key.dtype() == at::ScalarType::Half) {
|
const std::string& kv_cache_dtype) {
|
||||||
CALL_RESHAPE_AND_CACHE(uint16_t, uint8_t, true);
|
// FIXME: only support auto datatype, does not support fp8
|
||||||
} else if (key.dtype() == at::ScalarType::BFloat16) {
|
if (kv_cache_dtype != "auto") {
|
||||||
CALL_RESHAPE_AND_CACHE(__nv_bfloat16, uint8_t, true);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
TORCH_CHECK(false, "Unsupported data type of kv cache: ", kv_cache_dtype);
|
TORCH_CHECK(false, "Unsupported data type of kv cache: ", kv_cache_dtype);
|
||||||
}
|
}
|
||||||
|
int num_tokens = key.size(0);
|
||||||
|
int num_heads = key.size(1);
|
||||||
|
int head_size = key.size(2);
|
||||||
|
int block_size = k_cache.size(1);
|
||||||
|
|
||||||
|
int key_stride = key.stride(0);
|
||||||
|
int value_stride = value.stride(0);
|
||||||
|
int block_stride = k_cache.stride(0);
|
||||||
|
TORCH_CHECK(k_cache.stride(0) == v_cache.stride(0));
|
||||||
|
|
||||||
|
dim3 grid(num_tokens);
|
||||||
|
dim3 block(std::min(num_heads * head_size, 512));
|
||||||
|
const at::cuda::OptionalCUDAGuard device_guard(device_of(key));
|
||||||
|
const cudaStream_t stream = at::cuda::getCurrentCUDAStream();
|
||||||
|
VLLM_DISPATCH_FLOATING_TYPES(
|
||||||
|
key.scalar_type(), "reshape_and_cache_flash", [&] {
|
||||||
|
vllm::reshape_and_cache_flash_kernel<scalar_t>
|
||||||
|
<<<grid, block, 0, stream>>>(
|
||||||
|
key.data_ptr<scalar_t>(), value.data_ptr<scalar_t>(),
|
||||||
|
k_cache.data_ptr<scalar_t>(), v_cache.data_ptr<scalar_t>(),
|
||||||
|
slot_mapping.data_ptr<int64_t>(), block_stride, key_stride,
|
||||||
|
value_stride, num_heads, head_size, block_size);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
namespace vllm {
|
namespace vllm {
|
||||||
|
|
||||||
template<typename Tout, typename Tin>
|
template <typename Tout, typename Tin, Fp8KVCacheDataType kv_dt>
|
||||||
__global__ void convert_fp8_e5m2_kernel(
|
__global__ void convert_fp8_kernel(const Tin* __restrict__ src_cache,
|
||||||
const Tin* __restrict__ src_cache,
|
Tout* __restrict__ dst_cache,
|
||||||
Tout* __restrict__ dst_cache,
|
const float kv_scale,
|
||||||
const int64_t block_stride) {
|
const int64_t block_stride) {
|
||||||
const int64_t block_idx = blockIdx.x;
|
const int64_t block_idx = blockIdx.x;
|
||||||
for (int i = threadIdx.x; i < block_stride; i += blockDim.x) {
|
for (int i = threadIdx.x; i < block_stride; i += blockDim.x) {
|
||||||
int64_t idx = block_idx * block_stride + i;
|
int64_t idx = block_idx * block_stride + i;
|
||||||
#ifdef ENABLE_FP8_E5M2
|
dst_cache[idx] =
|
||||||
dst_cache[idx] = fp8_e5m2_unscaled::vec_conversion<Tout, Tin>(src_cache[idx]);
|
fp8::scaled_convert<Tout, Tin, kv_dt>(src_cache[idx], kv_scale);
|
||||||
#else
|
|
||||||
assert(false);
|
|
||||||
#endif
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace vllm
|
} // namespace vllm
|
||||||
|
|
||||||
#define CALL_CONVERT_FP8_E5M2(Tout, Tin) \
|
#define CALL_CONVERT_FP8(Tout, Tin, KV_DTYPE) \
|
||||||
vllm::convert_fp8_e5m2_kernel<Tout, Tin><<<grid, block, 0, stream>>>( \
|
vllm::convert_fp8_kernel<Tout, Tin, KV_DTYPE><<<grid, block, 0, stream>>>( \
|
||||||
reinterpret_cast<Tin*>(src_cache.data_ptr()), \
|
reinterpret_cast<Tin*>(src_cache.data_ptr()), \
|
||||||
reinterpret_cast<Tout*>(dst_cache.data_ptr()), \
|
reinterpret_cast<Tout*>(dst_cache.data_ptr()), kv_scale, block_stride);
|
||||||
block_stride);
|
|
||||||
|
// Only for testing.
|
||||||
|
void convert_fp8(torch::Tensor& dst_cache, torch::Tensor& src_cache,
|
||||||
|
const double kv_scale, const std::string& kv_cache_dtype) {
|
||||||
|
torch::Device src_device = src_cache.device();
|
||||||
|
torch::Device dst_device = dst_cache.device();
|
||||||
|
TORCH_CHECK(src_device.is_cuda(), "src must be on a GPU")
|
||||||
|
TORCH_CHECK(dst_device.is_cuda(), "dst must be on a GPU")
|
||||||
|
TORCH_CHECK(src_device.index() == dst_device.index(),
|
||||||
|
"src and dst must be on the same GPU");
|
||||||
|
at::cuda::OptionalCUDAGuard device_guard(src_device);
|
||||||
|
|
||||||
void convert_fp8_e5m2(
|
|
||||||
torch::Tensor& src_cache,
|
|
||||||
torch::Tensor& dst_cache)
|
|
||||||
{
|
|
||||||
int64_t num_blocks = src_cache.size(0);
|
int64_t num_blocks = src_cache.size(0);
|
||||||
int64_t block_stride = src_cache.stride(0);
|
int64_t block_stride = src_cache.stride(0);
|
||||||
|
|
||||||
@ -304,17 +353,37 @@ void convert_fp8_e5m2(
|
|||||||
dim3 block(std::min(block_stride, int64_t(512)));
|
dim3 block(std::min(block_stride, int64_t(512)));
|
||||||
const cudaStream_t stream = at::cuda::getCurrentCUDAStream();
|
const cudaStream_t stream = at::cuda::getCurrentCUDAStream();
|
||||||
|
|
||||||
if (src_cache.dtype() == at::ScalarType::Float) {
|
if (kv_cache_dtype == "auto") {
|
||||||
CALL_CONVERT_FP8_E5M2(uint8_t, float);
|
if (src_cache.dtype() == at::ScalarType::Float) {
|
||||||
} else if (src_cache.dtype() == at::ScalarType::Half) {
|
CALL_CONVERT_FP8(uint8_t, float, vllm::Fp8KVCacheDataType::kAuto);
|
||||||
CALL_CONVERT_FP8_E5M2(uint8_t, uint16_t);
|
} else if (src_cache.dtype() == at::ScalarType::Half) {
|
||||||
} else if (src_cache.dtype() == at::ScalarType::BFloat16) {
|
CALL_CONVERT_FP8(uint8_t, uint16_t, vllm::Fp8KVCacheDataType::kAuto);
|
||||||
CALL_CONVERT_FP8_E5M2(uint8_t, __nv_bfloat16);
|
} else if (src_cache.dtype() == at::ScalarType::BFloat16) {
|
||||||
} else if (dst_cache.dtype() == at::ScalarType::Float) {
|
CALL_CONVERT_FP8(uint8_t, __nv_bfloat16, vllm::Fp8KVCacheDataType::kAuto);
|
||||||
CALL_CONVERT_FP8_E5M2(float, uint8_t);
|
} else if (dst_cache.dtype() == at::ScalarType::Float) {
|
||||||
} else if (dst_cache.dtype() == at::ScalarType::Half) {
|
CALL_CONVERT_FP8(float, uint8_t, vllm::Fp8KVCacheDataType::kAuto);
|
||||||
CALL_CONVERT_FP8_E5M2(uint16_t, uint8_t);
|
} else if (dst_cache.dtype() == at::ScalarType::Half) {
|
||||||
} else if (dst_cache.dtype() == at::ScalarType::BFloat16) {
|
CALL_CONVERT_FP8(uint16_t, uint8_t, vllm::Fp8KVCacheDataType::kAuto);
|
||||||
CALL_CONVERT_FP8_E5M2(__nv_bfloat16, uint8_t);
|
} else if (dst_cache.dtype() == at::ScalarType::BFloat16) {
|
||||||
|
CALL_CONVERT_FP8(__nv_bfloat16, uint8_t, vllm::Fp8KVCacheDataType::kAuto);
|
||||||
|
}
|
||||||
|
} else if (kv_cache_dtype == "fp8" || kv_cache_dtype == "fp8_e4m3") {
|
||||||
|
if (src_cache.dtype() == at::ScalarType::Float) {
|
||||||
|
CALL_CONVERT_FP8(uint8_t, float, vllm::Fp8KVCacheDataType::kFp8E4M3);
|
||||||
|
} else if (src_cache.dtype() == at::ScalarType::Half) {
|
||||||
|
CALL_CONVERT_FP8(uint8_t, uint16_t, vllm::Fp8KVCacheDataType::kFp8E4M3);
|
||||||
|
} else if (src_cache.dtype() == at::ScalarType::BFloat16) {
|
||||||
|
CALL_CONVERT_FP8(uint8_t, __nv_bfloat16,
|
||||||
|
vllm::Fp8KVCacheDataType::kFp8E4M3);
|
||||||
|
} else if (dst_cache.dtype() == at::ScalarType::Float) {
|
||||||
|
CALL_CONVERT_FP8(float, uint8_t, vllm::Fp8KVCacheDataType::kFp8E4M3);
|
||||||
|
} else if (dst_cache.dtype() == at::ScalarType::Half) {
|
||||||
|
CALL_CONVERT_FP8(uint16_t, uint8_t, vllm::Fp8KVCacheDataType::kFp8E4M3);
|
||||||
|
} else if (dst_cache.dtype() == at::ScalarType::BFloat16) {
|
||||||
|
CALL_CONVERT_FP8(__nv_bfloat16, uint8_t,
|
||||||
|
vllm::Fp8KVCacheDataType::kFp8E4M3);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
TORCH_CHECK(false, "Unsupported data type: ", kv_cache_dtype);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user