diff --git a/.gitattributes b/.gitattributes index 921a127d322331de145fadbea3735690db5bdd6d..da8c7f0523bfa3b8a105e8ea9966d68c08cc8ead 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1830,3 +1830,6 @@ vllm/lib/python3.10/site-packages/cupy/_core/_routines_sorting.cpython-310-x86_6 vllm/lib/python3.10/site-packages/torch/testing/_internal/__pycache__/common_quantization.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text vllm/lib/python3.10/site-packages/torch/onnx/__pycache__/symbolic_opset9.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text vllm/lib/python3.10/site-packages/torch/testing/_internal/__pycache__/common_methods_invocations.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +parrot/lib/python3.10/site-packages/scipy/misc/ecg.dat filter=lfs diff=lfs merge=lfs -text +parrot/lib/python3.10/site-packages/scipy/sparse/linalg/_propack/_cpropack.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +parrot/lib/python3.10/site-packages/scipy/integrate/_dop.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Asmara b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Asmara new file mode 100644 index 0000000000000000000000000000000000000000..9dcfc19c56e62b12b730f4335b34479695f273f5 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Asmara differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Blantyre b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Blantyre new file mode 100644 index 0000000000000000000000000000000000000000..65f043f1d1833d26b5fe42a460f84b35d1dcba63 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Blantyre differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Bujumbura b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Bujumbura new file mode 100644 index 0000000000000000000000000000000000000000..65f043f1d1833d26b5fe42a460f84b35d1dcba63 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Bujumbura differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Gaborone b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Gaborone new file mode 100644 index 0000000000000000000000000000000000000000..65f043f1d1833d26b5fe42a460f84b35d1dcba63 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Gaborone differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Kampala b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Kampala new file mode 100644 index 0000000000000000000000000000000000000000..9dcfc19c56e62b12b730f4335b34479695f273f5 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Kampala differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Khartoum b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Khartoum new file mode 100644 index 0000000000000000000000000000000000000000..8ee8cb92e72d9c507ad0ee06dc6a38406ab06f34 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Khartoum differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Lubumbashi b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Lubumbashi new file mode 100644 index 0000000000000000000000000000000000000000..65f043f1d1833d26b5fe42a460f84b35d1dcba63 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Lubumbashi differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Maputo b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Maputo new file mode 100644 index 0000000000000000000000000000000000000000..65f043f1d1833d26b5fe42a460f84b35d1dcba63 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Maputo differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Mogadishu b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Mogadishu new file mode 100644 index 0000000000000000000000000000000000000000..9dcfc19c56e62b12b730f4335b34479695f273f5 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Mogadishu differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Nairobi b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Nairobi new file mode 100644 index 0000000000000000000000000000000000000000..9dcfc19c56e62b12b730f4335b34479695f273f5 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Africa/Nairobi differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Indianapolis b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Indianapolis new file mode 100644 index 0000000000000000000000000000000000000000..a84b6e99671f7305d1c459956e16a4dd772fc60e Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Indianapolis differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Marengo b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Marengo new file mode 100644 index 0000000000000000000000000000000000000000..677bbff6a9d89180cfd2dd3279a1c412610b6540 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Marengo differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Petersburg b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Petersburg new file mode 100644 index 0000000000000000000000000000000000000000..3082de00c2e0bfe89d4ac5e093d9e5921aa63610 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Petersburg differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Vevay b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Vevay new file mode 100644 index 0000000000000000000000000000000000000000..315b4c45aef1f241d025900544133c085fe4f69d Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Vevay differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Winamac b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Winamac new file mode 100644 index 0000000000000000000000000000000000000000..6d4e19377e9f70c3782daa223753c640c60ab1eb Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Winamac differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Apia b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Apia new file mode 100644 index 0000000000000000000000000000000000000000..e592a68e53f6215de9e1d1ac61ce062a333283c0 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Apia differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Chatham b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Chatham new file mode 100644 index 0000000000000000000000000000000000000000..bde46cf7e4b7909714b93cee39a5d953387d756c Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Chatham differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Fiji b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Fiji new file mode 100644 index 0000000000000000000000000000000000000000..acf8091ac85151a6c887e2b5049ee40754b7b0d3 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Fiji differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Funafuti b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Funafuti new file mode 100644 index 0000000000000000000000000000000000000000..47661d40a4188eb39e8d52e5af8ab23ef7f23766 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Funafuti differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Galapagos b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Galapagos new file mode 100644 index 0000000000000000000000000000000000000000..40051ddf63a32d79e5233b916e3911d6dc3ef759 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Galapagos differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Gambier b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Gambier new file mode 100644 index 0000000000000000000000000000000000000000..84acaf41520d2d302f75e300e2b47c5527218df4 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Gambier differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Guadalcanal b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Guadalcanal new file mode 100644 index 0000000000000000000000000000000000000000..1ab8353464ddb93947f871f07cfd12540373269c Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Guadalcanal differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Kanton b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Kanton new file mode 100644 index 0000000000000000000000000000000000000000..b1c4b0734483033722c28c8b2884ac9dddd2ab45 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Kanton differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Kosrae b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Kosrae new file mode 100644 index 0000000000000000000000000000000000000000..0666fb0dd161cb732b29f84d49c49cc985a3559a Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Kosrae differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Kwajalein b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Kwajalein new file mode 100644 index 0000000000000000000000000000000000000000..1887a607422edd499fdf24afe91a04294f1caf6f Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Kwajalein differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Majuro b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Majuro new file mode 100644 index 0000000000000000000000000000000000000000..47661d40a4188eb39e8d52e5af8ab23ef7f23766 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Majuro differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Marquesas b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Marquesas new file mode 100644 index 0000000000000000000000000000000000000000..f546c03f96b24859521aab5b9997bfc5dd124ead Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Marquesas differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Midway b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Midway new file mode 100644 index 0000000000000000000000000000000000000000..cb56709a77dedb471150f4907771bf38f1879ba4 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Midway differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Noumea b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Noumea new file mode 100644 index 0000000000000000000000000000000000000000..959cc8cd26f8a7b10a70e0f93bf3b3c9bbc680d2 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Noumea differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Pitcairn b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Pitcairn new file mode 100644 index 0000000000000000000000000000000000000000..5ee90e70203d72484b8752475c86139671bcb102 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Pitcairn differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Ponape b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Ponape new file mode 100644 index 0000000000000000000000000000000000000000..1ab8353464ddb93947f871f07cfd12540373269c Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Ponape differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Port_Moresby b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Port_Moresby new file mode 100644 index 0000000000000000000000000000000000000000..7be2474dd91c8a7da181fcda09d838254b890d75 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Port_Moresby differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Rarotonga b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Rarotonga new file mode 100644 index 0000000000000000000000000000000000000000..184a87c112b99536acbafa1ec7aba52c7a94b549 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Rarotonga differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Saipan b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Saipan new file mode 100644 index 0000000000000000000000000000000000000000..66490d25dff9bcc8f710b0141f1a02e64aeb32f3 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Saipan differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Wake b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Wake new file mode 100644 index 0000000000000000000000000000000000000000..47661d40a4188eb39e8d52e5af8ab23ef7f23766 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Wake differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Wallis b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Wallis new file mode 100644 index 0000000000000000000000000000000000000000..47661d40a4188eb39e8d52e5af8ab23ef7f23766 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Wallis differ diff --git a/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Yap b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Yap new file mode 100644 index 0000000000000000000000000000000000000000..7be2474dd91c8a7da181fcda09d838254b890d75 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pytz/zoneinfo/Pacific/Yap differ diff --git a/parrot/lib/python3.10/site-packages/scipy/integrate/_dop.cpython-310-x86_64-linux-gnu.so b/parrot/lib/python3.10/site-packages/scipy/integrate/_dop.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9d04ddbcddc727fb2757a2fc2678a9309c905e3d --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/integrate/_dop.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d401e835c7ad193d5ad481235e6c064a6b8fa337fc3704fac817c29c7dae7ae3 +size 116977 diff --git a/parrot/lib/python3.10/site-packages/scipy/misc/ecg.dat b/parrot/lib/python3.10/site-packages/scipy/misc/ecg.dat new file mode 100644 index 0000000000000000000000000000000000000000..59ee7d073be1a477ad1aacad59317c28cce94263 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/misc/ecg.dat @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f20ad3365fb9b7f845d0e5c48b6fe67081377ee466c3a220b7f69f35c8958baf +size 119035 diff --git a/parrot/lib/python3.10/site-packages/scipy/sparse/linalg/_propack/_cpropack.cpython-310-x86_64-linux-gnu.so b/parrot/lib/python3.10/site-packages/scipy/sparse/linalg/_propack/_cpropack.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..d7067b55583987c7626ea38987110613fc63d5b7 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/sparse/linalg/_propack/_cpropack.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5df2126116b6255066b2094cb032da257306dffd3eae00bd24369c80187a80c1 +size 566033 diff --git a/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/__pycache__/audio_fadein.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/__pycache__/audio_fadein.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10ca4636ea41aa3e0108e13c977208c0616f9ac9 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/__pycache__/audio_fadein.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/__pycache__/audio_left_right.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/__pycache__/audio_left_right.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a5b58daaf2c906dc5b897f8a76a64dca006cbf5 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/__pycache__/audio_left_right.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/__pycache__/audio_loop.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/__pycache__/audio_loop.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ee1f215ca29dfbbda02ab00db1bb0adda39bdd5 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/__pycache__/audio_loop.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/__pycache__/audio_normalize.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/__pycache__/audio_normalize.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..927e7ab60bdbfa40a34f8389396598a03e8fd5f1 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/__pycache__/audio_normalize.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/__pycache__/volumex.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/__pycache__/volumex.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9fca31d0e8b1239cd680b98e1fcc6544036bddc Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/__pycache__/volumex.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/all/__init__.py b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/all/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..11258d7f0fbab489c4d49659a28eaa95d75a0286 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/all/__init__.py @@ -0,0 +1,16 @@ +""" +Loads all the fx ! +Usage: +import moviepy.audio.fx.all as afx +audio_clip = afx.volume_x(some_clip, .5) +""" + +import pkgutil + +import moviepy.audio.fx as fx + +__all__ = [name for _, name, _ in pkgutil.iter_modules( + fx.__path__) if name != "all"] + +for name in __all__: + exec("from ..%s import %s" % (name, name)) diff --git a/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/all/__pycache__/__init__.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/all/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6549007434fe9887454e85d3f0c15cecf602fb8b Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/all/__pycache__/__init__.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/audio_fadein.py b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/audio_fadein.py new file mode 100644 index 0000000000000000000000000000000000000000..20b1eed00796030f5d60261e7033afc6abc68451 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/audio_fadein.py @@ -0,0 +1,21 @@ +import numpy as np + +from moviepy.decorators import audio_video_fx + + +@audio_video_fx +def audio_fadein(clip, duration): + """ Return an audio (or video) clip that is first mute, then the + sound arrives progressively over ``duration`` seconds. """ + + def fading(gf,t): + gft = gf(t) + + if np.isscalar(t): + factor = min(1.0 * t / duration, 1) + factor = np.array([factor,factor]) + else: + factor = np.minimum(1.0 * t / duration, 1) + factor = np.vstack([factor,factor]).T + return factor * gft + return clip.fl(fading, keep_duration = True) diff --git a/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/audio_normalize.py b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/audio_normalize.py new file mode 100644 index 0000000000000000000000000000000000000000..0c4daff782cb137610b81d73cf3d8645ffbe741f --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/audio_normalize.py @@ -0,0 +1,23 @@ +from moviepy.decorators import audio_video_fx + +from .volumex import volumex + + +@audio_video_fx +def audio_normalize(clip): + """ Return a clip whose volume is normalized to 0db. + + Return an audio (or video) clip whose audio volume is normalized + so that the maximum volume is at 0db, the maximum achievable volume. + + Examples + ======== + + >>> from moviepy.editor import * + >>> videoclip = VideoFileClip('myvideo.mp4').fx(afx.audio_normalize) + + """ + + + mv = clip.max_volume() + return volumex(clip, 1 / mv) diff --git a/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/volumex.py b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/volumex.py new file mode 100644 index 0000000000000000000000000000000000000000..6ec84ad5c03e5237507aaea54784e4e314435674 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/moviepy/audio/fx/volumex.py @@ -0,0 +1,20 @@ +from moviepy.decorators import audio_video_fx + + +@audio_video_fx +def volumex(clip, factor): + """ Returns a clip with audio volume multiplied by the + value `factor`. Can be applied to both audio and video clips. + + This effect is loaded as a clip method when you use moviepy.editor, + so you can just write ``clip.volumex(2)`` + + Examples + --------- + + >>> newclip = volumex(clip, 2.0) # doubles audio volume + >>> newclip = clip.fx( volumex, 0.5) # half audio, use with fx + >>> newclip = clip.volumex(2) # only if you used "moviepy.editor" + """ + return clip.fl(lambda gf, t: factor * gf(t), + keep_duration=True) diff --git a/videollama2/lib/python3.10/site-packages/torchao/dtypes/affine_quantized_tensor.py b/videollama2/lib/python3.10/site-packages/torchao/dtypes/affine_quantized_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..83c7d22fb4c563793d35b820fa75555e503be25e --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torchao/dtypes/affine_quantized_tensor.py @@ -0,0 +1,762 @@ +import torch +from typing import Dict, Callable, Any, Tuple, Optional +from collections import defaultdict +import functools +from torchao.quantization.quant_primitives import ( + choose_qparams_affine, + quantize_affine, + dequantize_affine, + ZeroPointDomain, + MappingType, + int_scaled_matmul, +) +from torchao.quantization.utils import ( + pack_tinygemm_scales_and_zeros, +) +from torch.utils._python_dispatch import return_and_correct_aliasing +from torchao.utils import find_multiple +from torchao.dtypes.utils import ( + _implements, + _ATEN_OP_OR_TORCH_FN_TABLE, + _register_layout_cls, + _get_layout_tensor_constructor, +) + +aten = torch.ops.aten + +def _aqt_is_int8(aqt): + """Check if an AffineQuantizedTensor is int8 quantized Tensor""" + return ( + aqt.layout_tensor.dtype == torch.int8 and + aqt.quant_min is None or aqt.quant_min == -128 and + aqt.quant_max is None or aqt.quant_max == 127 + ) + +def _aqt_is_int8_reduced_range(aqt): + return ( + aqt.layout_tensor.dtype == torch.int8 and + aqt.quant_min == -127 and + aqt.quant_max is None or aqt.quant_max == 127 + ) + +def _aqt_is_uint4(aqt): + """Check if an AffineQuantizedTensor is uint4 quantized Tensor""" + # TODO: use torch.uint4 + return ( + aqt.layout_tensor.dtype == torch.int32 and + aqt.quant_min is None or aqt.quant_min == 0 and + aqt.quant_max is None or aqt.quant_max == 15 + ) + +class AQTLayout(torch.Tensor): + """ + Base class for the layout tensor for `AffineQuantizedTensor` + """ + # this should be set for each layout class during registration + extended_layout: Optional[str] = None + + def get_plain() -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + pass + + @classmethod + def from_plain( + cls, + int_data: torch.Tensor, + scale: torch.Tensor, + zero_point: torch.Tensor, + ): + pass + + def _get_to_kwargs(self, *args, **kwargs): + device, dtype, _, memory_format = torch._C._nn._parse_to(*args, **kwargs) + device = self.device if device is None else device + dtype = self.dtype if dtype is None else dtype + memory_format = ( + memory_format if memory_format is not None else torch.preserve_format + ) + kwargs = { + "device": device, + "dtype": dtype, + "memory_format": memory_format, + } + return kwargs + +class AffineQuantizedTensor(torch.Tensor): + """ + Affine quantized tensor subclass. Affine quantization means we quantize the floating point tensor with an affine transformation: + quantized_tensor = float_tensor / scale + zero_point + + The shape and dtype of the tensor subclass represent how the tensor subclass looks externally, + regardless of the internal representation's type or orientation. + + fields: + layout_tensor (AQTLayout): tensor that serves as a general layout storage for the quantized data, + e.g. storing plain tensors (int_data, scale, zero_point) or packed formats depending on device + and operator/kernel + block_size (Tuple[int, ...]): granularity of quantization, this means the size of the tensor elements that's sharing the same qparam + e.g. when size is the same as the input tensor dimension, we are using per tensor quantization + shape (torch.Size): the shape for the Tensor + quant_min (Optional[int]): minimum quantized value for the Tensor, if not specified, it will be derived from dtype of `int_data` + quant_max (Optional[int]): maximum quantized value for the Tensor, if not specified, it will be derived from dtype of `int_data` + zero_point_domain (ZeroPointDomain): the domain that zero_point is in, should be eitehr integer or float + if zero_point is in integer domain, zero point is added to the quantized integer value during + quantization + if zero_point is in floating point domain, zero point is subtracted from the floating point (unquantized) + value during quantization + default is ZeroPointDomain.INT + input_quant_func (Optional[Callable]): function for quantizing the input float Tensor to a quantized tensor subclass object, that takes float Tensor as input and outputs an AffineQuantizedTensor object + dtype: dtype for external representation of the tensor, e.g. torch.float32 + """ + + @staticmethod + def __new__( + cls, + layout_tensor: AQTLayout, + block_size: Tuple[int, ...], + shape: torch.Size, + quant_min: Optional[int] = None, + quant_max: Optional[int] = None, + zero_point_domain: ZeroPointDomain = ZeroPointDomain.INT, + dtype=None, + strides=None, + ): + kwargs = {} + kwargs["device"] = layout_tensor.device + kwargs["layout"] = ( + kwargs.get("layout") if kwargs.get("layout", False) else layout_tensor.layout + ) + kwargs["dtype"] = dtype + if strides is not None: + kwargs["strides"] = strides + kwargs["requires_grad"] = False + return torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs) # type: ignore[attr-defined] + + def __init__( + self, + layout_tensor: AQTLayout, + block_size: Tuple[int, ...], + shape: torch.Size, + quant_min: Optional[int] = None, + quant_max: Optional[int] = None, + zero_point_domain: ZeroPointDomain = ZeroPointDomain.INT, + dtype=None, + strides=None, + ): + self.layout_tensor = layout_tensor + self.block_size = block_size + self.quant_min = quant_min + self.quant_max = quant_max + self.zero_point_domain = zero_point_domain + + def __repr__(self): + return ( + f"{self.__class__.__name__}(data={self.dequantize()}, shape={self.shape}, " + f"device={self.device}, dtype={self.dtype}, requires_grad={self.requires_grad})" + ) + + def dequantize(self, output_dtype=None): + if output_dtype is None: + output_dtype = self.dtype + int_data, scale, zero_point = self.layout_tensor.get_plain() + return dequantize_affine(int_data, self.block_size, scale, zero_point, int_data.dtype, self.quant_min, self.quant_max, self.zero_point_domain, output_dtype=output_dtype) + + def __tensor_flatten__(self): + return ["layout_tensor"], [self.block_size, self.shape, self.quant_min, self.quant_max, self.zero_point_domain, self.dtype] + + @classmethod + def __tensor_unflatten__( + cls, tensor_data_dict, tensor_attributes, outer_size, outer_stride + ): + layout_tensor = tensor_data_dict["layout_tensor"] + block_size, shape, quant_min, quant_max, zero_point_domain, dtype = tensor_attributes + return cls( + layout_tensor, + block_size, + shape if outer_size is None else outer_size, + quant_min, + quant_max, + zero_point_domain, + dtype=dtype, + strides=outer_stride, + ) + + @classmethod + def from_float( + cls, + input_float: torch.Tensor, + mapping_type: MappingType, + block_size: Tuple[int, ...], + target_dtype: torch.dtype, + quant_min: Optional[int] = None, + quant_max: Optional[int] = None, + eps: Optional[float] = None, + scale_dtype: Optional[torch.dtype] = None, + zero_point_dtype: Optional[torch.dtype] = None, + preserve_zero: bool = True, + zero_point_domain: ZeroPointDomain = ZeroPointDomain.INT, + extended_layout: str = "plain", + # TODO: this is only for "tensor_core_tiled", need to figure out + # the proper API for this arg + inner_k_tiles: Optional[int] = None, + ): + original_shape = input_float.shape + if extended_layout == "tensor_core_tiled": + orig_out_features, orig_in_features = input_float.shape + in_features = find_multiple(orig_in_features, 1024) + out_features = find_multiple(orig_out_features, 8) + input_float = torch.nn.functional.pad( + input_float, + (0, in_features - orig_in_features, 0, out_features - orig_out_features), + ) + + scale, zero_point = choose_qparams_affine(input_float, mapping_type, block_size, target_dtype, quant_min, quant_max, eps, scale_dtype, zero_point_dtype, preserve_zero, zero_point_domain) + int_data = quantize_affine(input_float, block_size, scale, zero_point, target_dtype, quant_min, quant_max, zero_point_domain) + + layout_cls_ctr = get_layout_tensor_constructor(extended_layout) + # TODO: this is temporary, need to come up with the proper UX + if extended_layout == "tensor_core_tiled": + layout_tensor = layout_cls_ctr(int_data, scale, zero_point, inner_k_tiles) + else: + layout_tensor = layout_cls_ctr(int_data, scale, zero_point) + return cls( + layout_tensor, + block_size, + original_shape, + quant_min, + quant_max, + zero_point_domain, + dtype=input_float.dtype + ) + + @property + def extended_layout(self) -> str: + return self.layout_tensor.extended_layout + + @classmethod + def __torch_function__(cls, func, types, args=(), kwargs=None): + kwargs = {} if kwargs is None else kwargs + + if func in _ATEN_OP_OR_TORCH_FN_TABLE[cls]: + return _ATEN_OP_OR_TORCH_FN_TABLE[cls][func](*args, **kwargs) + + with torch._C.DisableTorchFunctionSubclass(): + return func(*args, **kwargs) + + + def _get_to_kwargs(self, *args, **kwargs): + device, dtype, _, memory_format = torch._C._nn._parse_to(*args, **kwargs) + device = self.device if device is None else device + dtype = self.dtype if dtype is None else dtype + memory_format = ( + memory_format if memory_format is not None else torch.preserve_format + ) + kwargs = { + "device": device, + "dtype": dtype, + "memory_format": memory_format, + } + return kwargs + + def to(self, *args, **kwargs): + kwargs = self._get_to_kwargs(*args, **kwargs) + return self.__class__( + self.layout_tensor.to(kwargs["device"]), + self.block_size, + self.shape, + self.quant_min, + self.quant_max, + self.zero_point_domain, + **kwargs, + ) + + def _apply_fn_to_data(self, fn): + return self.__class__( + fn(self.layout_tensor), + self.block_size, + self.shape, + self.quant_min, + self.quant_max, + self.zero_point_domain, + dtype=self.dtype, + strides=self.stride(), + ) + + @classmethod + def __torch_dispatch__(cls, func, types, args, kwargs): + # Note: we only added cpu path here for 8da4w, this is for executorch, in the future + # 1. we'll add cpu/cuda version (int4mm etc.) + # 2. we'll need to hide the 8da4w executorch version under things like layouts (we also have multiple impl for cpu kernel as Michael mentioned), so it will be something like + # cpu device + et laytout --> gives current 8da4w executorch representation + # cpu device + avx layout --> gives optimized kernel for 8da4w in avx cpu etc. + # cuda device + some layout --> gives cuda kernel + + # two scenarios where we currently fall back to vanilla mm: + # 1 - when tensor is on CUDA: we'll add this later, we'll also enable dispatching to optimized + # kernels in CPU as well, see the note above + # 2 - we're given non-floats - quantizing long to int8 is crazy + + if func in _ATEN_OP_OR_TORCH_FN_TABLE[cls]: + return _ATEN_OP_OR_TORCH_FN_TABLE[cls][func](func, *args, **kwargs) + + raise NotImplementedError( + f"AffineQuantizedTensor dispatch: attempting to run {func}, this is not supported" + ) + +def implements(aten_ops_or_torch_fn): + return _implements(AffineQuantizedTensor, aten_ops_or_torch_fn) + +def register_layout_cls(extended_layout: str): + return _register_layout_cls(AffineQuantizedTensor, extended_layout) + +def get_layout_tensor_constructor(extended_layout: str): + return _get_layout_tensor_constructor(AffineQuantizedTensor, extended_layout) + +@register_layout_cls("plain") +class PlainAQTLayout(AQTLayout): + """ + Layout storage class for plain layout for affine quantized tensor, it stores int_data, scale, zero_point + tensors directly as plain tensors. + + fields: + int_data (torch.Tensor): the quantized integer data Tensor + scale (torch.Tensor): the scale Tensor used to map between floating point tensor to quantized tensor + zero_point (torch.Tensor): the zero_point Tensor used to map between floating point tensor to quantized tensor + """ + def __new__( + cls, + int_data: torch.Tensor, + scale: torch.Tensor, + zero_point: torch.Tensor, + ): + kwargs = {} + kwargs["device"] = int_data.device + kwargs["layout"] = ( + kwargs.get("layout") if kwargs.get("layout", False) else int_data.layout + ) + kwargs["dtype"] = int_data.dtype + kwargs["requires_grad"] = False + shape = int_data.shape + return torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs) # type: ignore[attr-defined] + + def __init__( + self, + int_data: torch.Tensor, + scale: torch.Tensor, + zero_point: torch.Tensor, + ): + self.int_data = int_data + self.scale = scale + self.zero_point = zero_point + + def __tensor_flatten__(self): + return ["int_data", "scale", "zero_point"], [] + + @classmethod + def __tensor_unflatten__( + cls, tensor_data_dict, tensor_attributes, outer_size, outer_stride + ): + int_data, scale, zero_point = tensor_data_dict["int_data"], tensor_data_dict["scale"], tensor_data_dict["zero_point"] + return cls(int_data, scale, zero_point) + + def to(self, *args, **kwargs): + kwargs = self._get_to_kwargs(*args, **kwargs) + return self.__class__( + self.int_data.to(kwargs["device"]), + self.scale.to(kwargs["device"]), + self.zero_point.to(kwargs["device"]), + ) + + def _apply_fn_to_data(self, fn): + return self.__class__( + fn(self.int_data), + fn(self.scale), + fn(self.zero_point), + ) + + @classmethod + def __torch_dispatch__(cls, func, types, args, kwargs): + kwargs = {} if kwargs is None else kwargs + + if func is aten.detach.default: + return return_and_correct_aliasing( + func, args, kwargs, args[0]._apply_fn_to_data(torch.detach) + ) + + if func is aten.t.default: + tensor = args[0] + new = tensor.__class__( + tensor.int_data.view(tensor.shape[::-1]), tensor.scale, tensor.zero_point + ) + return return_and_correct_aliasing(func, args, kwargs, new) + + raise NotImplementedError( + f"PlainAQTLayout dispatch: attempting to run {func}, this is not supported" + ) + + __torch_function__ = torch._C._disabled_torch_function_impl + + def get_plain(self): + return self.int_data, self.scale, self.zero_point + + @classmethod + def from_plain( + cls, + int_data: torch.Tensor, + scale: torch.Tensor, + zero_point: torch.Tensor, + ): + return cls(int_data, scale, zero_point) + +@register_layout_cls("tensor_core_tiled") +class TensorCoreTiledAQTLayout(AQTLayout): + """ + Layout storage class for tensor_core_tiled layout for affine quantized tensor, this is for int4 only, + it stores the original tensor of dimension [n][k] (int32 dtype) as packed weight of 4-d tensor of + dimension: [n / 8][k / (inner_k_tiles * 16)][32][inner_k_tiles / 2] + + fields: + packed_weight (torch.Tensor): the 4-d packed tensor in a tensor_core_tiled layout + scale_and_zero (torch.Tensor): the combined scale Tensor used to map between floating point tensor to quantized tensor and zero_point Tensor + """ + + def __new__( + cls, + packed_weight: torch.Tensor, + scale_and_zero: torch.Tensor, + transposed: bool, + ): + kwargs = {} + kwargs["device"] = packed_weight.device + kwargs["layout"] = ( + kwargs.get("layout") if kwargs.get("layout", False) else packed_weight.layout + ) + kwargs["dtype"] = packed_weight.dtype + kwargs["requires_grad"] = False + shape = packed_weight.shape + return torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs) # type: ignore[attr-defined] + + def __init__( + self, + packed_weight: torch.Tensor, + scale_and_zero: torch.Tensor, + transposed: bool, + ): + self.packed_weight = packed_weight + self.scale_and_zero = scale_and_zero + self.transposed = False + + def __tensor_flatten__(self): + return ["packed_weight", "scale_and_zero"], [self.transposed] + + @classmethod + def __tensor_unflatten__( + cls, tensor_data_dict, tensor_attributes, outer_size, outer_stride + ): + packed_weight, scale_and_zero = tensor_data_dict["packed_weight"], tensor_data_dict["scale_and_zero"] + transposed, = tensor_attributes + return cls(packed_weight, scale_and_zero, transposed) + + @classmethod + def from_plain(cls, int_data, scale, zero_point, inner_k_tiles=8): + packed_weight = torch.ops.aten._convert_weight_to_int4pack(int_data.to(torch.int32), inner_k_tiles) + scale = scale.reshape(int_data.shape[0], -1) + zero_point = zero_point.reshape(int_data.shape[0], -1) + scale_and_zero = pack_tinygemm_scales_and_zeros(scale, zero_point) + return cls(packed_weight, scale_and_zero, False) + + def to(self, *args, **kwargs): + kwargs = self._get_to_kwargs(*args, **kwargs) + device = kwargs["device"] + if device != "cuda" or (isinstance(device, torch.device) and device.type != "cuda"): + raise ValueError(f"TensorCoreTiledAQTLayout is only available for cuda device") + return self.__class__( + self.packed_weight.to(kwargs["device"]), + self.scale_and_zero.to(kwargs["device"]), + self.transposed + ) + + def _apply_fn_to_data(self, fn): + self.packed_weight = fn(self.packed_weight) + self.scale_and_zero = fn(self.scale_and_zero) + return self + + @classmethod + def __torch_dispatch__(cls, func, types, args, kwargs): + kwargs = {} if kwargs is None else kwargs + + if func is aten.detach.default: + return return_and_correct_aliasing( + func, args, kwargs, args[0]._apply_fn_to_data(torch.detach) + ) + + if func is aten.t.default: + """we don't need to repack the weight and just rely on external + shape being changed and record the status of transpose/no-transpose + """ + args[0].transposed = not args[0].transposed + return return_and_correct_aliasing(func, args, kwargs, args[0]) + + raise NotImplementedError( + f"TensorCoreTiledAQTLayout dispatch: attempting to run {func}, this is not supported" + ) + + __torch_function__ = torch._C._disabled_torch_function_impl + + def get_plain(self): + from torchao.quantization.quant_primitives import ( + ZeroPointDomain, + unpack_tinygemm_scales_and_zeros, + quantize_affine, + ) + cur_shape = self.shape + assert len(cur_shape) == 4 + inner_k_tiles = cur_shape[-1] * 2 + original_shape = (cur_shape[0] * 8, cur_shape[1] * (inner_k_tiles * 16)) + eye_shape = original_shape[1] + block_size = (1, 32) + device = self.device + original_dtype = torch.bfloat16 + groupsize = 32 + target_dtype = torch.int32 + quant_min = 0 + quant_max = 15 + zero_point_domain = ZeroPointDomain.FLOAT + assert len(block_size) == 2 and block_size[0] == 1 + groupsize = block_size[-1] + dequantized = torch.ops.aten._weight_int4pack_mm(torch.eye(eye_shape, device=device, dtype=original_dtype), self.packed_weight, groupsize, self.scale_and_zero) + dequantized = dequantized.t().contiguous() + scale, zero = unpack_tinygemm_scales_and_zeros(self.scale_and_zero) + # TODO: move this to `unpack_tinygemm_scales_and_zeros`? + scale = scale.reshape(scale.shape[:-1]).contiguous() + zero = zero.reshape(zero.shape[:-1]).contiguous() + int_data = quantize_affine(dequantized, block_size, scale, zero, target_dtype, quant_min, quant_max, zero_point_domain) + return int_data, scale, zero + +def _quantized_linear_op(input_tensor, weight_qtensor, bias): + """ + Quantized version of F.linear operator + + Args: + input_tensor: dimension is (batch_size, in_features) + weight_tensor: dimension is (out_features, in_features) + bias: dimension is (out_features,) + """ + is_cuda = weight_qtensor.is_cuda + is_cpu = weight_qtensor.device == torch.device("cpu") + if isinstance(weight_qtensor, AffineQuantizedTensor): + weight_is_int8 = _aqt_is_int8(weight_qtensor) + weight_is_uint4 = _aqt_is_uint4(weight_qtensor) + + if isinstance(input_tensor, AffineQuantizedTensor): + # if input tensor is quantized, either dispatch to the int8 mm kernel + # or just dequantize the input tensor + input_is_int8 = _aqt_is_int8_reduced_range(input_tensor) + if ( + is_cuda and + input_is_int8 and + input_tensor.dtype == weight_qtensor.dtype and + input_tensor.extended_layout == "plain" and + weight_qtensor.extended_layout == "plain" + ): + # + # 1. do the matrix form of dot(X_i, W_j) + # + # + # 2. rescale the output + # + # in cases with large matrices, y_dot_int32 can grow sufficiently + # large that y_dot_int32 * a float16 scale is greater than the maximum + # value of a float 16, (which results in a value of inf even if multiplying + # by the other scale would bring it within the expected range) + + x_vals_int8 = input_tensor.layout_tensor.int_data + x_scales = input_tensor.layout_tensor.scale + w_vals_int8_t = weight_qtensor.layout_tensor.int_data.contiguous().t() + w_scales = weight_qtensor.layout_tensor.scale + tmp = x_vals_int8.reshape(-1, x_vals_int8.shape[-1]) + y_dot_scaled = int_scaled_matmul(tmp, w_vals_int8_t, x_scales.reshape(-1, 1)) + + y = (y_dot_scaled * w_scales).reshape( + *x_vals_int8.shape[:-1], y_dot_scaled.shape[-1] + ) + + # can downcast only at the very end + output_dtype = input_tensor.dtype + y = y.to(output_dtype) + if bias is not None: + y += bias + return y + else: + input_tensor = input_tensor.dequantize() + + # weight only quantization + # TODO: enable cpu and mps path as well + # TODO: make sure weight dimension matches the expectation of the int4mm kernel + # TODO: cpu/cuda are sharing the same code now, may need some special handling for cpu + if ( + weight_is_uint4 and + weight_qtensor.dtype == torch.bfloat16 and + len(weight_qtensor.shape) == 2 and + weight_qtensor.zero_point_domain == ZeroPointDomain.FLOAT and + weight_qtensor.extended_layout == "tensor_core_tiled" + ): + assert weight_qtensor.block_size[0] == 1, f"Requires groupwise quantization, got block_size: {block_size}" + assert input_tensor.shape[-1] == weight_qtensor.shape[1], ( + f"need input_tensor shape: {input_tensor.shape} final" + f"dim to match weight_tensor shape: {weight_qtensor.shape} second dim " + ) + + # TODO: check groupsize quantization + # avoid circular dep, TODO: move this to a common util.py + act_mat = input_tensor + # weight is packed from padded (out_features, in_features) weight tensor + # (same dimension requirement as F.linear weight) + packed_weight = weight_qtensor.layout_tensor.packed_weight + scale_and_zero = weight_qtensor.layout_tensor.scale_and_zero + + orig_act_size = act_mat.size() + orig_dtype = act_mat.dtype + + # reshape and pad activation + act_mat = act_mat.reshape(-1, act_mat.shape[-1]).to(torch.bfloat16) + pad_size = find_multiple(act_mat.shape[-1], 1024) + act_mat = torch.nn.functional.pad(act_mat, (0, pad_size - act_mat.shape[-1])) + + # groupwise int4 quantization + groupsize = weight_qtensor.block_size[1] + y = torch.ops.aten._weight_int4pack_mm(act_mat.contiguous(), packed_weight, groupsize, scale_and_zero) + + # remove out_feature padding + orig_out_features = weight_qtensor.shape[-2] + y = y[:, :orig_out_features] + y = y.reshape(*orig_act_size[:-1], orig_out_features) + + if bias is not None: + y += bias + return y.to(orig_dtype) + elif ( + weight_is_int8 and + len(weight_qtensor.shape) == 2 and + len(weight_qtensor.block_size) == 2 and + weight_qtensor.block_size[0] == 1 and + weight_qtensor.block_size[1] == weight_qtensor.shape[1] and + weight_qtensor.zero_point_domain == ZeroPointDomain.INT and + weight_qtensor.extended_layout == "plain" + ): + # TODO: enable cpu and mps efficient path + # per channel int8 weight only quantizated mm + w_vals_int8_t = weight_qtensor.layout_tensor.int_data.t() + scale = weight_qtensor.layout_tensor.scale + orig_dtype = input_tensor.dtype + y = ( + torch.mm( + input_tensor.reshape(-1, input_tensor.shape[-1]), + w_vals_int8_t.to(input_tensor.dtype), + ) + * scale + ) + y = y.reshape(*input_tensor.shape[:-1], y.shape[-1]) + if bias is not None: + y += bias + return y.to(orig_dtype) + + # is_cpu and is_mps only, some issue with is_contiguous() currently + # return torch.ops.aten._weight_int8pack_mm(input_tensor.contiguous(), w_vals_int8_t, weight_qtensor.layout_tensor.scale) + + raise NotImplementedError("No specialized dispatch found for quantized linear op") + + +@implements(torch.nn.functional.linear) +def functional_linear(*args, **kwargs): + input_tensor, weight_tensor, bias = ( + args[0], + args[1], + args[2] if len(args) > 2 else None, + ) + # using try/except here so that we can have a general fallback when input_tensor/weight_tensor + # is not picked up by any of the dispatch paths in `_quantized_linear_op`, this allows us to + # make the branches easier to understand in `_quantized_linear_op` + try: + return _quantized_linear_op(input_tensor, weight_tensor, bias) + except: + if isinstance(input_tensor, AffineQuantizedTensor): + input_tensor = input_tensor.dequantize() + if isinstance(weight_tensor, AffineQuantizedTensor): + weight_tensor = weight_tensor.dequantize() + return torch.nn.functional.linear(input_tensor, weight_tensor, bias) + +@implements([aten.mm.default, aten.addmm.default]) +def aten_mm(func, *args, **kwargs): + if not args[0].is_floating_point(): + raise NotImplementedError(f"{func} is not implemented for non floating point input") + + # using try/except here so that we can have a general fallback when input_tensor/weight_tensor + # is not picked up by any of the dispatch paths in `_quantized_linear_op`, this allows us to + # make the branches easier to understand in `_quantized_linear_op` + if func == aten.addmm.default: + input_tensor, weight_tensor, bias = ( + args[1], + args[2], + args[0], + ) + try: + weight_tensor = weight_tensor.t() + return _quantized_linear_op(input_tensor, weight_tensor, bias) + except: + if isinstance(input_tensor, AffineQuantizedTensor): + input_tensor = input_tensor.dequantize() + if isinstance(weight_tensor, AffineQuantizedTensor): + weight_tensor = weight_tensor.dequantize() + return func(bias, input_tensor, weight_tensor) + else: + input_tensor, weight_tensor, bias = ( + args[0], + args[1], + None + ) + try: + weight_tensor = weight_tensor.t() + return _quantized_linear_op(input_tensor, weight_tensor, bias) + except: + if isinstance(input_tensor, AffineQuantizedTensor): + input_tensor = input_tensor.dequantize() + if isinstance(weight_tensor, AffineQuantizedTensor): + weight_tensor = weight_tensor.dequantize() + return func(input_tensor, weight_tensor) + +@implements([aten.detach.default]) +def detach(func, *args, **kwargs): + return return_and_correct_aliasing( + func, args, kwargs, args[0]._apply_fn_to_data(torch.detach) + ) + + +@implements([aten.clone.default]) +def clone(func, *args, **kwargs): + return return_and_correct_aliasing( + func, args, kwargs, args[0]._apply_fn_to_data(torch.clone) + ) + + +@implements([aten._to_copy.default]) +def _to_copy(func, *args, **kwargs): + return return_and_correct_aliasing( + func, + args, + kwargs, + args[0].to(*args[1:], **kwargs)._apply_fn_to_data(torch.clone), + ) + +@implements([aten.t.default]) +def t(func, *args, **kwargs): + block_size = args[0].block_size + assert len(block_size) == 2 + transposed_block_size = (block_size[1], block_size[0]) + tensor = args[0] + shape = tensor.shape[::-1] + new = tensor.__class__( + tensor.layout_tensor.t(), transposed_block_size, shape, tensor.quant_min, tensor.quant_max, tensor.zero_point_domain, dtype=tensor.dtype, strides=tensor.stride() + ) + return return_and_correct_aliasing(func, args, kwargs, new) + +to_affine_quantized = AffineQuantizedTensor.from_float diff --git a/videollama2/lib/python3.10/site-packages/torchao/quantization/GPTQ.py b/videollama2/lib/python3.10/site-packages/torchao/quantization/GPTQ.py new file mode 100644 index 0000000000000000000000000000000000000000..275e716aa13e3084c5b462882cc145977ec73b90 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torchao/quantization/GPTQ.py @@ -0,0 +1,1106 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import logging +from typing import Optional, List, Type + +import torch + +import torch.fx as fx +import torch.nn as nn +import torch.nn.functional as F + +from torch.utils._pytree import tree_flatten, tree_unflatten + +from .utils import ( + _lm_eval_available, + _MultiInput, +) +from torchao.utils import ( + find_multiple, +) +from torchao.utils import TORCH_VERSION_AFTER_2_3 +from typing import Any, Dict, Optional +from .unified import Quantizer + +from .utils import ( + get_groupwise_affine_qparams, + groupwise_affine_quantize_tensor_from_qparams, + groupwise_affine_dequantize_tensor_from_qparams, + pack_tinygemm_scales_and_zeros, + groupwise_affine_quantize_tensor, +) +aten = torch.ops.aten + +if not _lm_eval_available: + logging.info("lm_eval is not installed, GPTQ may not be usable") + +add_ons = [] + +if TORCH_VERSION_AFTER_2_3: + add_ons += ["Int8DynActInt4WeightQuantizer", "Int8DynActInt4WeightGPTQQuantizer"] + + +__all__ = [ + "Int4WeightOnlyGPTQQuantizer", + "Int4WeightOnlyQuantizer", +] + add_ons + + +class GenericGPTQRunner(fx.Interpreter): + """ + This is a generic GPTQ runner that takes an existing model and applies GPTQ. + It uses torch._dynamo.export to obtain a graph of the model and then hooks + into function calls and when it detects a linear, it applies GPTQ to the weight + given the calibration of inputs passed in at initialization. It puts the results + into the state_dict so that the quantized model weights/qparams can be loaded + directly into the model. + + intended to be used in concert with a GPTQQuantizer class to define the quantization mode. + """ + + def __init__( + self, + model, + inputs: _MultiInput, + blocksize=128, + percdamp=0.01, + groupsize=128, + ): + + self.id_to_name = { + id(value): name for name, value in dict(model.named_parameters()).items() + } + + # trace model for one input + one_input = [multi.values[0].cpu() for multi in inputs] # pyre-ignore[16] + # needed for GPTQ on the torchao llama model + import torchao + torchao._models.llama.model.use_index_put_for_kv_cache = True + exported_model = torch._dynamo.export( + model.cpu(), aten_graph=True, pre_dispatch=True, tracing_mode="fake" + )(*one_input) + super().__init__(exported_model.graph_module) + + self.new_state_dict = model.state_dict() + + self.blocksize = blocksize + + self.percdamp = percdamp + + self.groupsize = groupsize + self.inputs = inputs + self.gptq_done = False + self.debug = True + + def configure_quantization_mode( + self, + get_qparams_func, + quantize_func, + dequantize_func, + combine_qparams_list_func, + make_names_and_values_dict_func, + skip_layer_func, + act_fake_quant_func = None, + ): + # these functions need to already be curried with all inputs other than weight, qparams + + self.get_qparams_func = ( + get_qparams_func # accepts [2d weight tensor], outputs qparams. + ) + + self.quantize_func = quantize_func # accepts [2d weight tensor], [qparams], outputs a 2d quantized tensor of desired dtype + + self.dequantize_func = dequantize_func + # accepts [quantized] tensor and [qparams], outputs a 2d dequantized tensor of type float, + # assumes this output .to(w_orig_dtype) is ~eventual desired dequant behavior + + # `combine_qparams_list_func`. + self.combine_qparams_list_func = combine_qparams_list_func + # accepts [`list` of qparams] from quantizing one group at a time, + # outputs a qparams object that could be passed into quant/dequantize_func + + self.skip_layer_func = skip_layer_func # accepts [weight tensor], outputs a bool on whether or not to apply gptq to this layer + + # `make_names_and_values_dict_func`. + self.make_names_and_values_dict_func = make_names_and_values_dict_func # accepts [2d quantized tensor], [qparams], returns a dict of names, values to put in state_dict + # note any final packing for storage should happen here + + # `act_fake_quant_func` + if act_fake_quant_func is None: + self.act_fake_quant_func = lambda x: x + else: + self.act_fake_quant_func = act_fake_quant_func # accepts [activation tensor], returns a fake-quantized activation tensor + return self + + def run(self): + assert ( + self.get_qparams_func is not None + ), "need to configure quantization mode before running" + self.gptq_done = True + super().run(*self.inputs) + + def get_quantized_state_dict(self): + assert ( + self.gptq_done + ), "need to run GPTQRunner before you can get_quantized_state_dict" + quantized_state_dict = self.new_state_dict + # Don't want to store/load the kv_cache so remove it from the state_dict + del_list = [] + for param_fqn in quantized_state_dict: + if "kv_cache" in param_fqn: + del_list.append(param_fqn) + for param_fqn in del_list: + quantized_state_dict.pop(param_fqn) + return quantized_state_dict + + def call_function(self, target, args, kwargs, already_quantized=False): # noqa: C901 + + def tensors_to_cuda(args): + new_args = [] + for x in args: + new_args.append(x.cuda() if isinstance(x, torch.Tensor) else x) + return new_args + + # flatten args and kwargs together + flat_args, spec = tree_flatten((args, kwargs)) + # move all single tensors to cuda, will move _MultiInputs to cuda one at a time + flat_args = tensors_to_cuda(flat_args) + + has_multi_input = _MultiInput in [type(x) for x in flat_args] + if has_multi_input: + # Just some trickery to convert + # [_MultiInput[a, a, a], _MultiInput(b, b, b)] => [a, b], [a, b], [a, b] + multi_input_count = max( + [len(x.values) if isinstance(x, _MultiInput) else 1 for x in flat_args] + ) + transposed_args = list( + zip( + *[ + ( + x.values + if isinstance(x, _MultiInput) + else [x] * multi_input_count + ) + for x in flat_args + ] + ) + ) + else: + transposed_args = [flat_args] + outputs = [] + + # check whether we apply GPTQ to this module + quantize_linear = ( + (target == aten.linear.default) # if its a linear + and id(args[1]) in self.id_to_name # and if we know the layer name + # and we haven't already quantized this layer + and not already_quantized + # and if the skip_layer_func doesn't say we should skip + and not (self.skip_layer_func is not None and self.skip_layer_func(args[1])) + + ) # then we will quantize this linear layer/weight + + if quantize_linear: # instantiate variables for GPTQ + H = 0 + total_batches = 0 + + for inp in transposed_args: + inp = tensors_to_cuda(inp) + cur_args, cur_kwargs = tree_unflatten(inp, spec) + + if ( + quantize_linear + ): # calculate H instead of output (will run the linear eventually with updated weight) + x = cur_args[0].float() + x = self.act_fake_quant_func(x) + shape = x.shape + n = 1 if len(shape) == 2 else shape[0] + H *= total_batches / (total_batches + n) + total_batches += n + x = ((2 / total_batches) ** (1 / 2)) * x.reshape( + -1, shape[-1] + ).t().float() + H += x.matmul(x.t()) + else: + # weight has already been quantized but still need to apply + # activation quant for final calculation + if already_quantized: + cur_args = (self.act_fake_quant_func(cur_args[0]), *cur_args[1:]) + + # get output if its not a linear + out = super().call_function(target, cur_args, cur_kwargs) + if isinstance(out, torch.Tensor): + outputs.append(out.cpu()) + else: + outputs.append(out) + + if quantize_linear: + mod_fqn = ".".join(self.id_to_name[id(args[1])].split(".")[:-1]) + + W = args[1].to(H.device) + + Q, DQ, qparams = self.faster_quant(H, W.detach()) + print(mod_fqn) + + # `make_names_and_values_dict_func`. + names_and_values_dict = self.make_names_and_values_dict_func(Q, qparams) + + # delete old weight + if mod_fqn + ".weight" in self.new_state_dict: + self.new_state_dict.pop(mod_fqn + ".weight") + if len(args) > 2: + self.new_state_dict[mod_fqn + ".bias"] = args[2] + for name, value in names_and_values_dict.items(): + self.new_state_dict[mod_fqn + "." + name] = value + + # run linear with new weight to get corrected output + new_out = self.call_function( + target, (args[0], DQ, *args[2:]), kwargs, already_quantized=True + ) + + if self.debug: + old_out = self.call_function( + target, (args[0][:2], args[1], *args[2:]), kwargs, already_quantized=True + ) + + def SQNR(x, y): + # TODO: Use of deprecated function torch.norm + return 20 * torch.log10( + torch.linalg.norm(x) / torch.linalg.norm(x - y) + ) + + # `dequantize_func`. + DQ_after = self.dequantize_func(Q, qparams).to(W.dtype) + print( + "SQNR for QDQ (this should be inf)", SQNR(DQ, DQ_after) + ) # matches + print( + "SQNR for weight (can be low)", SQNR(W, DQ.cuda()) + ) # fine to not match + print( + "SQNR for output with GPTQ (hopefully 35+)", + torch.cat( + [ + SQNR(old.cpu(), new.cpu()).unsqueeze(0) + for (old, new) in zip(old_out.values, new_out.values[:2]) + ] + ).mean(), + ) + + # `get_qparams_func`. + qparams2 = self.get_qparams_func(W) + + Q2 = self.quantize_func(W, qparams2) + DQ2 = self.dequantize_func(Q2, qparams2).to(W.dtype) + old_q_out = self.call_function( + target, (args[0][:2], DQ2, *args[2:]), kwargs, already_quantized=True + ) + + print( + "SQNR for output without GPTQ (should be less than above)", + torch.cat( + [ + SQNR(old.cpu(), old_q.cpu()).unsqueeze(0) + for (old, old_q) in zip(old_out.values, old_q_out.values) + ] + ).mean(), + ) + return new_out + + return _MultiInput(outputs) if has_multi_input else outputs[0] + + def faster_quant(self, H, W): + percdamp = self.percdamp + blocksize = self.blocksize + groupsize = self.groupsize + orig_dtype = W.dtype + W = W.detach().float() + _, columns = W.shape[0], W.shape[1] + device = W.device + + if groupsize == -1: + + cur_qparams = self.get_qparams_func(W) + dead = torch.diag(H) == 0 + H[dead, dead] = 1 + W[:, dead] = 0 + + Losses = torch.zeros_like(W) + DQ = torch.zeros_like(W) + + damp = percdamp * torch.mean(torch.diag(H)) + diag = torch.arange(columns, device=device) + H[diag, diag] += damp + H = torch.linalg.cholesky(H) + H = torch.cholesky_inverse(H) + H = torch.linalg.cholesky(H, upper=True) + Hinv = H + + all_qparams = [] + for i1 in range(0, columns, blocksize): + i2 = min(i1 + blocksize, columns) + count = i2 - i1 + W1 = W[:, i1:i2].clone() + DQ1 = torch.zeros_like(W1) + Err1 = torch.zeros_like(W1) + Losses1 = torch.zeros_like(W1) + Hinv1 = Hinv[i1:i2, i1:i2] + for i in range(count): + w = W1[:, i] + d = Hinv1[i, i] + + if groupsize != -1 and (i1 + i) % groupsize == 0: # start of new group + cur_qparams = self.get_qparams_func( + W[:, (i1 + i) : (i1 + i + groupsize)] + ) + all_qparams.append(cur_qparams) + + q = self.quantize_func(w.unsqueeze(1), cur_qparams).flatten() + + # `dequantize_func`. + + dq = self.dequantize_func(q.unsqueeze(1), cur_qparams).flatten() + + DQ1[:, i] = dq + Losses1[:, i] = (w - dq) ** 2 / d**2 + + err1 = (w - dq) / d + W1[:, i:] -= ( + err1.to(Hinv1.dtype).unsqueeze(1).matmul(Hinv1[i, i:].unsqueeze(0)) + ) + Err1[:, i] = err1 + + DQ[:, i1:i2] = DQ1 + Losses[:, i1:i2] = Losses1 / 2 + + W[:, i2:] -= Err1.to(Hinv.dtype).matmul(Hinv[i1:i2, i2:]) + + torch.cuda.synchronize() + + if all_qparams == []: + + all_qparams.append(cur_qparams) + + # convert a list of qparams objects into a single one. enerally by + # concatenating a bunch of n,1 scale/zeros tensors into a n,num_groups tensor + + # `combine_qparams_list_func`. + all_qparams = self.combine_qparams_list_func(all_qparams) + Q = self.quantize_func(DQ, all_qparams) + return Q, DQ.to(orig_dtype), all_qparams + + +class GPTQQuantizer(Quantizer): + """ + This class implements a GPTQ Quantizer that can be used to apply GPTQ to a model in concert with the GenericGPTQRunner class. + Unlike the base Quantizer class, the user does not need to implement the create_quantized_state_dict, instead they have to reimplement + __init__ such that it defines the functions for the quantization mode. User is expected to reimplement convert_for_runtime. + + The following functions (which must be defined in __init__) are used to define the quantization mode for both GPTQ and + create_quantized_state_dict. Here is a description of each function. + + get_qparams_func: + A function that calculates the quantization qparams for an input tensor. + Args: + weight: A 2d weight tensor with non-integer dtype. + Returns: + qparams: it can have any format but will need to be handled by the other defined functions below. + + quantize_func: + A function that applies quantization to an input tensor. It should be noted + that this function needs to be able to handle quantizing the entire weight tensor, a single group, + or a single column. + Args: + weight: A 2d weight tensor with non-integer dtype. + qparams: the output from get_qparams_func + Returns: + quantized_weight: A 2d quantized weight tensor (generally with an integer dtype) + + + dequantize_func: + A function that dequantizes an input quantized weight tensor. It should be noted + that this function needs to be able to handle dequantizing the entire weight tensor, a single group, + or a single column. + Args: + quantized_weight: A 2d quantized weight tensor (generally with an integer dtype) + qparams: the output from get_qparams_func + Returns: + weight: A 2d weight tensor with non-integer dtype. + + act_fake_quant_func (optional): + A function that (dynamically) quantizes activation to input + Args: + input: input Tensor in f32/bf16/f16 + Returns: + output: dynamically quantized and dequantized Tensor (with the same dtype as input) + + combine_qparams_list_func: + A function that combines several qparams into one qparam. + Args: + qparams_list: a list of qparams objects, each obtained by calling get_qparams_func + on a single group from a weight tensor + Returns: + qparams: an object of the same format as the qparams above. + + skip_layer_func: + A function that determines which linear layers should be skipped during GPTQ + Args: + weight: A 2d weight tensor with non-integer dtype. + Returns: + skip: boolean indicating whether layer should be skipped + + make_names_and_values_dict_func: + A function that prepares the qparams and quantized_weight and creates a dictionary indicating how they + should be inserted into the state_dict. Generally any packing of the weight and qparams should be done here. + Args: + quantized_weight: A 2d quantized weight tensor (generally with an integer dtype) + qparams: the output from get_qparams_func + Returns: + names_and_values_dict: a dictionary mapping the name of the parameters of the quantized module to the + corresponding quantized weights and qparams. + """ + + def __init__(self): + + assert self.get_qparams_func is not None + + assert self.quantize_func is not None + + assert self.dequantize_func is not None + + assert self.combine_qparams_list_func is not None + + # `make_names_and_values_dict_func`. + assert self.make_names_and_values_dict_func is not None + + @torch.no_grad() + def _create_quantized_state_dict( + self, + model, + inputs, + blocksize, + percdamp, + groupsize, + # `typing.Dict[, ]` to avoid runtime subscripting errors. + ) -> Dict: + print("Tracing model for GPTQ") + GPTQ_runner = GenericGPTQRunner( + model, + inputs, + blocksize, + percdamp, + groupsize, + ).configure_quantization_mode( + self.get_qparams_func, # pyre-ignore[16] + self.quantize_func, # pyre-ignore[16] + self.dequantize_func, # pyre-ignore[16] + self.combine_qparams_list_func, # pyre-ignore[16] + self.make_names_and_values_dict_func, # pyre-ignore[16] + self.skip_layer_func, # pyre-ignore[16] + self.act_fake_quant_func if hasattr(self, "act_fake_quant_func") else None, # pyre-ignore[16] + ) + print("Applying GPTQ to weights") + GPTQ_runner.run() + return GPTQ_runner.get_quantized_state_dict() + + def _convert_for_runtime(self, model: torch.nn.Module) -> "nn.Module": + raise NotImplementedError("_convert_for_runtime not implemented") + + @torch.no_grad() + def quantize(self, model: torch.nn.Module, inputs: List[_MultiInput], **kwargs: Any) -> torch.nn.Module: + pass + +def _check_linear_int4_k(k, groupsize = 1, inner_k_tiles = None): + k_divisible_by_groupsize = k % groupsize == 0 + if inner_k_tiles is not None: + k_divisible_by_16_times_inner_k_tiles = k % (inner_k_tiles * 16) == 0 + return k_divisible_by_groupsize and k_divisible_by_16_times_inner_k_tiles + return k_divisible_by_groupsize + +def linear_forward_int4(x, weight_int4pack, scales_and_zeros, out_features, groupsize): + origin_x_size = x.size() + x = x.reshape(-1, origin_x_size[-1]) + c = torch.ops.aten._weight_int4pack_mm( + x.to(torch.bfloat16), + weight_int4pack, + groupsize, + scales_and_zeros.to(torch.bfloat16) + ).to(dtype=x.dtype) + new_shape = origin_x_size[:-1] + (out_features,) + c = c.reshape(new_shape) + return c + +class WeightOnlyInt4Linear(torch.nn.Module): + __constants__ = ['in_features', 'out_features'] + in_features: int + out_features: int + weight: torch.Tensor + + def __init__( + self, in_features: int, out_features: int, + bias=False, device=None, dtype=None, groupsize: int = 128, inner_k_tiles: int = 8, + ) -> None: + super().__init__() + self.padding = not _check_linear_int4_k(in_features, groupsize, inner_k_tiles) + if self.padding: + from model import find_multiple + self.origin_in_features = in_features + in_features = find_multiple(in_features, 1024) + + self.in_features = in_features + self.out_features = out_features + assert not bias, "require bias=False" + self.groupsize = groupsize + self.inner_k_tiles = inner_k_tiles + + assert out_features % 8 == 0, "require out_features % 8 == 0" + assert in_features % (inner_k_tiles * 16) == 0, "require in_features % (innerKTiles * 16) == 0" + self.register_buffer( + "weight", + torch.empty((out_features // 8, in_features // (inner_k_tiles * 16), 32, inner_k_tiles // 2), dtype=torch.int32) + ) + self.register_buffer( + "scales_and_zeros", + torch.empty((in_features // groupsize, out_features, 2), dtype=torch.bfloat16) + ) + + def forward(self, input: torch.Tensor) -> torch.Tensor: + if self.padding: + import torch.nn.functional as F + input = F.pad(input, pad=(0, self.in_features - self.origin_in_features)) + return linear_forward_int4( + input, + self.weight, self.scales_and_zeros, self.out_features, self.groupsize + ) + +def replace_linear_int4(module, groupsize, inner_k_tiles, padding_allowed, skip_layer_func = None): + + for name, child in module.named_children(): + if isinstance(child, nn.Linear) and (skip_layer_func is None or not skip_layer_func(child.weight)): + if _check_linear_int4_k(child.in_features, groupsize, inner_k_tiles) or padding_allowed: + setattr(module, name, WeightOnlyInt4Linear( + child.in_features, child.out_features, bias=False, + groupsize=groupsize, inner_k_tiles=inner_k_tiles, + )) + else: + replace_linear_int4(child, groupsize, inner_k_tiles, padding_allowed, skip_layer_func) + +class Int4WeightOnlyQuantizer(Quantizer): + def __init__( + self, + groupsize: int = 256, + padding_allowed: bool = True, + inner_k_tiles: Optional[int] = 8, + device: torch.device = torch.device("cuda"), + ) -> None: + super().__init__() + assert inner_k_tiles in [2, 4, 8] + assert groupsize in [32, 64, 128, 256] + + self.inner_k_tiles = inner_k_tiles + self.groupsize: int = groupsize + self.padding_allowed: bool = padding_allowed + self.device: torch.device = device + + @torch.no_grad() + def _create_quantized_state_dict( + self, model: torch.nn.Module + ) -> Dict[str, torch.Tensor]: + cur_state_dict = model.state_dict() + for fqn, mod in model.named_modules(): + if isinstance(mod, torch.nn.Linear): + assert not mod.bias + out_features = mod.out_features + in_features = mod.in_features + # assert out_features % 8 == 0, "require out_features % 8 == 0" + print(f"linear: {fqn}, in={in_features}, out={out_features}") + + assert ( + in_features % self.groupsize == 0 + ), f"require in_features:{in_features} % self.groupsize:{self.groupsize} == 0" + + weight = mod.weight.data + if not _check_linear_int4_k( + in_features, self.groupsize, self.inner_k_tiles + ): + if self.padding_allowed: + from .utils import find_multiple + import torch.nn.functional as F + print(f"warning: {fqn} is padded to satisfy in_features % 1024 == 0") + padded_in_features = find_multiple(in_features, 1024) + weight = F.pad(weight, pad=(0, padded_in_features - in_features)) + else: + print(f"warning: {fqn} is skipped, int4 requires that in_features is 32, 64, or is divisible by 1024, " + + "and that groupsize and inner_k_tiles*16 evenly divide into it") + continue + ( + w_int4x8, + scales_and_zeros + ) = groupwise_affine_quantize_tensor( + weight, + 4, # n_bit + self.groupsize, + ) + weight_int4pack = torch.ops.aten._convert_weight_to_int4pack(w_int4x8.to(self.device), self.inner_k_tiles) + cur_state_dict[f"{fqn}.weight"] = weight_int4pack.to(self.device) + cur_state_dict[f"{fqn}.scales_and_zeros"] = scales_and_zeros.to(self.device) + return cur_state_dict + + def _convert_for_runtime(self, model: torch.nn.Module) -> torch.nn.Module: + replace_linear_int4( + model, + self.groupsize, + self.inner_k_tiles, + self.padding_allowed, + ) + return model + + def quantize( + self, model: torch.nn.Module, *args: Any, **kwargs: Any + ) -> torch.nn.Module: + state_dict = self._create_quantized_state_dict(model) + model = self._convert_for_runtime(model) + # TODO: make it strict + model.load_state_dict(state_dict, strict=False) + return model + +class Int4WeightOnlyGPTQQuantizer(GPTQQuantizer): + def __init__( + self, + blocksize=128, + percdamp=0.01, + groupsize=64, + inner_k_tiles=8, + padding_allowed=True, + device: torch.device = torch.device("cuda"), + ): + self.blocksize = blocksize + self.percdamp = percdamp + self.groupsize = groupsize + self.inner_k_tiles = inner_k_tiles + self.padding_allowed = padding_allowed + self.device = device + self.act_fake_quant_func = None + n_bit = 4 + self.get_qparams_func = lambda w: get_groupwise_affine_qparams( + w, n_bit, groupsize + ) + self.quantize_func = lambda w, qparams: groupwise_affine_quantize_tensor_from_qparams( + w, qparams[0], qparams[1], n_bit, groupsize + ) + self.dequantize_func = lambda q, qparams: groupwise_affine_dequantize_tensor_from_qparams( + q, + qparams[0], + qparams[1], + n_bit, + groupsize, + ) + self.combine_qparams_list_func = lambda qparams_list: [ + torch.cat(x, dim=1) for x in zip(*qparams_list) + ] + # skip unless padding_allowed=True or its correctly sized + self.skip_layer_func = lambda linear_weight: not ( + _check_linear_int4_k(linear_weight.shape[-1], groupsize) or padding_allowed + ) + + # we need to do the padding here, both for q and the qparams if necessary + + # TODO: this is the gpt-fast version, merge with the main version later + def make_names_and_values_dict_func(q, qparams): + k = q.shape[1] + if not _check_linear_int4_k(k, groupsize): + new_k = find_multiple(k, 1024) + else: + new_k = k + # how much we need to pad the weight + delta_k = new_k - q.shape[1] + q = q.to(torch.int32).to(self.device) + final_q = torch.ops.aten._convert_weight_to_int4pack(F.pad(q, pad=(0, delta_k)), inner_k_tiles) + scales = qparams[0].to(torch.bfloat16).to(self.device) + zeros = qparams[1].to(torch.bfloat16).to(self.device) + scales_and_zeros = pack_tinygemm_scales_and_zeros(scales, zeros) + # how many new groups we need for padded weight + delta_groups = new_k // groupsize - scales_and_zeros.shape[0] + final_s_and_z = F.pad(scales_and_zeros, pad=(0,0,0,0,0, delta_groups), value=1) + return {"weight": final_q, "scales_and_zeros": final_s_and_z} + + self.make_names_and_values_dict_func = make_names_and_values_dict_func + super().__init__() + + def _convert_for_runtime(self, model): + replace_linear_int4( + model, + self.groupsize, + self.inner_k_tiles, + self.padding_allowed, + skip_layer_func=self.skip_layer_func, + ) + return model + + def quantize(self, model: torch.nn.Module, inputs: List[_MultiInput], **kwargs: Any) -> torch.nn.Module: + state_dict = self._create_quantized_state_dict( + model, + inputs, + self.blocksize, + self.percdamp, + self.groupsize, + ) + model = self._convert_for_runtime(model) + model.load_state_dict(state_dict, strict=False) + return model + + +from .utils import ( + get_group_qparams_symmetric, + group_quantize_tensor_symmetric, + per_token_dynamic_quant, +) + +def linear_forward_8da4w( + x, + weight_int8, + scales, + zeros, + out_features, + groupsize, + precision, +): + x = per_token_dynamic_quant(x) + # TODO: verify and remove following reshape code + # origin_x_size = x.size() + # x = x.reshape(-1, origin_x_size[-1]) + + # TODO: better API + # weight_int8 = torch.ops.quantized_decomposed.unpack_int4_to_int8(weight_int4packed) + n_bit = 4 + quant_min = -(2 ** (n_bit - 1)) + quant_max = 2 ** (n_bit - 1) - 1 + from torchao._executorch_ops import _quantized_decomposed_dequantize_per_channel_group_wrapper + w_dq = _quantized_decomposed_dequantize_per_channel_group_wrapper( + weight_int8, + scales, + zeros, + quant_min, + quant_max, + torch.int8, + groupsize, + precision, + ) + + # x = x.to(torch.float16) + # w_dq = w_dq.to(torch.float16) + c = torch.nn.functional.linear(x, w_dq) + + # new_shape = origin_x_size[:-1] + (out_features,) + # c = c.reshape(new_shape) + + return c + +class Int8DynActInt4WeightLinear(torch.nn.Module): + __constants__ = ["in_features", "out_features"] + + in_features: int + out_features: int + weight: torch.Tensor + + """ + This module implements a dynamic quantized linear layer with int4 weight. + Weights are per channel groupwise quantized. Parameters of importance + groupsize: the number of elements in each quantized group + precision: precision of input and output. e.g. torch.float32 means input + activation is float32 and output is float32. + scales_precision: precision of per group scale. + """ + + def __init__( + self, + in_features: int, + out_features: int, + bias=True, + device=None, + dtype=None, + groupsize: int = 256, + precision: torch.dtype = torch.float32, + scales_precision: torch.dtype = torch.float32, + ) -> None: + super().__init__() + # always pad if needed since it becomes a noop at runtime if not needed + # self.origin_in_features = in_features + assert ( + in_features % groupsize == 0 + ), f"require in_features:{in_features} % groupsize:{groupsize} == 0" + # in_features = _calc_padded_size_linear_int4( + # in_features, groupsize + # ) + self.in_features = in_features + self.out_features = out_features + assert not bias, "require bias=False" + # TODO: align groupsize naming + self.groupsize = groupsize + # Precision of the activation which also indicates + # output precision of the dynamically quantized linear layer + # that his module represents. + self.precision = precision + + # currently storing unpacked int8 weights + self.register_buffer( + "weight", + torch.empty((out_features, in_features), dtype=torch.int8), + ) + self.register_buffer( + "scales", + torch.empty( + (out_features, in_features // groupsize), + dtype=scales_precision, + ), + ) + self.register_buffer( + "zeros", + torch.empty( + (out_features, in_features // groupsize), + dtype=scales_precision, + ), + ) + + def forward(self, input: torch.Tensor) -> torch.Tensor: + input = input.to(self.precision) + # padding is removed for perf + # input = F.pad(input, pad=(0, self.in_features - self.origin_in_features)) + return linear_forward_8da4w( + input, + self.weight, + self.scales, + self.zeros, + self.out_features, + self.groupsize, + self.precision, + ) + +def _replace_linear_8da4w( + module: torch.nn.Module, + groupsize: int, + padding_allowed: bool, + precision: torch.dtype, + scales_precision: torch.dtype, + linear_class: Type[torch.nn.Module], + copy_weights: bool = False, +): + for name, child in module.named_children(): + if isinstance(child, nn.Linear): + if _check_linear_int4_k(child.in_features, groupsize) or padding_allowed: + new_linear = linear_class( + child.in_features, + child.out_features, + bias=False, + device=child.weight.device, + groupsize=groupsize, + precision=precision, + scales_precision=scales_precision, + ) + # In distributed training, the model may be instantiated + # on the meta device, in which case there is no need to + # copy the weights, and doing so will result in an error + if copy_weights and child.weight.device != torch.device("meta"): + new_linear.weight = child.weight + setattr(module, name, new_linear) + else: + _replace_linear_8da4w( + child, + groupsize, + padding_allowed, + precision, + scales_precision, + linear_class, + copy_weights, + ) + +def replace_linear_8da4w( + module: torch.nn.Module, + groupsize: int, + padding_allowed: bool, + precision: torch.dtype, + scales_precision: torch.dtype, +): + _replace_linear_8da4w( + module, + groupsize, + padding_allowed, + precision, + scales_precision, + Int8DynActInt4WeightLinear, + ) + +class Int8DynActInt4WeightQuantizer(Quantizer): + def __init__( + self, + groupsize: int = 256, + padding_allowed: bool = False, + precision: torch.dtype = torch.float32, + scales_precision: torch.dtype = torch.float32, + ) -> None: + super().__init__() + self.groupsize: int = groupsize + self.padding_allowed: bool = padding_allowed + self.precision: torch.dtype = precision + self.scales_precision: torch.dtype = scales_precision + + @torch.no_grad() + def _create_quantized_state_dict( + self, model: torch.nn.Module + ) -> Dict[str, torch.Tensor]: + cur_state_dict = model.state_dict() + for fqn, mod in model.named_modules(): + if isinstance(mod, torch.nn.Linear): + assert not mod.bias + out_features = mod.out_features + in_features = mod.in_features + # assert out_features % 8 == 0, "require out_features % 8 == 0" + print(f"linear: {fqn}, in={in_features}, out={out_features}") + + assert ( + in_features % self.groupsize == 0 + ), f"require in_features:{in_features} % self.groupsize:{self.groupsize} == 0" + + weight = mod.weight.data + if not _check_linear_int4_k(in_features, self.groupsize): + if self.padding_allowed: + from .utils import find_multiple + import torch.nn.functional as F + print(f"warning: {fqn} is padded to satisfy in_features % 1024 == 0") + padded_in_features = find_multiple(in_features, 1024) + weight = F.pad(weight, pad=(0, padded_in_features - in_features)) + else: + print(f"warning: {fqn} is skipped, int4 requires that in_features is 32, 64, or is divisible by 1024, " + + "and that groupsize and inner_k_tiles*16 evenly divide into it") + continue + ( + weight_int8, + scales, + zeros, + ) = group_quantize_tensor_symmetric( + weight.to(self.precision), + 4, # n_bit + self.groupsize, + self.scales_precision, + ) + cur_state_dict[f"{fqn}.weight"] = weight_int8.to("cpu") + cur_state_dict[f"{fqn}.scales"] = scales.to("cpu") + cur_state_dict[f"{fqn}.zeros"] = zeros.to("cpu") + # TODO: support bias? + + return cur_state_dict + + def _convert_for_runtime(self, model: torch.nn.Module) -> torch.nn.Module: + replace_linear_8da4w( + model, + self.groupsize, + self.padding_allowed, + self.precision, + self.precision, + ) + return model + + def quantize( + self, model: torch.nn.Module, *args: Any, **kwargs: Any + ) -> torch.nn.Module: + state_dict = self._create_quantized_state_dict(model) + model = self._convert_for_runtime(model) + # TODO: make it strict + model.load_state_dict(state_dict, strict=False) + return model + + +class Int8DynActInt4WeightGPTQQuantizer(GPTQQuantizer): + def __init__( + self, + blocksize=128, + percdamp=.01, + groupsize=64, + inner_k_tiles=8, + padding_allowed=True, + precision=torch.float32, + ): + self.blocksize = blocksize + self.percdamp = percdamp + self.groupsize = groupsize + self.inner_k_tiles = inner_k_tiles + self.padding_allowed = padding_allowed + self.precision = precision + + self.act_fake_quant_func = per_token_dynamic_quant + n_bit = 4 + self.get_qparams_func = lambda w: get_group_qparams_symmetric( + w, n_bit, groupsize, self.precision + ) + quant_min = -(2 ** (n_bit - 1)) + quant_max = 2 ** (n_bit - 1) - 1 + + from torchao._executorch_ops import _quantized_decomposed_quantize_per_channel_group_wrapper + self.quantize_func = lambda w, qparams: _quantized_decomposed_quantize_per_channel_group_wrapper( + w, qparams[0], qparams[1], quant_min, quant_max, torch.int8, groupsize + ) + + from torchao._executorch_ops import _quantized_decomposed_dequantize_per_channel_group_wrapper + self.dequantize_func = lambda q, qparams: _quantized_decomposed_dequantize_per_channel_group_wrapper( + q, + qparams[0], + qparams[1], + quant_min, + quant_max, + torch.int8, + groupsize, + self.precision, + ) + + self.combine_qparams_list_func = lambda qparams_list: [ + torch.cat(x, dim=1) for x in zip(*qparams_list) + ] + # skip unless padding_allowed=True or its correctly sized + + self.skip_layer_func = lambda linear_weight: not ( + _check_linear_int4_k(linear_weight.shape[-1], groupsize) or padding_allowed + ) + + # we need to do the padding here, both for q and the qparams if necessary + def make_names_and_values_dict_func(q, qparams): + k = q.shape[1] + new_k = find_multiple(k, 1 if groupsize is None else groupsize) + # how much we need to pad the weight + delta_k = new_k - q.shape[1] + final_q = F.pad(q, pad=(0, delta_k)) + scales = qparams[0].to(self.precision) + zeros = qparams[1].to(self.precision) + return {"weight": final_q, "scales": scales, "zeros": zeros} + + self.make_names_and_values_dict_func = make_names_and_values_dict_func + super().__init__() + + def _convert_for_runtime(self, model): + replace_linear_8da4w( + model, + self.groupsize, + self.padding_allowed, + self.precision, + self.precision, + ) + return model + + def quantize(self, model: torch.nn.Module, inputs: List[_MultiInput], **kwargs: Any) -> torch.nn.Module: + state_dict = self._create_quantized_state_dict( + model, + inputs, + self.blocksize, + self.percdamp, + self.groupsize, + ) + model = self._convert_for_runtime(model) + model.load_state_dict(state_dict, strict=False) + return model diff --git a/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/GPTQ.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/GPTQ.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afce225be9294614f90d2370c34753c81f6dfbd4 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/GPTQ.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/autoquant.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/autoquant.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab4bd832b0d06dcceacdb67dbc68f0008b81170a Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/autoquant.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/dynamic_quant.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/dynamic_quant.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b40f8983add7d471602cbae9f944c3b9743c500 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/dynamic_quant.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/quant_api.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/quant_api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..689fa982527db9c900e83b07a0f0141370a40f6d Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/quant_api.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/quant_primitives.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/quant_primitives.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77bfc51f376e548340a47da07fa8dc2fc0a62336 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/quant_primitives.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/unified.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/unified.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a4783344cc5c19d4d830706a2274d71ac4db085 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/unified.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/weight_only.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/weight_only.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..808d1be4b4655df963ecdce751c179e8f880c303 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torchao/quantization/__pycache__/weight_only.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torchao/quantization/autoquant.py b/videollama2/lib/python3.10/site-packages/torchao/quantization/autoquant.py new file mode 100644 index 0000000000000000000000000000000000000000..18a58cd17fd30d7cf07b4cffcc90cffef42f22e5 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torchao/quantization/autoquant.py @@ -0,0 +1,560 @@ +import torch +from .subclass import ( # noqa + Int8DynamicallyQuantizedLinearWeight, + Int8WeightOnlyQuantizedLinearWeight, + QuantizedLinearWeightBase, +) +from torch.utils._python_dispatch import return_and_correct_aliasing +from .quant_primitives import ( + safe_int_mm, +) +from torchao.utils import TORCH_VERSION_AFTER_2_4 +from torchao.quantization.utils import quantize_activation_per_token_absmax + +import torch.nn.functional as F +try: + from torch._inductor.utils import do_bench +except: + from torch._inductor.runtime.runtime_utils import do_bench + +__all__ = [ + "AutoQuantizableLinearWeight", + "autoquant", +] + + +aten = torch.ops.aten + +AUTOQUANT_CACHE = {} + +def check_cache(cls, shapes_and_dtype): + return AUTOQUANT_CACHE.get((cls,)+shapes_and_dtype, None) + +def update_cache(cls, shapes_and_dtype, res): + AUTOQUANT_CACHE[(cls,)+shapes_and_dtype] = res + +# TODO: Document the methods +class AutoQuantizableLinearWeight(torch.Tensor): + """ + A subclass of torch.Tensor that, when run, finds the best type of quantization for itself and swaps + its data with the quantized version. + + Args: + weight (torch.Tensor): The initial weight tensor. + qtensor_class_list (list): A list of tensor classes to be considered for quantization. + *args: Additional positional arguments. + mode (list, optional): A list containing mode settings for quantization. The first element is the mode type + (e.g., "relu"), and the second element is the mode value (e.g., None). Defaults to ["relu", None]. + **kwargs: Additional keyword arguments. + """ + + @staticmethod + def __new__(cls, weight, qtensor_class_list, *args, mode=["relu", None], **kwargs): + kwargs["device"] = weight.device + kwargs["layout"] = ( + kwargs.get("layout") if kwargs.get("layout", False) else weight.layout + ) + kwargs["dtype"] = ( + kwargs.get("dtype") if kwargs.get("dtype", False) else weight.dtype + ) + kwargs["requires_grad"] = False + shape = kwargs.pop("shape", weight.shape) + return torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs) # type: ignore[attr-defined] + + def __init__(self, weight, qtensor_class_list, *args, mode=["relu", None], **kwargs): + self.weight = weight + self.qtensor_class_list = qtensor_class_list + self.logged_data = {} + self.mode = mode + + def __repr__(self): + return ( + f"{self.__class__.__name__}(data={self.weight}, shape={self.shape}, " + f"device={self.device}, dtype={self.dtype}, qtensor_class_list={self.qtensor_class_list})" + ) + + @staticmethod + def log_shape(act_mat, w_autoquant, bias): + act_mat = act_mat.reshape(-1, act_mat.shape[-1]) + logged_dtype = act_mat.dtype + logged_shapes = (act_mat.shape, w_autoquant.shape, None if bias is None else bias.shape,) + shapes_and_dtype = logged_shapes + (logged_dtype,) + w_autoquant.logged_data[shapes_and_dtype] = 1 + w_autoquant.logged_data.get(shapes_and_dtype, 0) + for q_cls in w_autoquant.qtensor_class_list: + if check_cache(q_cls, shapes_and_dtype) is None: + update_cache(q_cls, shapes_and_dtype, None) + + def tune_autoquant(self, q_cls, shapes_and_dtype, best_time): + act_shape, w_shape, bias_shape, act_dtype = shapes_and_dtype + if check_cache(q_cls, shapes_and_dtype) is None: + with torch.no_grad(): + act_mat = torch.randn(act_shape, dtype=act_dtype, device=self.device) + bias = None if bias_shape is None else torch.randn(bias_shape, dtype=act_dtype, device=self.device) + res = q_cls._autoquant_test(act_mat, self.weight, bias, best_time, self.mode) + update_cache(q_cls, shapes_and_dtype, res) + + @torch.no_grad() + def to_quantized(self, error_on_unseen, **kwargs): + if error_on_unseen and self.logged_data == {}: + raise RuntimeError("must run module normally to get shape, dtype info for autoquant") + elif (self.logged_data == {}) and not error_on_unseen: + # default back to non-quantized weight if not seen + self = AQFloatLinearWeight.from_float(self.weight) + return self + + + # only want to print shape (at start) and final result (at end) + # once per shape+quantization subclass combination. + ran_new_benchmarks = False + print_shape_once = True + + def count_shapes(self, do_print=True): + differe_shape_count=0 + for shapes_and_dtype, times_seen in self.logged_data.items(): + differe_shape_count += 1 + if do_print: + act_shape, weight_shape, bias_shape, dtype = shapes_and_dtype + print(f"activation_shapes: {act_shape}, times_seen: {times_seen}") + if do_print: + print(f"weight_shape: {weight_shape}, dtype: {dtype}, bias_shape: {bias_shape}") + return differe_shape_count + + # check each class + best_time = torch.inf + best_cls = None + for q_cls in self.qtensor_class_list: + # for each logged shape+dtype, benchmark + cur_time=0 + total_seen=0 + shape_count = count_shapes(self, do_print=False) + for shapes_and_dtype, times_seen in self.logged_data.items(): + if check_cache(q_cls, shapes_and_dtype) is None: + # only print shapes once + if print_shape_once == True: + print_shape_once = False + count_shapes(self, do_print=True) + + time_for_best_shape = check_cache(best_cls, shapes_and_dtype) + time_for_best_shape = torch.inf if time_for_best_shape is None else time_for_best_shape + self.tune_autoquant(q_cls, shapes_and_dtype, time_for_best_shape) + ran_new_benchmarks=True + torch._dynamo.reset() + cur_time += check_cache(q_cls, shapes_and_dtype) * times_seen + total_seen += times_seen + cur_time = cur_time / total_seen + # print aggregated time if there were multiple shapes to aggregate and some new benchmarking was done + if shape_count is not None and shape_count > 1 and ran_new_benchmarks: + print(f">time (all shapes): {cur_time:0.4f}ms for {q_cls}, prev_best: {best_time:0.4f}ms") + if best_time >= cur_time: + best_time = cur_time + best_cls = q_cls + # if no new benchmarking was done, don't print the final result, it will be the same as for another layer + if ran_new_benchmarks: + print(f"best_cls={best_cls}\n") + # TODO handle random cls args/kwargs? or should they be curried? + self = best_cls.from_float(self.weight) + return self + + def _apply_fn_to_data(self, fn): + return self.__class__( + fn(self.weight), self.qtensor_class_list, dtype=self.dtype, mode=self.mode + ) + + def __tensor_flatten__(self): + return ["weight"], [self.qtensor_class_list, self.mode, self.dtype, self.shape] + + @classmethod + def __tensor_unflatten__(cls, tensor_data_dict, tensor_attributes, outer_size=None, outer_stride=None): + weight = tensor_data_dict["weight"] + qtensor_class_list, mode, dtype, shape = tensor_attributes[0] + return cls(weight, qtensor_class_list, mode, shape=shape if outer_size is None else outer_size, dtype=dtype, strides=outer_stride) + + @classmethod + def from_float(cls, weight, qtensor_class_list, **kwargs): + return cls(weight, qtensor_class_list, **kwargs) + + @classmethod + def __torch_function__(cls, func, types, args=(), kwargs=None): + kwargs = {} if kwargs is None else kwargs + + if func is torch.nn.functional.linear: + mat1, w_autoquant, bias = ( + args[0], + args[1], + args[2] if len(args)>2 else None + ) + cls.log_shape(mat1, w_autoquant, bias) + return func(mat1, w_autoquant.weight, bias) + try: + with torch._C.DisableTorchFunctionSubclass(): + return func(*args, **kwargs) + except: + print(f"ERR: subclass doesn't implement {func}") + + @classmethod + def __torch_dispatch__(cls, func, types, args, kwargs): + if func is aten.detach.default: + return return_and_correct_aliasing(func, args, kwargs, args[0]._apply_fn_to_data(torch.detach)) + +@torch.no_grad() +def do_autoquant_bench(op, *args, **kwargs): + """ + runs benchmark op(*args, **kwargs) avoiding torch.compile overhead + """ + rep = kwargs.pop("rep", 100) + warmup = kwargs.pop("warmup", 25) + with torch.no_grad(): + torch.cuda.synchronize() + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + op(*args, **kwargs) + stream.synchronize() + torch.cuda.current_stream().wait_stream(stream) + torch.cuda.synchronize() + + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + op(*args, **kwargs) + if TORCH_VERSION_AFTER_2_4: + from torch._inductor.runtime.runtime_utils import do_bench_gpu + res = do_bench_gpu(lambda: graph.replay(), warmup=warmup, rep=rep, return_mode="median") + else: + res = do_bench(lambda: graph.replay(), warmup=warmup, rep=rep, return_mode="median") + return res + +def _is_interpolate_mode(mode): + if isinstance(mode, list) and mode[0]=="interpolate" and len(mode)==2 and isinstance(mode[1], float): + return True + return False + +class AQMixin(): + """ + Tests and benchmarks the autoquantization process for the given activation matrix, weight, and bias. + + Args: + act_mat (torch.Tensor): The activation matrix. + weight (torch.Tensor): The weight tensor. + bias (torch.Tensor or None): The bias tensor. + best_time (float): The best time to beat for the quantization process. + mode (list, optional): A list containing mode settings for quantization. The first element is the mode type + (e.g., "relu"), and the second element is the mode value (e.g., None). Defaults to ["relu", None]. + + Returns: + float: The benchmarked time for the autoquantization process. + """ + @classmethod + def _autoquant_test(cls, act_mat, weight, bias, best_time, mode=["relu", None]): + w_qtensor = cls.from_float(weight) + if _is_interpolate_mode(mode): + q_c_op = torch.compile(cls._quantized_op, mode="max-autotune-no-cudagraphs") + else: + func = lambda a,b,c: F.relu(cls._quantized_op(F.relu(a), b, c)) + q_c_op = torch.compile(func, mode="max-autotune-no-cudagraphs") + res = do_autoquant_bench(q_c_op, act_mat, w_qtensor, bias, warmup=25, rep=100) + if res < best_time*1.1: + res2 = do_autoquant_bench(q_c_op, act_mat, w_qtensor, bias, warmup=25, rep=900) + res=(res2*.9+res*.1) + print(f">>time: {res:0.3f}ms for {cls}, to_beat: {best_time:0.3f}ms ") + return res + +class AQInt8DynamicallyQuantizedLinearWeight(AQMixin, Int8DynamicallyQuantizedLinearWeight): + """ + AutoQuantizable version of Int8DynamicallyQuantizedLinearWeight + """ + @classmethod + def _autoquant_test(cls, act_mat, weight, bias, best_time, mode=["relu", None]): + """ + Tests and benchmarks the autoquantization process with special handling for interpolate mode. + + Args: + act_mat (torch.Tensor): The activation matrix. + weight (torch.Tensor): The weight tensor. + bias (torch.Tensor or None): The bias tensor. + best_time (float): The best time to beat for the quantization process. + mode (list, optional): A list containing mode settings for quantization. The first element is the mode type + (e.g., "relu"), and the second element is the mode value (e.g., None). Defaults to ["relu", None]. + + Returns: + float: The benchmarked time for the autoquantization process. + """ + if not _is_interpolate_mode(mode): + return super()._autoquant_test(act_mat, weight, bias, best_time, mode) + + # SAM best is between .8 and 1, SDXL also performs best in this range + INTERPOLATION_CONSTANT = mode[1] + w_qtensor = cls.from_float(weight) + x_vals_int8, x_scales = quantize_activation_per_token_absmax( + act_mat.reshape(-1, act_mat.shape[-1]) + ) + quantized_matmul = ( + lambda x_vals_int8, x_scales, w_vals_int8: + safe_int_mm(x_vals_int8, w_vals_int8) * x_scales + ) + q_c_matmul=torch.compile(quantized_matmul, mode="max-autotune-no-cudagraphs") + with torch.no_grad(): + res_matmul = do_autoquant_bench(q_c_matmul, x_vals_int8, x_scales.reshape(-1,1), w_qtensor.int_data) + print(f">>time: {res_matmul:0.3f}ms for {cls} matmul, to_beat: {best_time:0.3f}ms") + + # if the (much faster) matmul kernel is already beat, don't bother benchmarking full op + if res_matmul>=best_time: + return res_matmul + + # calculate what time full op needs to beat for dynamic quant to be best given INTERPOLATION_CONSTANT + to_beat = best_time + INTERPOLATION_CONSTANT/(1-INTERPOLATION_CONSTANT)*(best_time-res_matmul) + res = super()._autoquant_test(act_mat, weight, bias, to_beat) + max_int_const_win = (best_time-res_matmul)/(res-res_matmul) + res_f = INTERPOLATION_CONSTANT*res+(1-INTERPOLATION_CONSTANT)*res_matmul + print(f">>time: {res_f:0.3f}ms for {cls} interpolated, breakeven constant: {max_int_const_win:0.2f}") + return res_f + +class AQWeightOnlyQuantizedLinearWeight(Int8WeightOnlyQuantizedLinearWeight, AQMixin): + """ + AutoQuantizable version of Int8WeightOnlyQuantizedLinearWeight + """ + +class AQWeightOnlyQuantizedLinearWeight2(Int8WeightOnlyQuantizedLinearWeight, AQMixin): + """ + AutoQuantizable version of Int8WeightOnlyQuantizedLinearWeight that + uses a different kernel + """ + @staticmethod + def _quantized_op(act_mat, w_qtensor, bias): + """ + Performs the quantized linear operations + + Args: + act_mat (torch.Tensor): The activation matrix. + w_qtensor (torch.Tensor): The quantized weight tensor. + bias (torch.Tensor or None): The bias tensor. + + Returns: + torch.Tensor: The result of the quantized operation. + """ + orig_dtype = act_mat.dtype + orig_shape = act_mat.shape + act_mat = act_mat.reshape(-1, act_mat.shape[-1], 1) + y = (act_mat*w_qtensor.int_data.unsqueeze(0)).sum(dim=-2) + y = y.reshape(*orig_shape[:-1], y.shape[-1]) * w_qtensor.q_scales + if bias is not None: + y += bias + return y.to(orig_dtype) + + @classmethod + def _autoquant_test(cls, act_mat, *args): + # if act_mat has batchsize>2 don't use this kernel + if act_mat.reshape(-1, act_mat.shape[-1]).shape[0]>32: + return torch.inf + return super()._autoquant_test(act_mat, *args) + +class AQWeightOnlyQuantizedLinearWeight3(Int8WeightOnlyQuantizedLinearWeight, AQMixin): + """ + AutoQuantizable version of Int8WeightOnlyQuantizedLinearWeight that + uses a different kernel + """ + def _quantized_op(act_mat, w_qtensor, bias): + orig_shape = act_mat.shape + y = torch.mm(act_mat.reshape(-1, orig_shape[-1]), w_qtensor.int_data*w_qtensor.q_scales) + y=y.reshape(*orig_shape[:-1], y.shape[-1]) + if bias is not None: + y += bias + return y + +class AQFloatLinearWeight(torch.Tensor, AQMixin): + """ + A class to be used in concert with AutoQuantizableLinearWeight to provide a + default/non-quantized option. Only implements the bare minimum needed to work with the + AutoQuantizableLinearWeight class using the same interfaces that would normally be + used by QTensor subclasses but for a default linear op instead. Result of from_float + is not a tensor subclass, but rather the float tensor. + """ + def __init__(self): + super().__init__() + + @staticmethod + def _quantized_op(act_mat, w_qtensor, bias): + return torch.nn.functional.linear(act_mat, w_qtensor, bias) + + @classmethod + def from_float(cls, weight): + return weight + +DEFAULT_CLASS_LIST = [ + AQFloatLinearWeight, + AQWeightOnlyQuantizedLinearWeight, + AQWeightOnlyQuantizedLinearWeight2, + # AQWeightOnlyQuantizedLinearWeight3, + # TODO this gets picked in places where it makes perf worse, why? + AQInt8DynamicallyQuantizedLinearWeight, +] + +def _change_linears_to_autoquantizable(model, **kwargs): + """ + Converts all linear weight tensors to the + AutoQuantizableLinearWeight tensor subclass. Expectation is that this is followed + by running the model and then calling _change_autoquantizable_to_quantized + """ + from torchao.quantization.quant_api import _is_linear + filter_fn = kwargs.pop("filter_fn", _is_linear) + _ = kwargs.pop("error_on_unseen", True) # same kwargs used for this and to_quantized + kwargs["qtensor_class_list"] = kwargs.get("qtensor_class_list", DEFAULT_CLASS_LIST) + kwargs["mode"] = kwargs.get("mode", ["relu", None]) + from torchao.quantization.quant_api import _replace_with_custom_fn_if_matches_filter + from torchao.quantization.quant_api import _get_subclass_inserter + _replace_with_custom_fn_if_matches_filter( + model, + _get_subclass_inserter(AutoQuantizableLinearWeight, **kwargs), + filter_fn if filter_fn is not None else _is_linear, + ) + +def _change_autoquantizable_to_quantized(model, **kwargs): + """ + Converts AutoQuantizableLinearWeight tensor subclasses + to various quantized/non-quantized tensor subclasses depending + on benchmark results. Expectation is that these modules are + torch.compiled afterwards. + """ + hold = torch._dynamo.config.automatic_dynamic_shapes + torch._dynamo.config.automatic_dynamic_shapes = False + + filter_fn = kwargs.pop( + "filter_fn", + lambda mod, *args: + hasattr(mod, "weight") and isinstance(mod.weight, AutoQuantizableLinearWeight) + ) + error_on_unseen=kwargs.pop("error_on_unseen", True) + from torchao.quantization.quant_api import _replace_with_custom_fn_if_matches_filter + from torchao.quantization.quant_api import _get_subclass_inserter + _replace_with_custom_fn_if_matches_filter( + model, + _get_subclass_inserter( + AutoQuantizableLinearWeight, method="to_quantized", error_on_unseen=error_on_unseen, **kwargs + ), + filter_fn, + ) + torch._dynamo.config.automatic_dynamic_shapes = hold + torch._dynamo.reset() + +# TODO: example_input seems weird to include in the API +# TODO: Document all the modes +# TODO: Mode being a list is weird, should be a string or some object +@torch.no_grad() +def autoquant( + model, + example_input=None, + qtensor_class_list=DEFAULT_CLASS_LIST, + filter_fn=None, mode=["interpolate", .85], + manual=False, + **aq_kwargs +): + """ + Autoquantization is a process which identifies the fastest way to quantize each layer of a model over some set of potential + qtensor subclasses. + + Autoquantization happens in three steps: + + 1-Prepare Model: the model is searched for Linear layers whose weights are exchanged for AutoQuantizableLinearWeight. + 2-Shape Calibration: the user runs the model on one or more inputs, the details of the activation shape/dtype seen by + the AutoQuantizableLinearWeight are recorded so we know what shapes/dtypes to use in order to optimize the quantized op in step 3 + 3-Finalize Autoquantization: for each AutoQuantizableLinearWeight, benchmarks are run for each shape/dtype on each member of the qtensor_class_list. + the fastest option is picked, resulting in a highly performant model + + This autoquant function performs step 1. Steps 2 and 3 can be completed by simply running the model. + If `example_input` is provided, this function also runs the model (which completes steps 2 and 3). + This autoquant api can handle models which have already had torch.compile applied to them, in which case, once the model is run and quantized, + the torch.compile process normally proceeds as well. + + To optimize over a combination of input shapes/dtypes, the user can set manual=True, run the model with all desired shapes/dtypes, then + call model.finalize_autoquant to finalize the quantization once the desired set of inputs have been logged. + + Args: + model (torch.nn.Module): The model to be autoquantized. + example_input (Any, optional): An example input for the model. If provided, the function performs a forward pass + on this input (which fully autoquantizes the model unless manual=True). Defaults to None. + qtensor_class_list (list, optional): A list of tensor classes to be used for quantization. Defaults to DEFAULT_CLASS_LIST. + filter_fn (callable, optional): A filter function to apply to the model parameters. Defaults to None. + mode (list, optional): A list containing mode settings for quantization. The first element is the mode type (e.g., "interpolate"), + and the second element is the mode value (e.g., 0.85). Defaults to ["interpolate", .85]. + manual (bool, optional): Whether to stop shape calibration and do autoquant after a single run (default, False) or to wait for + the user to call model.finalize_autoquant (True) so inputs with several shapes/dtypes can be logged. + **aq_kwargs: Additional keyword arguments for the autoquantization process. + + Returns: + torch.nn.Module: The autoquantized and wrapped model. If `example_input` is provided, the function performs a forward pass + on the input and returns the result of the forward pass. + + Example usage: + torchao.autoquant(torch.compile(model)) + model(*example_input) + + # multiple input shapes + torchao.autoquant(model, manual=True) + model(*example_input1) + model(*example_input2) + model.finalize_autoquant() + """ + + # perform initial swap from linear weights + # to AutoQuantizableLinearWeight + _change_linears_to_autoquantizable( + model, + filter_fn=filter_fn, + qtensor_class_list=qtensor_class_list, + mode=mode, + **aq_kwargs + ) + + # access actual model of torch.compile wrapper if needed + is_compiled = isinstance(model, torch._dynamo.eval_frame.OptimizedModule) + if is_compiled: + real_model = model._orig_mod + else: + real_model = model + + if manual: + # we don't want model.forward to trigger + # torch.compilation + if is_compiled: + real_model.old_forward = model.forward + model.forward = real_model.forward + + # we want to automatically do autoquant after a single model run + # and have it occur before torch.compilation if applicable + else: + # the hook we will use to intercept the model forward and perform + # autoquantization + def autoquant_prehook(module, args, kwargs): + real_model.forward(*args, **kwargs) + module.finalize_autoquant() + return args, kwargs + + # the autoquant_prehook intercepts the forward call, performs logging then + # does autoquantization. if model is a torch.compile wrapper, it then + # does the tracing/compile since the prehook is naturally followed by the normal. + # model run. + handle = model.register_forward_pre_hook(autoquant_prehook, with_kwargs=True) + + # note the torch.compile wrapper (eval_frame) moves the assignment of any assigned + # attributes to the inner model that didn't exist before, so we have to call delattr on the inner model + def finalize_autoquant(): + _change_autoquantizable_to_quantized( + real_model, + **aq_kwargs, + ) + if hasattr(real_model, "old_forward"): + model.forward = real_model.old_forward + delattr(real_model, "old_forward") + if hasattr(real_model, "finalize_autoquant"): + delattr(real_model, "finalize_autoquant") + if not manual: + handle.remove() + + real_model.finalize_autoquant = finalize_autoquant + + # if example input was provided, check it and run it + if isinstance(example_input, torch.Tensor): + example_input = [example_input] + if isinstance(example_input, (tuple, list)): + model(*example_input) + + return model diff --git a/videollama2/lib/python3.10/site-packages/torchao/quantization/dynamic_quant.py b/videollama2/lib/python3.10/site-packages/torchao/quantization/dynamic_quant.py new file mode 100644 index 0000000000000000000000000000000000000000..61c6b0dc075a28807e837831aa204b3da6a4d466 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torchao/quantization/dynamic_quant.py @@ -0,0 +1,85 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn + +from .utils import ( + dynamically_quantize_per_channel, + quant_int8_dynamic_per_token_linear, +) + +__all__ = ["DynamicallyPerAxisQuantizedLinear"] + + +class DynamicallyPerAxisQuantizedLinear(torch.nn.Linear): + """ + This class is a replacement for `torch.nn.Linear`. It implements a + quantized matmul using int8 dynamic symmetric per-token activation, + and int8 symmetric per-channel weight quantization + """ + + def __init__( + self, + in_features: int, + out_features: int, + bias: bool = True, + ) -> None: + super().__init__(in_features, out_features, bias) + + def forward(self, X: torch.Tensor, *args, **kwargs) -> torch.Tensor: + """ + Performs the forward pass of the quantized linear layer which consists + of int8 dynamic symmetric per-token activation and int8 symmetric per-channel weight + quantization + + Args: + X (torch.Tensor): The input floating point tensor to the quantized linear layer. + + Returns: + torch.Tensor: The output floating point tensor after the quantized matmul and rescale. + + """ + + Y = quant_int8_dynamic_per_token_linear( + X, self.W_int_repr_t, self.W_scales, self.bias, X.dtype + ) + return Y + + @classmethod + def from_float(cls, mod: torch.nn.Linear) -> "DynamicallyPerAxisQuantizedLinear": + """ + Converts a `mod` of class `torch.nn.Linear` to the + `DynamicallyPerAxisQuantizedLinear` class + + Args: + mod (torch.nn.Linear): The original `torch.nn.Linear` module to convert. + + Returns: + DynamicallyPerAxisQuantizedLinear: The converted quantized linear module. + + """ + + # create the new module with a toy size to ensure initialization is fast + fake_in_features, fake_out_features = 8, 8 + new_mod = cls( + fake_in_features, + fake_out_features, + bias=mod.bias is not None, + ) + new_mod.in_features = mod.in_features + new_mod.out_features = mod.out_features + W_int_repr, W_scales, _W_zps = dynamically_quantize_per_channel( + mod.weight, -128, 127, torch.int8 + ) + new_mod.register_buffer("W_int_repr_t", W_int_repr.contiguous().t()) + new_mod.W_scales = nn.Parameter(W_scales) + new_mod.bias = mod.bias + del new_mod.weight + + device_to_use = next(mod.parameters()).device + new_mod.to(device_to_use) + return new_mod diff --git a/videollama2/lib/python3.10/site-packages/torchao/quantization/prototype/__init__.py b/videollama2/lib/python3.10/site-packages/torchao/quantization/prototype/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videollama2/lib/python3.10/site-packages/torchao/quantization/prototype/__pycache__/__init__.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torchao/quantization/prototype/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62b6d437021cc3ce6745a7d0f6c9cc05b2c9391e Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torchao/quantization/prototype/__pycache__/__init__.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torchao/quantization/prototype/__pycache__/qat.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torchao/quantization/prototype/__pycache__/qat.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ade69773bdc8a908536374a1bb4406ed19d2e72 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torchao/quantization/prototype/__pycache__/qat.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torchao/quantization/prototype/qat.py b/videollama2/lib/python3.10/site-packages/torchao/quantization/prototype/qat.py new file mode 100644 index 0000000000000000000000000000000000000000..71b585b15e0922339f161ef08841f74ae5e2bf0f --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torchao/quantization/prototype/qat.py @@ -0,0 +1,323 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Any, Tuple + +import torch +from torch.ao.quantization.fx._decomposed import quantized_decomposed_lib +from torch.library import impl + +from torchao.quantization.utils import get_group_qparams_symmetric +from torchao.quantization.unified import TwoStepQuantizer + +from torchao.quantization.GPTQ import ( + _replace_linear_8da4w, + Int8DynActInt4WeightLinear, +) + + +class Int8DynActInt4WeightQATQuantizer(TwoStepQuantizer): + """ + Quantizer for performing QAT on a model, where linear layers have int8 + dynamic per token fake quantized activations and int4 fake quantized + grouped per channel weights. + """ + + def __init__( + self, + groupsize: int = 256, + padding_allowed: bool = False, + precision: torch.dtype = torch.float32, + scales_precision: torch.dtype = torch.float32, + ) -> None: + super().__init__() + self.groupsize: int = groupsize + self.padding_allowed: bool = padding_allowed + self.precision: torch.dtype = precision + self.scales_precision: torch.dtype = scales_precision + + def prepare( + self, + model: torch.nn.Module, + *args: Any, + **kwargs: Any + ) -> torch.nn.Module: + _replace_linear_8da4w( + model, + self.groupsize, + self.padding_allowed, + self.precision, + self.scales_precision, + Int8DynActInt4WeightQATLinear, + copy_weights=True, + ) + return model + + def convert( + self, + model: torch.nn.Module, + *args: Any, + **kwargs: Any + ) -> torch.nn.Module: + _convert_qat_linear_8da4w(model) + return model + +def _convert_qat_linear_8da4w(module: torch.nn.Module): + """ + Replace all `Int8DynActInt4WeightQATLinear` with `Int8DynActInt4WeightLinear`. + """ + for name, child in module.named_children(): + if isinstance(child, Int8DynActInt4WeightQATLinear): + quantized_linear = Int8DynActInt4WeightLinear( + child.in_features, + child.out_features, + bias=False, + groupsize=child.groupsize, + precision=child.precision, + scales_precision=child.scales_precision, + ) + setattr(module, name, quantized_linear) + + # Load weights and qparams into quantized linear + n_bit = 4 + (qmin, qmax) = child._get_qmin_qmax(n_bit) + (s, zp) = get_group_qparams_symmetric(child.weight, n_bit, child.groupsize) + from torchao._executorch_ops import _quantized_decomposed_quantize_per_channel_group_wrapper + q_weight = _quantized_decomposed_quantize_per_channel_group_wrapper( + child.weight, s, zp, qmin, qmax, torch.int8, child.groupsize, + ) + quantized_linear.weight = q_weight + quantized_linear.scales = s + quantized_linear.zeros = zp + else: + _convert_qat_linear_8da4w(child) + +class Int8DynActInt4WeightQATLinear(torch.nn.Linear): + """ + This module implements a linear layer with int8 dynamic per token fake + quantized activations with int4 fake quantized grouped per channel weights. + + args: + groupsize: the number of elements in each quantized group for weights + precision: precision of weights + scales_precision: precision of per group scales and zero points + """ + + def __init__( + self, + in_features: int, + out_features: int, + bias: bool = False, + device: torch.device = None, + groupsize: int = 256, + precision: torch.dtype = torch.float32, + scales_precision: torch.dtype = torch.float32, + ) -> None: + super().__init__( + in_features, + out_features, + bias, + device=device, + dtype=precision, + ) + assert ( + in_features % groupsize == 0 + ), f"require in_features:{in_features} % groupsize:{groupsize} == 0" + assert not bias, "require bias=False" + self.groupsize = groupsize + self.precision = precision + self.scales_precision = scales_precision + # TODO: make this configurable? + self.zero_points_precision = torch.int32 + self._fake_quant_enabled = True + + def enable_fake_quant(self, enabled: bool = True): + self._fake_quant_enabled = enabled + + def disable_fake_quant(self): + self.enable_fake_quant(False) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + # activations: int8 dynamic asymmetric quant + if self._fake_quant_enabled: + (act_scales, act_zp) = _choose_qparams_per_token_asymmetric( + x, self.scales_precision, self.zero_points_precision, + ) + (act_qmin, act_qmax) = self._get_qmin_qmax(8) + x_fq = fake_quantize_per_token( + x, act_scales, act_zp, act_qmin, act_qmax, + ) + else: + x_fq = x + + # weights: int4 grouped per channel symmetric quant + if self._fake_quant_enabled: + (weight_scales, weight_zp) = get_group_qparams_symmetric( + self.weight, 4, self.groupsize, self.scales_precision, + ) + # TODO: pass zp dtype to `get_group_qparams_symmetric` instead + weight_zp = weight_zp.to(self.zero_points_precision) + (weight_qmin, weight_qmax) = self._get_qmin_qmax(4) + w_fq = fake_quantize_per_channel_group( + self.weight, + weight_scales, + weight_zp, + weight_qmin, + weight_qmax, + self.groupsize, + ) + else: + w_fq = self.weight + return torch.nn.functional.linear(x_fq, w_fq) + + # TODO: move this to common util + def _get_qmin_qmax(self, n_bit: int): + qmin = -(2 ** (n_bit - 1)) + qmax = 2 ** (n_bit - 1) - 1 + return (qmin, qmax) + +def enable_8da4w_fake_quant(mod: torch.nn.Module): + """ + Enable fake quantization for `Int8DynActInt4WeightQATLinear`. + """ + if isinstance(mod, Int8DynActInt4WeightQATLinear): + mod.enable_fake_quant() + +def disable_8da4w_fake_quant(mod: torch.nn.Module): + """ + Disable fake quantization for `Int8DynActInt4WeightQATLinear`. + """ + if isinstance(mod, Int8DynActInt4WeightQATLinear): + mod.disable_fake_quant() + +# ======================== +# | QUANT PRIMITIVES | +# ======================== + +class _GenericFakeQuantize(torch.autograd.Function): + """ + Implementation of generic fake quantize with backward STE. + + With the appropriate input tensor shape, this can be used to express + grouped per channel fake quantize or per token fake quantize. + """ + + @staticmethod + def forward(ctx, input, scales, zero_points, quant_min, quant_max): + # Note: for bf16 inputs, casting them to fp32 has the unexpected + # side effect of reducing memory footprint significantly, presumably + # because bf16 * fp32 kernels are not as memory efficient + assert input.dtype == torch.float32 + assert scales.dtype == torch.float32 + assert zero_points.dtype == torch.int32 + q = input.mul(1.0 / scales).round().add(zero_points) + dq = q.clamp(quant_min, quant_max).sub(zero_points).mul(scales) + mask = torch.logical_and((q >= quant_min), (q <= quant_max)) + ctx.save_for_backward(mask) + return dq + + @staticmethod + def backward(ctx, gy): + (mask,) = ctx.saved_tensors + return gy * mask, None, None, None, None, None + +# TODO: move this to core +quantized_decomposed_lib.define( + "fake_quantize_per_channel_group(Tensor input, Tensor scales, Tensor zero_points, " + "int quant_min, int quant_max, int group_size) -> Tensor" +) + +@impl(quantized_decomposed_lib, "fake_quantize_per_channel_group", "CompositeImplicitAutograd") +def fake_quantize_per_channel_group( + input: torch.Tensor, + scales: torch.Tensor, + zero_points: torch.Tensor, + quant_min: int, + quant_max: int, + group_size: int, +) -> torch.Tensor: + assert group_size > 1 + assert input.shape[-1] % group_size == 0 + assert input.dim() == 2 + grouped_input = input.reshape(-1, group_size).to(torch.float32) + scales = scales.reshape(-1, 1) + zero_points = zero_points.reshape(-1, 1) + fq = _GenericFakeQuantize.apply( + grouped_input, scales, zero_points, quant_min, quant_max, + ) + return fq.reshape_as(input).to(input.dtype) + +# TODO: move this to core +quantized_decomposed_lib.define( + "fake_quantize_per_token(Tensor input, Tensor scales, Tensor zero_points, " + "int quant_min, int quant_max) -> Tensor" +) + +@impl(quantized_decomposed_lib, "fake_quantize_per_token", "CompositeImplicitAutograd") +def fake_quantize_per_token( + input: torch.Tensor, + scales: torch.Tensor, + zero_points: torch.Tensor, + quant_min: int, + quant_max: int, +) -> torch.Tensor: + # TODO: we won't need this import anymore once we move this to core + from torch.ao.quantization.fx._decomposed import _per_token_quant_qparam_dim_check + + _per_token_quant_qparam_dim_check(input, scales, zero_points) + fq_input = input.to(torch.float32) + fq = _GenericFakeQuantize.apply( + fq_input, scales, zero_points, quant_min, quant_max, + ) + return fq.reshape_as(input).to(input.dtype) + +# TODO: This is copied from torch/ao/quantization/fx/_decomposed.py. +# The version in pytorch does not have backward support yet so we add +# it here for now until https://github.com/pytorch/pytorch/pull/123452 +# is landed. +def _choose_qparams_per_token_asymmetric( + input: torch.Tensor, + scales_precision: torch.dtype = torch.float32, + zero_points_precision: torch.dtype = torch.float32, +) -> Tuple[torch.Tensor, torch.Tensor]: + """Choose quantization parameters for per token quantization. This means for a N dimension Tensor + (M1, M2, ...Mn, N), we calculate scales/zero_points for each N elements and quantize + every N elements with the same quantization parameter. The dimension for scales/zero_points + will be (M1 * M2 ... * Mn) + + Args: + input (torch.Tensor): original float32/float16 Tensor + scales_precision (torch.dtype): precision of returned scales + zero_points_precision (torch.dtype): precision of returned zero points + + Returns: + scales and zero_points, both float32 Tensors + """ + # Based on https://github.com/google/XNNPACK/blob/df156f0cf3db5a4576cc711123eeb54915f82ffc/src/xnnpack/quantization.h#L18 + qmin, qmax = -128, 127 + min_val = torch.amin(input, dim=-1, keepdim=True) + max_val = torch.amax(input, dim=-1, keepdim=True) + min_val_neg = torch.min(min_val, torch.zeros_like(min_val)) + max_val_pos = torch.max(max_val, torch.zeros_like(max_val)) + eps = torch.finfo(torch.float32).eps # use xnnpack eps? + + # scale + scale = (max_val_pos - min_val_neg) / float(qmax - qmin) + scale = scale.clamp(min=eps) + + # zero point + descaled_min = min_val_neg / scale + descaled_max = max_val_pos / scale + zero_point_from_min_error = qmin + descaled_min + zero_point_from_max_error = qmax + descaled_max + zero_point = torch.where( + zero_point_from_min_error + zero_point_from_max_error > 0, + qmin - descaled_min, + qmax - descaled_max, + ) + zero_point = torch.clamp(zero_point, qmin, qmax).round() + + return scale.to(scales_precision), zero_point.to(zero_points_precision) diff --git a/videollama2/lib/python3.10/site-packages/torchao/quantization/quant_api.py b/videollama2/lib/python3.10/site-packages/torchao/quantization/quant_api.py new file mode 100644 index 0000000000000000000000000000000000000000..6f7f5497045b80d8b370395cddec0c077411b60b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torchao/quantization/quant_api.py @@ -0,0 +1,450 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +""" +Quantization APIs + +Generally these APIs can be applied directly to any model +with Linear modules to obtain quantized linear ops. The intended +usage involves applying torch.compile to the model afterwards +both because primitives were designed based on the fusions that +come along with it and because that is how we access the intended quantized +and mixed GEMM kernels +""" + +import torch +import torch.nn as nn +import torch.nn.functional as F +from typing import Any, Callable, Union, Dict, Optional + +from torchao.utils import ( + TORCH_VERSION_AFTER_2_4, + unwrap_tensor_subclass, +) + +from .subclass import ( + QuantizedLinearWeightBase, + LinearActQuantizedTensor, + to_linear_act_quantized, +) + +from .quant_primitives import ( + MappingType, + ZeroPointDomain, +) +from .weight_only import WeightOnlyInt8QuantLinear +from .unified import Quantizer, TwoStepQuantizer +from .GPTQ import ( + Int4WeightOnlyGPTQQuantizer, + Int4WeightOnlyQuantizer, +) +import logging +from .autoquant import autoquant, AutoQuantizableLinearWeight + + +__all__ = [ + "swap_conv2d_1x1_to_linear", + "Quantizer", + "TwoStepQuantizer", + "Int4WeightOnlyGPTQQuantizer", + "Int4WeightOnlyQuantizer", + "autoquant", + "_get_subclass_inserter", + "quantize", + "int8_dynamic_activation_int4_weight", + "int8_dynamic_activation_int8_weight", + "int4_weight_only", + "int8_weight_only", +] + +from .GPTQ import ( + Int8DynActInt4WeightQuantizer, + Int8DynActInt4WeightGPTQQuantizer, + +) +__all__ += [ + "Int8DynActInt4WeightQuantizer", + "Int8DynActInt4WeightGPTQQuantizer", +] + +### TO BE DEPRECATED START +from .subclass import ( + Int4WeightOnlyQuantizedLinearWeight, + Int8DynamicallyQuantizedLinearWeight, + Int8WeightOnlyQuantizedLinearWeight, +) + +def _in_features_greater_than_16(mod, *args): + return hasattr(mod, "in_features") and mod.in_features > 16 + +def change_linear_weights_to_int8_dqtensors(model, filter_fn=None, **kwargs): + """ + Converts all linear weight tensors to the `Int8DynamicallyQuantizedLinearWeight` + Tensor subclass, effectively applying the same form of quantization + as apply_dynamic_quant while not modifying the linear modules. + """ + if TORCH_VERSION_AFTER_2_4: + raise ImportError("This API is deprecated for pytorch 2.4+, please checkout quantization/README.md for most up to date APIs") + + if filter_fn is None: + filter_fn = lambda *args: _is_linear(*args) and _in_features_greater_than_16( + *args + ) + + _replace_with_custom_fn_if_matches_filter( + model, _get_subclass_inserter(Int8DynamicallyQuantizedLinearWeight, enable_parametrization=False, **kwargs), filter_fn + ) + + +def change_linear_weights_to_int8_woqtensors(model, filter_fn=None, **kwargs): + """ + Converts all linear weight tensors to the + `Int8WeightOnlyQuantizedLinearWeight` tensor subclass, + effectively applying the same form of quantization + as apply_weight_only_int8_quant while not modifying the linear modules. + """ + if TORCH_VERSION_AFTER_2_4: + raise ImportError("This API is deprecated for pytorch 2.4+, please checkout quantization/README.md for most up to date APIs") + + _replace_with_custom_fn_if_matches_filter( + model, + _get_subclass_inserter(Int8WeightOnlyQuantizedLinearWeight, enable_parametrization=False, **kwargs), + _is_linear if filter_fn is None else filter_fn, + ) + +def change_linear_weights_to_int4_woqtensors(model, groupsize=128, inner_k_tiles=8, filter_fn=None): + """ + Converts all linear weight tensors to the + `Int4WeightOnlyQuantizedLinearWeight` tensor subclass, + effectively applying the same form of quantization + as apply_dynamic_quant while not modifying the linear modules. + Args: + `groupsize`: parameter for quantization, controls the granularity of quantization, smaller + size is more fine grained, choices are [256, 128, 64, 32] + `inner_k_tiles`: parameter for int4 mm kernel, choices are [8, 4, 2] + """ + if TORCH_VERSION_AFTER_2_4: + raise ImportError("This API is deprecated for pytorch 2.4+, please checkout quantization/README.md for most up to date APIs") + + if filter_fn is None: + filter_fn = _is_linear + + _replace_with_custom_fn_if_matches_filter( + model, + _get_subclass_inserter(Int4WeightOnlyQuantizedLinearWeight, enable_parametrization=False, groupsize=groupsize, inner_k_tiles=inner_k_tiles), + filter_fn, + ) + +### TO BE DEPRECATED END + + + +def _replace_with_custom_fn_if_matches_filter( + model, + replacement_fn, + filter_fn, + cur_fqn="", +) -> None: + """ + Recursively replaces each child module in `model` with the result of `replacement_fn(child)` + if `filter_fn(child)` returns `True`. + + Args: + model (torch.nn.Module): The model containing modules to be replaced. + replacement_fn (Callable[[torch.nn.Module], torch.nn.Module]): The function to replace matching modules. + filter_fn (Callable[[torch.nn.Module], bool]): The filter function to determine which modules to replace. + cur_fqn (str, optional): The current fully qualified name of the module being processed. Defaults to "". + + Returns: + None + """ + if filter_fn(model, cur_fqn[:-1]): + model = replacement_fn(model) + return model + else: + for name, child in model.named_children(): + new_child = _replace_with_custom_fn_if_matches_filter( + child, replacement_fn, filter_fn, f"{cur_fqn}{name}." + ) + if new_child is not child: + setattr(model, name, new_child) + return model + + +def _is_linear(mod, *args): + # avoid circular dep + from torchao.dtypes import AffineQuantizedTensor + + # adding weight tensor subclass isinstance check to make sure the weight is only quantized once + # when it is shared by multiple linear modules + return ( + isinstance(mod, torch.nn.Linear) + and hasattr(mod, "weight") + and not isinstance(mod.weight, QuantizedLinearWeightBase) + and not isinstance(mod.weight, AutoQuantizableLinearWeight) + and not isinstance(mod.weight, AffineQuantizedTensor) + and not isinstance(mod.weight, LinearActQuantizedTensor) + ) + +import torch.nn.utils.parametrize as parametrize + +def _get_subclass_inserter(cls, enable_parametrization=False, **kwargs): + """ + Returns a function which inserts the given subclass into all linear modules + in the model. The inserted module will have its weight set to the result of + `cls(mod.weight, **kwargs)`. If parametrization is enabled then this will be done using + torch.nn.utils.parametrize instead of directly setting the attribute on the module. + + Args: + cls (torch.Tensor): The class to insert as a child module. + kwargs (Any): Any additional arguments for the constructor. + """ + constructor = kwargs.pop("constructor", "subclass_constructor") + from_float = kwargs.pop("method", "from_float") + def insert_subclass(lin): + if enable_parametrization: + lin.weight = torch.nn.Parameter(cls.from_float(lin.weight, **kwargs), requires_grad=False) + _, args = lin.weight.__tensor_flatten__() + parametrize.register_parametrization(lin, "weight", getattr(cls, constructor)(*args)) + else: + lin.weight = torch.nn.Parameter( + # cls.from_float(...) + getattr(cls, from_float)(lin.weight, **kwargs), requires_grad=False + ) + return lin + + return insert_subclass + + +def swap_conv2d_1x1_to_linear(model, filter_fn=None): + """ + Changes all conv2d 1x1 modules to equivalent linear modules so that they can then be quantized. + """ + + class PermuteSandwich(torch.nn.Module): + def __init__(self, mod): + super().__init__() + self.mod = mod + + def forward(self, *args): + return self.mod(args[0].permute(0, 2, 3, 1)).permute(-0, 3, 1, 2) + + def replace_conv2d_1x1(conv): + assert conv.kernel_size == (1, 1) + lin = torch.nn.Linear( + conv.in_channels, conv.out_channels, bias=(conv.bias is None) + ) + lin.weight = torch.nn.Parameter(conv.weight.squeeze(-1, -2)) + lin.bias = conv.bias + return PermuteSandwich(lin) + + if filter_fn is None: + filter_fn = lambda mod, *args: isinstance( + mod, torch.nn.Conv2d + ) and mod.kernel_size == (1, 1) + + _replace_with_custom_fn_if_matches_filter( + model, replace_conv2d_1x1, filter_fn=filter_fn + ) + + +def _get_linear_subclass_inserter(constructor): + def insert_subclass(lin): + lin.weight = torch.nn.Parameter(constructor(lin.weight), requires_grad=False) + return lin + + return insert_subclass + +def quantize(model: torch.nn.Module, apply_tensor_subclass: Callable[[torch.Tensor], torch.Tensor], filter_fn: Optional[Callable[[torch.nn.Module, str], bool]]=None) -> torch.nn.Module: + """Convert the weight of linear modules in the model with `apply_tensor_subclass` + + Args: + model (torch.nn.Module): input model + apply_tensor_subclass (Callable[[torch.Tensor], torch.Tensor]): function that convert a floating point Tensor to a (quantized) tensor subclass instance (e.g. affine quantized tensor instance) + filter_fn (Optional[Callable[[torch.nn.Module, str], bool]]): function that takes a nn.Module instance and fully qualified name of the module, returns True if we want to run `apply_tensor_subclass` on + the weight of the module + + Example:: + + import torch + import torch.nn as nn + from torchao import quantize + + # 1. quantize with some predefined `apply_tensor_subclass` method that corresponds to + # optimized execution paths or kernels (e.g. int4 tinygemm kernel) + # also customizable with arguments + # currently options are + # int8_dynamic_activation_int4_weight (for executorch) + # int8_dynamic_activation_int8_weight (optimized with int8 mm op and torch.compile) + # int4_weight_only (optimized with int4 tinygemm kernel and torch.compile) + # int8_weight_only (optimized with int8 mm op and torch.compile + from torchao.quantization.quant_api import int4_weight_only + + m = nn.Sequential(nn.Linear(32, 1024), nn.Linear(1024, 32)) + m = quantize(m, int4_weight_only(group_size=32)) + + # 2. write your own new apply_tensor_subclass + # You can also add your own apply_tensor_subclass by manually calling tensor subclass constructor + # on weight + + from torchao.dtypes import to_affine_quantized + + # weight only uint4 asymmetric groupwise quantization + groupsize = 32 + apply_weight_quant = lambda x: to_affine_quantized( + x, "asymmetric", (1, groupsize), torch.int32, 0, 15, 1e-6, + zero_point_dtype=torch.bfloat16, preserve_zero=False, zero_point_domain="float") + + # apply to modules under block0 submodule + def filter_fn(module: nn.Module, fqn: str) -> bool: + return isinstance(module, nn.Linear) + + m = nn.Sequential(nn.Linear(32, 1024), nn.Linear(1024, 32)) + m = quantize(m, apply_weight_quant, filter_fn) + + """ + if isinstance(apply_tensor_subclass, str): + if apply_tensor_subclass not in _APPLY_TS_TABLE: + raise ValueError(f"{apply_tensor_subclass} not supported: {_APPLY_TS_TABLE.keys()}") + apply_tensor_subclass = _APPLY_TS_TABLE[apply_tensor_subclass] + + assert not isinstance(apply_tensor_subclass, str) + + _replace_with_custom_fn_if_matches_filter( + model, + _get_linear_subclass_inserter(apply_tensor_subclass), + _is_linear if filter_fn is None else filter_fn, + ) + return model + +def int8_dynamic_activation_int4_weight(group_size=32): + """Applies int8 dynamic per token asymmetric activation quantization and int4 per group weight symmetric quantization to linear + This is used to produce a model for executorch backend, but currently executorch did not + support lowering for the quantized model from this flow yet + + Args: + `group_size`: parameter for quantization, controls the granularity of quantization, smaller + size is more fine grained + """ + def apply_int8_dynamic_activation_int4_weight_quant(weight): + # avoid circular dep + from torchao.dtypes import to_affine_quantized + + # weight settings + mapping_type = MappingType.SYMMETRIC + block_size = (1, group_size) + target_dtype = torch.int8 + eps = torch.finfo(torch.float32).eps + quant_min = -8 + quant_max = 7 + + # TODO: make a general helper function? + # input settings + def get_per_token_block_size(x): + block_size = [] + for i in range(len(x.shape)-1): + block_size.append(1) + block_size.append(x.shape[-1]) + return block_size + + # input settings + input_mapping_type = MappingType.ASYMMETRIC + input_target_dtype = torch.int8 + input_quant_func = lambda x: to_affine_quantized(x, input_mapping_type, get_per_token_block_size(x), input_target_dtype) + + weight = to_affine_quantized(weight, mapping_type, block_size, target_dtype, quant_min, quant_max, eps) + weight = to_linear_act_quantized(weight, input_quant_func) + return weight + + return apply_int8_dynamic_activation_int4_weight_quant + + +def int4_weight_only(group_size=128, inner_k_tiles=8): + """ + Applies uint4 weight-only asymmetric per-group quantization to linear layers, using + "tensor_core_tiled" layout for speedup with tinygemm kernel + + Args: + `group_size`: parameter for quantization, controls the granularity of quantization, smaller + size is more fine grained, choices are [256, 128, 64, 32] + `inner_k_tiles`: parameter for int4 mm kernel, choices are [8, 4, 2] + """ + def apply_int4_weight_only_quant(weight): + # avoid circular dep + from torchao.dtypes import to_affine_quantized + + mapping_type = MappingType.ASYMMETRIC + block_size = (1, group_size) + target_dtype = torch.int32 + quant_min = 0 + quant_max = 15 + eps = 1e-6 + preserve_zero = False + zero_point_dtype = torch.bfloat16 + zero_point_domain = ZeroPointDomain.FLOAT + return to_affine_quantized(weight, mapping_type, block_size, target_dtype, quant_min, quant_max, eps, zero_point_dtype=zero_point_dtype, preserve_zero=preserve_zero, zero_point_domain=zero_point_domain, extended_layout="tensor_core_tiled", inner_k_tiles=inner_k_tiles) + + return apply_int4_weight_only_quant + + +def int8_weight_only(): + """ + Applies int8 weight-only symmetric per-channel quantization to linear layers. + """ + def apply_int8wo_quant(weight): + # avoid circular dep + from torchao.dtypes import to_affine_quantized + + mapping_type = MappingType.SYMMETRIC + target_dtype = torch.int8 + eps = torch.finfo(torch.float32).eps + zero_point_dtype = torch.int64 + block_size = (1, weight.shape[1]) + return to_affine_quantized(weight, mapping_type, block_size, target_dtype, eps=eps, zero_point_dtype=zero_point_dtype) + + return apply_int8wo_quant + +def int8_dynamic_activation_int8_weight(): + """ + Applies int8 dynamic symmetric per-token activation and int8 per-channel weight + quantization to linear layers + """ + def apply_int8_dynamic_activation_int8_weight_quant(weight): + in_features = weight.shape[1] + # int8 dynamic quantization only has benefit when in_feature > 16 + if in_features <= 16: + return weight + + # avoid circular dep + from torchao.dtypes import to_affine_quantized + # weight settings + mapping_type = MappingType.SYMMETRIC + def get_weight_block_size(x): + return (1, x.shape[1]) + target_dtype = torch.int8 + eps = torch.finfo(torch.float32).eps + zero_point_dtype = torch.int64 + + # input settings + def get_per_token_block_size(x): + block_size = list(x.shape) + for i in range(len(block_size)-1): + block_size[i] = 1 + return block_size + + input_mapping_type = MappingType.SYMMETRIC + input_target_dtype = torch.int8 + input_eps = 1e-5 + input_quant_min = -127 + input_quant_max = 127 + input_quant_func = lambda x: to_affine_quantized(x, input_mapping_type, get_per_token_block_size(x), input_target_dtype, eps=input_eps, quant_min=input_quant_min, quant_max=input_quant_max, scale_dtype=torch.float32 if x.dtype == torch.float16 else None) + + block_size = get_weight_block_size(weight) + weight = to_affine_quantized(weight, mapping_type, block_size, target_dtype, eps=eps, zero_point_dtype=zero_point_dtype) + weight = to_linear_act_quantized(weight, input_quant_func) + return weight + + return apply_int8_dynamic_activation_int8_weight_quant diff --git a/videollama2/lib/python3.10/site-packages/torchao/quantization/quant_primitives.py b/videollama2/lib/python3.10/site-packages/torchao/quantization/quant_primitives.py new file mode 100644 index 0000000000000000000000000000000000000000..a78c42605a0101b271116f5eba7d3af01f7f40c9 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torchao/quantization/quant_primitives.py @@ -0,0 +1,367 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from enum import Enum +from typing import List, Optional, Tuple, Dict +import torch + +from torchao.kernel.intmm import int_scaled_matmul +from torchao.kernel.intmm import safe_int_mm +from torchao.utils import TORCH_VERSION_AFTER_2_3 + + +__all__ = [ + "safe_int_mm", + "int_scaled_matmul", + "choose_qparams_affine", + "quantize_affine", + "dequantize_affine", +] + +class MappingType(Enum): + """How floating point number is mapped to integer number + + symmetric mapping means floating point range is symetrically mapped to integer range + let's say we have floating point range (-3.5, 10.2) and integer range (-8, 7) (int4) + we'll use (-10.2, 10.2) as the range for floating point and map that to (-8, 7) + e.g. scale = (10.2 - (-10.2)) / (7 - (-8)) + + asymmetric mapping means we just directly map the floating point range to integer range, + for the above example, we will map (-3.5, 10.2) to (-8, 7) and calculate quantization parameter + based on this mapping + e.g. scale = (10.2 - (-3.5)) / (7 - (-8)) + """ + SYMMETRIC = 0 + ASYMMETRIC = 1 + +class ZeroPointDomain(Enum): + """Enum that indicate whether zero_point is in integer domain or floating point domain + + integer domain: quantized_val = (float_val / scale) (integer) + zero_point (integer) + float domain: quantized_val = (float_val - (zero_point (float) - scale * mid_point)) / scale + """ + INT = 0 + FLOAT = 1 + +""" +Map from dtype to the bound value of integers +TODO: maybe can replace this with call to torch.iinfo +""" +_DTYPE_TO_QVALUE_BOUNDS: Dict[torch.dtype, Tuple[int, int]] = { + torch.uint8: (0, 255), + torch.int8: (-128, 127), + torch.int16: (-(2**15), 2**15 - 1), + torch.int32: (-(2**31), 2**31 - 1), +} + +if TORCH_VERSION_AFTER_2_3: + _DTYPE_TO_QVALUE_BOUNDS.update({ + torch.uint1: (0, 2**1-1), + torch.uint2: (0, 2**2-1), + torch.uint3: (0, 2**3-1), + torch.uint4: (0, 2**4-1), + torch.uint5: (0, 2**5-1), + torch.uint6: (0, 2**6-1), + torch.uint7: (0, 2**7-1), + }) + + +# TODO: decide on if we want to allow custom quant_min/quant_max here +def _get_and_check_qmin_qmax(dtype, quant_min, quant_max): + """Get quant_min and quant_max args based on dtype and also + verify that they are within the range of possible quant_min/quant_max + for dtype + """ + if dtype not in _DTYPE_TO_QVALUE_BOUNDS: + raise ValueError(f"Unsupported dtype: {dtype}") + quant_min_lower_bound, quant_max_upper_bound = _DTYPE_TO_QVALUE_BOUNDS[dtype] + if quant_min is None: + quant_min = quant_min_lower_bound + if quant_max is None: + quant_max = quant_max_upper_bound + + assert quant_min >= quant_min_lower_bound, \ + "quant_min out of bound for dtype, " \ + f"quant_min_lower_bound: {quant_min_lower_bound} quant_min: {quant_min}" + + assert quant_max <= quant_max_upper_bound, \ + "quant_max out of bound for dtype, " \ + f"quant_max_upper_bound: {quant_max_upper_bound} quant_max: {quant_max}" + return quant_min, quant_max + +def _get_reduction_params(block_size, input_size): + """Given block_size and input size find the parameters for reduction: + + Output: + shape_for_reduction: the shape we use to `view` input to prepare it for reduction + reduction_dims: the dims we'll do reduction over + + Example:: + Input: + block_size: (3, 3, 2, 10) + input_size: (3, 3, 10, 10) + + Output: + shape_for_reduction: (3, 3, 5, 2, 10) + reduction_dim: [0, 1, 3, 4] + """ + assert len(block_size) == len(input_size) + shape_for_reduction = [] + reduction_dims = [] + cur_dim = 0 + for i in range(len(block_size)): + if block_size[i] != input_size[i] and block_size[i] > 1: + assert input_size[i] % block_size[i] == 0, f"Expecting input size at {i} dimension: {input_size[i]} to be divisible by block_size at {i} dimension: {block_size[i]}" + shape_for_reduction.append(input_size[i] // block_size[i]) + shape_for_reduction.append(block_size[i]) + # reduce over the block_size[i] dim + reduction_dims.append(cur_dim + 1) + cur_dim += 2 + else: + # block_size[i] == input_size[i] or block_size[i] == 1 + shape_for_reduction.append(input_size[i]) + # we only need to reduce over the dimension if block_size is greater than 1 + # otherwise it's already the same as reduced dimension + if block_size[i] != 1: + reduction_dims.append(cur_dim) + cur_dim += 1 + return shape_for_reduction, reduction_dims + + +def quantize_affine( + input: torch.Tensor, + block_size: Tuple[int, ...], + scale: torch.Tensor, + zero_point: Optional[torch.Tensor], + output_dtype: torch.dtype, + quant_min: Optional[int] = None, + quant_max: Optional[int] = None, + zero_point_domain: ZeroPointDomain = ZeroPointDomain.INT, +): + """ + Args: + input (torch.Tensor): original float32, float16 or bfloat16 Tensor + block_size: (Tuple[int, ...]): granularity of quantization, this means the size of the tensor elements that's sharing the same qparam + e.g. when size is the same as the input tensor dimension, we are using per tensor quantization + scale (float): quantization parameter for affine quantization + zero_point (int): quantization parameter for affine quantization + output_dtype (torch.dtype): requested dtype (e.g. torch.uint8) for output Tensor + quant_min (Optional[int]): minimum quantized value for output Tensor, if not specified, it will be derived from dtype + quant_max (Optional[int]): maximum quantized value for output Tensor, if not specified, it will be derived from dtype + zero_point_domain (ZeroPointDomain): the domain that zero_point is in, should be eitehr integer or float + if zero_point is in integer domain, zero point is added to the quantized integer value during + quantization + if zero_point is in floating point domain, zero point is subtracted from the floating point (unquantized) + value during quantization + default is ZeroPointDomain.INT + + Note: + How can block_size represent different granularities? + let's say we have a Tensor of size: (3, 3, 10, 10), here is the table showing how block_size represents different + granularities: + + granularity type | block_size + per_tensor | (3, 3, 10, 10) + per_axis (axis=0) | (1, 3, 10, 10) + per_axis (axis=1) | (3, 1, 10, 10) + per_group (groupsize=2) | (3, 3, 10, 2) + per_group (groupsize=2) for axis = 3 | (3, 3, 2, 10) + + + Output: + quantized tensor with requested dtype + """ + # TODO: validations + # TODO: validate scale/zero_point dimensions are compatible with block_size + assert input.dtype in [torch.float32, torch.float16, torch.bfloat16], f"Unsupported input dtype: {input.dtype}" + quant_min, quant_max = _get_and_check_qmin_qmax(output_dtype, quant_min, quant_max) + shape_for_reduction, reduction_dims = _get_reduction_params(block_size, input.size()) + original_shape = input.shape + input = input.view(shape_for_reduction) + shape_after_reduction = shape_for_reduction + for i in reduction_dims: + shape_after_reduction[i] = 1 + scale = scale.view(shape_after_reduction) + if zero_point is not None: + zero_point = zero_point.view(shape_after_reduction) + + if zero_point_domain == ZeroPointDomain.INT: + quant = torch.clamp( + torch.round(input * (1.0 / scale)) + zero_point, quant_min, quant_max + ).to(output_dtype) + else: + assert zero_point_domain == ZeroPointDomain.FLOAT + mid_point = (quant_max + quant_min + 1) / 2 + min_val = zero_point - scale * mid_point + quant = ( + torch.clamp( + torch.round((input - min_val) / scale), + quant_min, quant_max) + ).to(output_dtype) + quant = quant.view(original_shape) + + return quant + +def dequantize_affine( + input: torch.Tensor, + block_size: Tuple[int, ...], + scale: torch.Tensor, + zero_point: Optional[torch.Tensor], + input_dtype: torch.dtype, + quant_min: Optional[int] = None, + quant_max: Optional[int] = None, + zero_point_domain: ZeroPointDomain = ZeroPointDomain.INT, + *, + output_dtype: torch.dtype = torch.float32, +): + """ + Args: + input (torch.Tensor): quantized tensor, should match the dtype `dtype` argument + block_size: (List[int]): granularity of quantization, this means the size of the tensor elements that's sharing the same qparam + e.g. when size is the same as the input tensor dimension, we are using per tensor quantization + scale (Tensor): quantization parameter for affine quantization + zero_point (Tensor): quantization parameter for affine quantization + dtype (torch.dtype): requested dtype (e.g. torch.uint8) for output Tensor + quant_min (Optional[int]): minimum quantized value for input Tensor + quant_max (Optional[int]): maximum quantized value for input Tensor + output_dtype (torch.dtype): dtype for output Tensor, default is fp32 + zero_point_domain (ZeroPointDomain): the domain that zero_point is in, should be eitehr integer or float + if zero_point is in integer domain, zero point is added to the quantized integer value during + quantization + if zero_point is in floating point domain, zero point is subtracted from the floating point (unquantized) + value during quantization + default is ZeroPointDomain.INT + + Output: + dequantized Tensor, with requested dtype or fp32 + """ + + # TODO: validations + # TODO: validate scale/zero_point dimensions are compatible with block_size + assert input.dtype == input_dtype, f"Expected: {input_dtype}, got: {input.dtype}" + assert output_dtype in [torch.float32, torch.float16, torch.bfloat16], f"Unsupported output dtype: {output_dtype}" + quant_min, quant_max = _get_and_check_qmin_qmax(input_dtype, quant_min, quant_max) + + shape_for_reduction, reduction_dims = _get_reduction_params(block_size, input.size()) + original_shape = input.shape + input = input.view(shape_for_reduction) + shape_after_reduction = shape_for_reduction + for i in reduction_dims: + shape_after_reduction[i] = 1 + scale = scale.view(shape_after_reduction) + if zero_point is not None: + zero_point = zero_point.view(shape_after_reduction) + + if zero_point_domain == ZeroPointDomain.INT: + # Force a copy to avoid input modification due + # to upcoming in-place operations. + dequant = input.to(torch.int32, copy=True) + if zero_point is not None: + dequant -= zero_point.to(torch.int32) + dequant = dequant.to(output_dtype) + dequant *= scale + else: + assert zero_point_domain == ZeroPointDomain.FLOAT, f"Unexpected zero point domain: {zero_point_domain}" + mid_point = (quant_max + quant_min + 1) / 2 + # This should allocate new memory and avoid input modification + dequant = input - mid_point + dequant = dequant.to(output_dtype) + dequant *= scale + if zero_point is not None: + dequant += zero_point + + return dequant.view(original_shape).to(output_dtype) + +def choose_qparams_affine( + input: torch.Tensor, + mapping_type: MappingType, + block_size: Tuple[int, ...], + target_dtype: torch.dtype, + quant_min: Optional[int] = None, + quant_max: Optional[int] = None, + eps: Optional[float] = None, + scale_dtype: Optional[torch.dtype] = None, + zero_point_dtype: Optional[torch.dtype] = None, + preserve_zero: bool = True, + zero_point_domain = ZeroPointDomain.INT, +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Args: + input (torch.Tensor): fp32, bf16, fp16 input Tensor + mapping_type (MappingType): determines how the qparams are calculated, symmetric or asymmetric + block_size: (Tuple[int, ...]): granularity of quantization, this means the size of the tensor elements that's sharing the same qparam + e.g. when size is the same as the input tensor dimension, we are using per tensor quantization + target_dtype (torch.dtype): dtype for target quantized Tensor + quant_min (Optional[int]): minimum quantized value for target quantized Tensor + quant_max (Optioanl[int]): maximum quantized value for target quantized Tensor + eps (Optional[float]): minimum scale, if not provided, default to eps of input.dtype + scale_dtype (torch.dtype): dtype for scale Tensor + zero_point_dtype (torch.dtype): dtype for zero_point Tensor + preserve_zero (bool): a flag to indicate whether we need zero to be exactly + representable or not, this is typically required for ops that needs zero padding, like convolution + it's less important for ops that doesn't have zero padding in the op itself, like linear. + + For example, given a floating point Tensor [1.2, 0.1, 3.0, 4.0, 0.4, 0], if `preserve_zero` is True, + we'll make sure there is a integer value corresponding to the floating point 0, e.g. [-3, -8, 3, 7, -7, -8], 0 will be mapped to `-8` without loss. But if `preserve_zero` is not True, there won't be such + gurantee. + + If we don't need zero to be exactly representable, we won't do rounding and clamping for zero_point + + zero_point_domain (ZeroPointDomain): the domain that zero_point is in, should be eitehr integer or float + if zero_point is in integer domain, zero point is added to the quantized integer value during + quantization + if zero_point is in floating point domain, zero point is subtracted from the floating point (unquantized) + value during quantization + default is ZeroPointDomain.INT + + Output: + Tuple of scales and zero_points Tensor with requested dtype + """ + quant_min, quant_max = _get_and_check_qmin_qmax(target_dtype, quant_min, quant_max) + assert mapping_type in [MappingType.SYMMETRIC, MappingType.ASYMMETRIC], f"Unsupported mapping type: {mapping_type}" + + if scale_dtype is None: + scale_dtype = input.dtype + if zero_point_dtype is None: + zero_point_dtype = input.dtype + + assert len(block_size) == input.dim() + shape_for_reduction, reduction_dims = _get_reduction_params(block_size, input.size()) + input = input.view(shape_for_reduction) + + min_val = torch.amin(input, dim=reduction_dims, keepdim=False) + max_val = torch.amax(input, dim=reduction_dims, keepdim=False) + + if preserve_zero: + min_val_neg = torch.min(min_val, torch.zeros_like(min_val)) + max_val_pos = torch.max(max_val, torch.zeros_like(max_val)) + else: + min_val_neg = min_val + max_val_pos = max_val + + if mapping_type == MappingType.SYMMETRIC: + max_val_pos = torch.max(-min_val_neg, max_val_pos) + scale = max_val_pos / (float(quant_max - quant_min) / 2) + if not preserve_zero: + raise ValueError("preserve_zero == False is not supported for symmetric quantization") + if zero_point_domain != ZeroPointDomain.INT: + raise ValueError("zero_point_domain != ZeroPointDomain.INT is not supported for symmetric quantization") + zero_point = torch.full_like(scale, int((quant_max + quant_min + 1) / 2)) + else: + scale = (max_val_pos - min_val_neg) / float(quant_max - quant_min) + if preserve_zero: + zero_point = quant_min - torch.round(min_val_neg / scale) + zero_point = torch.clamp(zero_point, quant_min, quant_max) + else: + assert zero_point_domain == ZeroPointDomain.FLOAT, "if not preserve_zero, zero_point must be in FLOAT domain" + mid_point = (quant_max + quant_min + 1) / 2 + zero_point = min_val_neg + scale * mid_point + + if eps is None: + eps = torch.finfo(input.dtype).eps + scale = torch.clamp(scale, min=eps) + + return scale.to(dtype=scale_dtype), zero_point.to(dtype=zero_point_dtype) diff --git a/videollama2/lib/python3.10/site-packages/torchao/quantization/smoothquant.py b/videollama2/lib/python3.10/site-packages/torchao/quantization/smoothquant.py new file mode 100644 index 0000000000000000000000000000000000000000..8d3d8be546166a40b85a498215d5acee6f482979 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torchao/quantization/smoothquant.py @@ -0,0 +1,270 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +""" +Testing out accuracy-only implementation of SmoothQuant +(https://arxiv.org/pdf/2211.10438.pdf) +Note: this is an application of input-weight equalization, with the addition that the +multiplication by scale is fused into the preceding layer, specifically for relevant +parts of transformer blocks. +""" + +import torch +import torch.nn.functional as F + +import torchao.quantization.quant_api as quant_api + +from .utils import ( + dynamically_quantize_per_channel, + quant_int8_dynamic_per_token_linear, +) + +__all__ = [ + "get_scale", + "SmoothFakeDynQuantMixin", + "SmoothFakeDynamicallyQuantizedLinear", + "swap_linear_with_smooth_fq_linear", + "smooth_fq_linear_to_inference", + "set_smooth_fq_attribute", +] + + +def get_scale(X_absmax, W_absmax, alpha=0.5): + """ + Calculate the scale based on abs(max(X)), abs(max(W)), and alpha. + + Args: + X_absmax (torch.Tensor): Absolute maximum values of the input tensor X. + W_absmax (torch.Tensor): Absolute maximum values of the weight tensor W. + alpha (float, optional): Scaling factor. Defaults to 0.5. + + Returns: + torch.Tensor: The calculated scale of dimension `k` if X is of dimension `b*n*k` and W is of dimension `k*m`. + """ + X_pow = torch.pow(X_absmax, alpha) + W_pow = torch.pow(W_absmax, 1.0 - alpha) + div = X_pow / W_pow + return div.reshape(-1) + + +class SmoothFakeDynQuantMixin(torch.nn.Module): + + def init_smoothquant_variables(self, alpha): + self.calibrating = True + self.x_running_abs_max = None + self.register_buffer("smooth_scale", None) + self.alpha = alpha + # debug only + self.debug_skip_scaling = False + # self.debug_skip_scaling = True + + # Currently torch._int_mm cuBLAS underlying kernel does not work with + # non-contiguous weight. However, torch.compil'ing through + # torch._int_mm leads to triton code which is ~2x faster if the weight + # is transposed. So, for now we have a debug flag to toggle whether + # we store the quantized weight transposed, so that we can get correct + # numerics both in eager mode and after torch.compile. + # The default is True for cuBLAS / eager mode, set to False for + # torch.compile. + # self.store_w_int_repr_t = True + self.store_w_int_repr_t = False + + def update_x_running_abs_max(self, X): + # update the running max of incoming activations + all_dims_except_last = tuple(range(len(X.shape) - 1)) + cur_abs_max = torch.amax(torch.abs(X), dim=all_dims_except_last) + if self.x_running_abs_max is None: + self.x_running_abs_max = cur_abs_max + else: + self.x_running_abs_max = torch.max(cur_abs_max, self.x_running_abs_max) + + def get_scaled_quantized_w(self): + # inference + assert ( + self.smooth_scale is not None + ), "self.smooth_scale is None, did you turn on inference?" + W = self.weight + + # scale weight + # in the future, this can be done ahead of time instead of + # during inference + if not self.debug_skip_scaling: + # TODO(future): do below in `to_inference` instead of here + W = torch.matmul( + torch.diag(self.smooth_scale), W.transpose(0, 1) + ).transpose(0, 1) + + # fake quantize input and weight, and then do matmul in fp32/fp16 + # in the future, this should be replaced with quantized kernels which + # work on NVIDIA GPUs (such as protoquant's implementation) + W_dq_dtype = W.dtype + W_int_repr, W_scales, W_zps = dynamically_quantize_per_channel( + W, -128, 127, torch.int8 + ) + W_int_repr = W_int_repr.contiguous() + return W_int_repr, W_scales, W_zps + + def to_inference(self): + raise NotImplementedError() + + def fold_weight(self): + # note: _W_zps are zeroes and they are ignored + # TODO(future PR): set up serialization for this + W_int_repr, self.W_scales, _W_zps = self.get_scaled_quantized_w() + # need to store transposed weights to make eager mode matmul + # op work in cuBlas, or non-transposed to make it fast in torch.compile + if self.store_w_int_repr_t: + self.register_buffer("W_int_repr", W_int_repr.transpose(0, 1).contiguous()) + else: + self.register_buffer("W_int_repr", W_int_repr.contiguous()) + del self.weight + + def set_debug_x_absmax(self): + """ + Sets `self.x_running_abs_max` to a value which will lead to smooth scale + of all ones if `alpha=0.5`, to enable performance benchmarking without + calibration. + """ + raise NotImplementedError() + + +class SmoothFakeDynamicallyQuantizedLinear(SmoothFakeDynQuantMixin, torch.nn.Linear): + """ + This is a replacement for `torch.nn.Linear` which implements dynamic per-token + activation quantization and dynamic per-channel weight quantization based on + Smoothquant scaling. + """ + + def __init__(self, *args, **kwargs): + alpha = kwargs.pop("alpha") + super().__init__(*args, **kwargs) + self.init_smoothquant_variables(alpha) + + def forward(self, X, *args, **kwargs): + if self.calibrating: + self.update_x_running_abs_max(X) + Y = F.linear(X, self.weight, self.bias) + else: + if not self.debug_skip_scaling: + # Ideally this would be fused into preceding layers + # but in practice torch.compile fuses it with other + # ops so the slowdown is minimal + X = X / self.smooth_scale + W_int_repr_t = ( + self.W_int_repr if self.store_w_int_repr_t else self.W_int_repr.t() + ) + Y = quant_int8_dynamic_per_token_linear( + X, W_int_repr_t, self.W_scales, self.bias, X.dtype + ) + return Y + + @classmethod + def from_float(cls, mod, alpha=0.5): + """ + Converts a `mod` of class `torch.nn.Linear` to the smooth fake quantized + version of it. Note: requires calibration. + """ + # create the new module with a toy size to ensure initialization is fast + fake_in_features, fake_out_features = 8, 8 + new_mod = cls( + fake_in_features, fake_out_features, bias=mod.bias is not None, alpha=alpha + ) + new_mod.in_features = mod.in_features + new_mod.out_features = mod.out_features + new_mod.weight = mod.weight + new_mod.bias = mod.bias + # TODO: test when creation is on cuda + device_to_use = next(mod.parameters()).device + new_mod.to(device_to_use) + return new_mod + + def to_inference(self): + """ + Calculates the smoothquant scale based on calibration + in preparation for inference + """ + assert self.x_running_abs_max is not None, "no calibration data found" + self.calibrating = False + self.smooth_scale = get_scale( + self.x_running_abs_max, + torch.max(torch.abs(self.weight.transpose(0, 1)), dim=1).values, + alpha=self.alpha, + ) + self.fold_weight() + + def set_debug_x_absmax(self): + w_absmax = torch.max(torch.abs(self.weight.transpose(0, 1)), dim=1).values + self.x_running_abs_max = w_absmax + + +# +# utils to use the smooth linear on real models +# + +source_cls_to_target_cls = { + torch.nn.Linear: SmoothFakeDynamicallyQuantizedLinear, + torch.nn.modules.linear.NonDynamicallyQuantizableLinear: SmoothFakeDynamicallyQuantizedLinear, +} + + +def swap_linear_with_smooth_fq_linear( + model, skip_fqn_list=None, cur_fqn="", alpha=0.5 +) -> None: + """ + Replaces linear layers in the model with their SmoothFakeDynamicallyQuantizedLinear equivalents. + + Args: + model (torch.nn.Module): The model containing linear layers to be replaced. + skip_fqn_list (list of str, optional): List of fully qualified names to skip during replacement. Defaults to None. + cur_fqn (str, optional): The current fully qualified name of the module being processed. Defaults to "". + alpha (float, optional): The scaling factor for SmoothQuant. Defaults to 0.5. + + Returns: + None + """ + + name_to_child = dict(model.named_children()) + for name, child in name_to_child.items(): + if cur_fqn == "": + new_fqn = name + else: + new_fqn = f"{cur_fqn}.{name}" + if ((skip_fqn_list is None) or (new_fqn not in skip_fqn_list)) and ( + type(child) in source_cls_to_target_cls.keys() + ): + target_cls = source_cls_to_target_cls[type(child)] + new_child = target_cls.from_float(child, alpha=alpha) + setattr(model, name, new_child) + else: + swap_linear_with_smooth_fq_linear(child, skip_fqn_list, new_fqn, alpha) + + +def smooth_fq_linear_to_inference(model, debug_skip_calibration=False) -> None: + """ + Prepares the model for inference by calculating the smoothquant scale for each SmoothFakeDynamicallyQuantizedLinear layer. + + Args: + model (torch.nn.Module): The model containing SmoothFakeDynamicallyQuantizedLinear layers. + debug_skip_calibration (bool, optional): If True, sets the running maximum of activations to a debug value for performance benchmarking. + Defaults to False. + + Returns: + None + """ + for _, mod in model.named_modules(): + if isinstance(mod, tuple(source_cls_to_target_cls.values())): + if debug_skip_calibration: + mod.set_debug_x_absmax() + mod.to_inference() + + +# useful for quickly toggling smoothquant debug settings on all smoothquant +# modules in a model +def set_smooth_fq_attribute(model, attribute_name, new_attribute_val): + for _, mod in model.named_modules(): + if isinstance(mod, tuple(source_cls_to_target_cls.values())): + if hasattr(mod, attribute_name): + setattr(mod, attribute_name, new_attribute_val) diff --git a/videollama2/lib/python3.10/site-packages/torchao/quantization/subclass.py b/videollama2/lib/python3.10/site-packages/torchao/quantization/subclass.py new file mode 100644 index 0000000000000000000000000000000000000000..a2801a622fc6b0551e985997b012fa860e2201ae --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torchao/quantization/subclass.py @@ -0,0 +1,754 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import warnings + +import torch +from torch.utils._python_dispatch import return_and_correct_aliasing + +from .quant_primitives import ( + MappingType, +) + +from .utils import ( + find_multiple, + dequantize_per_channel, + dynamically_quantize_per_channel, + groupwise_affine_quantize_tensor, + quant_int8_dynamic_per_token_linear, + unpack_tinygemm_scales_and_zeros, + groupwise_affine_quantize_tensor_from_qparams, +) +from torchao.utils import find_multiple +from typing import Tuple, Optional, Callable, Dict, Any + + +__all__ = [ + "Int8DynamicallyQuantizedLinearWeight", + "Int8WeightOnlyQuantizedLinearWeight", + "Int4WeightOnlyQuantizedLinearWeight", + "LinearActQuantizedTensor", + "to_linear_act_quantized", +] + + +aten = torch.ops.aten + +class QuantizedLinearWeightBase(torch.Tensor): + """ + Base quantized tensor subclass for quantized linear weights. When the from_float method is used, + to create an instance of any QuantizedLinearWeightBase, we assume the input + weight is oriented the way it is in a normal linear op, i.e. out-channels x in-channels. + + The shape and dtype of the tensor subclass represent how the tensor subclass looks externally, + regardless of the internal representation's type or orientation. + """ + + @staticmethod + def __new__(cls, int_data, transposed, shape, *args, **kwargs): + kwargs["device"] = int_data.device + kwargs["layout"] = ( + kwargs.get("layout") if kwargs.get("layout", False) else int_data.layout + ) + assert "dtype" in kwargs + assert not kwargs.get("requires_grad", False) + kwargs["requires_grad"] = False + return torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs) # type: ignore[attr-defined] + + def __init__(self, int_data, transposed, *args, **kwargs): + + self.int_data = int_data + + self.transposed = transposed + + @staticmethod + def _quantized_op(act_mat, w_qtensor, bias): + pass + + def __repr__(self): + return ( + f"{self.__class__.__name__}(data={self.dequantize()}, shape={self.shape}, " + f"device={self.device}, dtype={self.dtype}, requires_grad={self.requires_grad})" + ) + + def dequantize(self): + pass + + def int_repr(self): + pass + + def q_params(self): + pass + + def half(self): + return self.to(torch.float16) + + def _get_to_kwargs(self, *args, **kwargs): + device, dtype, _, memory_format = torch._C._nn._parse_to(*args, **kwargs) + device = self.device if device is None else device + dtype = self.dtype if dtype is None else dtype + memory_format = ( + memory_format if memory_format is not None else torch.preserve_format + ) + kwargs = { + "device": device, + "dtype": dtype, + "memory_format": memory_format, + } + return kwargs + + def _apply_fn_to_data(self, fn): + pass + + def _change_shape(self): + pass + + def __tensor_flatten__(self): + pass + + @classmethod + def __tensor_unflatten__( + cls, tensor_data_dict, tensor_attributes, outer_size, outer_stride + ): + pass + + @classmethod + def from_float(cls, input_float): + pass + + # __torch_function__ = torch._C._disabled_torch_function_impl + + @classmethod + def __torch_function__(cls, func, types, args=(), kwargs=None): + kwargs = {} if kwargs is None else kwargs + + if func is torch.nn.functional.linear: + mat1, w_qtensor, bias = ( + args[0], + args[1], + args[2] if len(args) > 2 else None, + ) + assert w_qtensor.transposed == False + return cls._quantized_op(mat1, w_qtensor, bias) + + try: + with torch._C.DisableTorchFunctionSubclass(): + return func(*args, **kwargs) + except: + print(f"ERR: subclass doesn't implement {func}") + + @classmethod + def __torch_dispatch__(cls, func, types, args, kwargs): + # two scenarios where we currently fall back to vanilla mm: + # 1 - when tensor is on CPU: we are missing qmm for CPU, but we should have a CPU implementation + # for consistency and to allow people to test + # 2 - we're given non-floats - quantizing long to int8 is crazy + if ( + func in [aten.mm.default, aten.addmm.default] + and args[0].is_floating_point() + and args[0].is_cuda + ): + if func == aten.addmm.default: + assert args[1].shape[-1] == args[2].shape[0], ( + f"need mat1 shape: {args[1].shape} final" + f"dim to match mat2 shape: {args[2].shape} first dim " + ) + mat1, w_qtensor, bias = ( + args[1], + args[2], + args[0], + ) + else: + assert args[0].shape[-1] == args[1].shape[0], ( + f"need mat1 shape: {args[0].shape} final dim" + f"to match mat2 shape: {args[1].shape} first dim" + ) + mat1, w_qtensor, bias = ( + args[0], + args[1], + None if len(args) == 2 else args[2], + ) + # call the quantized op for the specific type + # of quantized tensor subclass + return cls._quantized_op(mat1, w_qtensor, bias) + + if func is aten.detach.default: + return return_and_correct_aliasing( + func, args, kwargs, args[0]._apply_fn_to_data(torch.detach) + ) + + if func is aten.clone.default: + return return_and_correct_aliasing( + func, args, kwargs, args[0]._apply_fn_to_data(torch.clone) + ) + + if func is aten.t.default: + args[0].transposed = not args[0].transposed + new = args[0]._change_shape(args[0].shape[::-1]) + return return_and_correct_aliasing(func, args, kwargs, new) + + if func is aten._to_copy.default: + return return_and_correct_aliasing( + func, + args, + kwargs, + args[0].to(*args[1:], **kwargs)._apply_fn_to_data(torch.clone), + ) + +class ConstructTensorSubclass(torch.nn.Module): + def __init__(self, *args, **kwargs): + super().__init__() + self.args = args + self.kwargs = kwargs + + def forward(self, x): + pass + + def right_inverse(self, tensor_subclass_instance): + fields, _ = tensor_subclass_instance.__tensor_flatten__() + return [getattr(tensor_subclass_instance, field) for field in fields] + + +@torch._dynamo.allow_in_graph +def from_qtensor_components_int8dyn(*args, **kwargs): + return Int8DynamicallyQuantizedLinearWeight(*args, **kwargs) + + +class ConstructTensorSubclassInt8Dyn(ConstructTensorSubclass): + def forward(self, int_data, q_scales): + return from_qtensor_components_int8dyn(int_data, q_scales, *self.args, **self.kwargs) + + +class Int8DynamicallyQuantizedLinearWeight(QuantizedLinearWeightBase): + """ + A Tensor subclass that when applied to a weight used in a linear op/module, changes the + linear op to a dynamically quantized linear op with symmetric per-token and per-channel + quantization on the activation and weight respectively. + """ + subclass_constructor = ConstructTensorSubclassInt8Dyn + + @staticmethod + def __new__(cls, int_data, q_scales, transposed, shape, dtype=None, **kwargs): + if dtype is None: + dtype = qscales.dtype + kwargs["dtype"] = dtype + return super().__new__(cls, int_data, transposed, shape, **kwargs) # type: ignore[attr-defined] + + def __init__(self, int_data, q_scales, transposed, shape, dtype=None, **kwargs): + self.q_scales = q_scales + super().__init__(int_data, transposed) + + @staticmethod + def _quantized_op(act_mat, w_qtensor, bias): + return quant_int8_dynamic_per_token_linear( + act_mat, w_qtensor.int_data, w_qtensor.q_scales, bias, act_mat.dtype + ) + + def dequantize(self, dtype=None): + """ + Obtain the dequantized version of the quantized tensor subclass + """ + zero_points = torch.zeros(self.q_scales.shape, device=self.q_scales.device, dtype=self.q_scales.dtype) + # zero_points = 0 + # TODO: fix dtype here? `to(self.dtype)` is not overwritten by `dtype` arg? + dq_t = dequantize_per_channel( + self.int_data.t(), self.q_scales, zero_points, self.dtype if dtype is None else dtype + ).to(self.dtype) + # data was transposed to dequantize so make sure shape is correct + return dq_t if not self.transposed else dq_t.t() + + def int_repr(self): + """ + Get the internal integer representation of the quantized tensor + """ + return self.int_data if self.transposed else self.int_data.t() + + def q_params(self): + """ + Get the quantization scales for the quantized tensor + """ + return {"q_scales": self.q_scales} + + def to(self, *args, **kwargs): + kwargs = self._get_to_kwargs(*args, **kwargs) + return self.__class__( + self.int_data.to(kwargs["device"]), + self.q_scales.to(kwargs["device"]), + self.transposed, + self.shape, + **kwargs, + ) + + def _apply_fn_to_data(self, fn): + return self.__class__( + fn(self.int_data), + fn(self.q_scales), + self.transposed, + self.shape, + dtype=self.dtype, + ) + + # `QuantizedLinearWeightBase` inconsistently. + + def _change_shape(self, shape): + return self.__class__( + self.int_data, self.q_scales, self.transposed, shape, dtype=self.dtype + ) + + def __tensor_flatten__(self): + # note: the order of args must match the order of args in __init__ + return ["int_data", "q_scales"], [self.transposed, self.shape, self.dtype] + + @classmethod + def __tensor_unflatten__( + cls, tensor_data_dict, tensor_attributes, outer_size=None, outer_stride=None + ): + int_data, q_scales = tensor_data_dict["int_data"], tensor_data_dict["q_scales"] + transposed, shape, dtype = tensor_attributes + return cls( + int_data, + q_scales, + transposed, + shape if outer_size is None else outer_size, + dtype=dtype, + strides=outer_stride, + ) + + @classmethod + def from_float(cls, input_float, qmin=-128, qmax=127, dtype=None): + """ + Method used to convert a linear weight tensor to an instance of the + Int8DynamicallyQuantizedLinearWeight subclass. + + Example usage:: + + model.lin_mod.weight = ( + Int8DynamicallyQuantizedLinearWeight.from_float(model.lin_mod.weight) + ) + """ + if dtype is None: + dtype = input_float.dtype + + # because we call transpose in dequantization + w_int_repr, w_scales, _ = dynamically_quantize_per_channel( + input_float, qmin, qmax, torch.int8 + ) + # the desired representation shape for fast quantized matmul is + # transposed compared to how it's stored as a linear weight, + # i.e. we want in_channels as dim=0 and out_channels (and quantized axis) as dim=1 + # however the external representation of our tensor will maintain the correct + # shape attribute which needs to be tracked directly. + int_data = w_int_repr.contiguous().t() + if not issubclass(cls, Int8DynamicallyQuantizedLinearWeight): + int_data = int_data.contiguous() + return cls( + int_data, w_scales, False, input_float.shape, dtype=dtype, + ) + + +@torch._dynamo.allow_in_graph +def from_qtensor_components_int8wo(*args, **kwargs): + return Int8WeightOnlyQuantizedLinearWeight(*args, **kwargs) + + +class ConstructTensorSubclassInt8wo(ConstructTensorSubclass): + def forward(self, int_data, q_scales): + return from_qtensor_components_int8wo(int_data, q_scales, *self.args, **self.kwargs) + + +class Int8WeightOnlyQuantizedLinearWeight(Int8DynamicallyQuantizedLinearWeight): + """ + A Tensor subclass that when applied to a weight used in a linear op/module, + changes the linear op to a weight-only quantized linear op with symmetric + per-channel quantization on the weight. + """ + subclass_constructor = ConstructTensorSubclassInt8wo + + @staticmethod + def _quantized_op(act_mat, w_qtensor, bias): + orig_dtype = act_mat.dtype + y = ( + torch.mm( + act_mat.reshape(-1, act_mat.shape[-1]), + w_qtensor.int_data.to(act_mat.dtype), + ) + * w_qtensor.q_scales + ) + y = y.reshape(*act_mat.shape[:-1], y.shape[-1]) + if bias is not None: + y += bias + return y.to(orig_dtype) + + +@torch._dynamo.allow_in_graph +def from_qtensor_components_int4wo(*args, **kwargs): + return Int4WeightOnlyQuantizedLinearWeight(*args, **kwargs) + +class ConstructTensorSubclassInt4wo(ConstructTensorSubclass): + def forward(self, int_data, scales_and_zeros): + return from_qtensor_components_int4wo(int_data, scales_and_zeros, *self.args, **self.kwargs) + +class Int4WeightOnlyQuantizedLinearWeight(QuantizedLinearWeightBase): + """ + A Tensor subclass that when applied to a weight used in a linear op/module, + changes that linear op to a weight-only int4 quantized linear op with groupwise + affine quantization on the weight. + """ + subclass_constructor = ConstructTensorSubclassInt4wo + + @staticmethod + def __new__( + cls, + int_data, + scales_and_zeros, + transposed, + shape, + groupsize=128, + inner_k_tiles=8, + dtype=None, + **kwargs, + ): + if dtype is None: + dtype = scales_and_zeros.dtype + kwargs["dtype"] = dtype + return super().__new__(cls, int_data, transposed, shape, **kwargs) # type: ignore[attr-defined] + + def __init__( + self, + int_data, + scales_and_zeros, + transposed, + shape, + groupsize, + inner_k_tiles, + dtype, + **kwargs, + ): + # the transposed flag tracks whether the tensor subclass has been transposed relative + # to how a weight is normally stored in a linear i.e. [out_features, in_features]. + # tracking both transposed and shape is slightly redundant but corner cases like + # square matrices can cause issues otherwise + + self.scales_and_zeros = scales_and_zeros + self.groupsize = groupsize + self.inner_k_tiles = inner_k_tiles + super().__init__(int_data, transposed) + + @staticmethod + def _quantized_op(act_mat, w_qtensor, bias): + orig_act_size = act_mat.size() + orig_dtype = act_mat.dtype + + # reshape and pad activation + act_mat = act_mat.reshape(-1, act_mat.shape[-1]).to(torch.bfloat16) + pad_size = find_multiple(act_mat.shape[-1], 1024) + act_mat = torch.nn.functional.pad(act_mat, (0, pad_size - act_mat.shape[-1])) + + # matmul + y = aten._weight_int4pack_mm( + act_mat.contiguous(), + w_qtensor.int_data, + w_qtensor.groupsize, + w_qtensor.scales_and_zeros, + ) + + # remove out_feature padding + orig_out_features = ( + w_qtensor.shape[-1] if w_qtensor.transposed else w_qtensor.shape[-2] + ) + y = y[:, :orig_out_features] + + y = y.reshape(*orig_act_size[:-1], orig_out_features) + if bias is not None: + y += bias + return y.to(orig_dtype) + + def dequantize(self): + eye_shape = self.shape[1] if not self.transposed else self.shape[0] + w_dq = self._quantized_op( + torch.eye(eye_shape, device=self.device, dtype=self.dtype), self, None + ) + # we dequantized using linear with the identity matrix, output has shape [in_channels, out_channels] + # so we need to transpose back to get the original shape unless self.transposed is set. + w_dq = w_dq if self.transposed else w_dq.t() + return w_dq.to(self.dtype) + + def int_repr(self): + return self.int_data + + def q_params(self): + scales, zero_points = unpack_tinygemm_scales_and_zeros( + self.scales_and_zeros, + ) + return {"q_scales": scales, "q_zero_points": zero_points} + + def to(self, *args, **kwargs): + kwargs = self._get_to_kwargs(*args, **kwargs) + return self.__class__( + self.int_data.to(kwargs["device"]), + self.scales_and_zeros.to(kwargs["device"]), + self.transposed, + self.shape, + self.groupsize, + self.inner_k_tiles, + **kwargs, + ) + + def _apply_fn_to_data(self, fn): + return self.__class__( + fn(self.int_data), + fn(self.scales_and_zeros), + self.transposed, + self.shape, + self.groupsize, + self.inner_k_tiles, + dtype=self.dtype, + ) + + # `QuantizedLinearWeightBase` inconsistently. + + def _change_shape(self, shape): + return self.__class__( + self.int_data, + self.scales_and_zeros, + self.transposed, + shape, + self.groupsize, + self.inner_k_tiles, + dtype=self.dtype, + ) + + def __tensor_flatten__(self): + return ["int_data", "scales_and_zeros"], ( + self.transposed, + self.shape, + self.groupsize, + self.inner_k_tiles, + self.dtype, + ) + + @classmethod + + # `QuantizedLinearWeightBase` inconsistently. + + def __tensor_unflatten__( + cls, tensor_data_dict, attributes, outer_size=None, outer_stride=None + ): + int_data, scales_and_zeros = ( + tensor_data_dict["int_data"], + tensor_data_dict["scales_and_zeros"], + ) + transposed, shape, groupsize, inner_k_tiles, dtype = attributes + return cls( + int_data, + scales_and_zeros, + transposed, + shape if outer_size is None else outer_size, + groupsize, + inner_k_tiles, + dtype=dtype, + strides=outer_stride, + ) + + @classmethod + def from_float(cls, input_float, groupsize=128, inner_k_tiles=8, dtype=None): + """ + Method used to convert a linear weight tensor to an instance of the + Int4WeightOnlyQuantizedLinearWeight subclass. + + Example usage:: + + model.lin_mod.weight = ( + Int4WeightOnlyQuantizedLinearWeight.from_float(model.lin_mod.weight) + ) + """ + if dtype is None: + dtype = input_float.dtype + + int_data, scales_and_zeros, transposed, groupsize, inner_k_tils = cls.to_qtensor_components(input_float, groupsize, inner_k_tiles) + return cls( + int_data, + scales_and_zeros, + transposed, + input_float.shape, + groupsize, + inner_k_tiles, + dtype=dtype, + ) + + @classmethod + def to_qtensor_components(cls, input_float, groupsize=128, inner_k_tiles=8): + assert groupsize in [256, 128, 64, 32] + assert inner_k_tiles in [8, 4, 2] + orig_out_features, orig_in_features = input_float.shape + + # padding + in_features = find_multiple(orig_in_features, 1024) + out_features = find_multiple(orig_out_features, 8) + input_float = torch.nn.functional.pad( + input_float, + (0, in_features - orig_in_features, 0, out_features - orig_out_features), + ) + + # quantization and packing + input_int4x8, scales_and_zeros = groupwise_affine_quantize_tensor( + input_float, 4, groupsize, dtype=input_float.dtype + ) + int_data = aten._convert_weight_to_int4pack(input_int4x8, inner_k_tiles) + return int_data, scales_and_zeros, False, groupsize, inner_k_tiles + + +class LinearActQuantizedTensor(torch.Tensor): + """ + Applies activation quantization for linear operator + """ + def __new__( + cls, + original_weight_tensor: torch.Tensor, + input_quant_func: Callable, + ): + kwargs = {} + dtype = original_weight_tensor.dtype + kwargs["dtype"] = dtype + kwargs["requires_grad"] = False + kwargs["device"] = original_weight_tensor.device + shape = original_weight_tensor.shape + return torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs) # type: ignore[attr-defined] + + def __init__( + self, + original_weight_tensor: torch.Tensor, + input_quant_func: Callable, + ): + self.original_weight_tensor = original_weight_tensor + self.input_quant_func = input_quant_func + + def __tensor_flatten__(self): + return ["original_weight_tensor"], [self.input_quant_func] + + @classmethod + def __tensor_unflatten__( + cls, tensor_data_dict, tensor_attributes, outer_size, outer_stride + ): + original_weight_tensor = tensor_data_dict["original_weight_tensor"] + input_quant_func, = tensor_attributes + return cls( + original_weight_tensor, + input_quant_func, + ) + + @classmethod + def from_float(cls, input_float, input_quant_func): + return cls(input_float, input_quant_func) + + @classmethod + def __torch_function__(cls, func, types, args=(), kwargs=None): + kwargs = {} if kwargs is None else kwargs + + if func is torch.nn.functional.linear: + input_tensor, weight_tensor, bias = ( + args[0], + args[1], + args[2] if len(args) > 2 else None, + ) + if isinstance(weight_tensor, LinearActQuantizedTensor): + input_quant_func = weight_tensor.input_quant_func + original_weight_tensor = weight_tensor.original_weight_tensor + aqt = input_quant_func(input_tensor) + return torch.nn.functional.linear(aqt, original_weight_tensor, bias) + + with torch._C.DisableTorchFunctionSubclass(): + return func(*args, **kwargs) + + def _apply_fn_to_data(self, fn): + return self.__class__( + fn(self.original_weight_tensor), + self.input_quant_func, + ) + + def _get_to_kwargs(self, *args, **kwargs): + device, dtype, _, memory_format = torch._C._nn._parse_to(*args, **kwargs) + device = self.device if device is None else device + dtype = self.dtype if dtype is None else dtype + memory_format = ( + memory_format if memory_format is not None else torch.preserve_format + ) + kwargs = { + "device": device, + "dtype": dtype, + "memory_format": memory_format, + } + return kwargs + + def to(self, *args, **kwargs): + kwargs = self._get_to_kwargs(*args, **kwargs) + return self.__class__( + self.original_weight_tensor.to(**kwargs), + self.input_quant_func, + ) + + def __torch_dispatch__(cls, func, types, args, kwargs): + if ( + func in [aten.mm.default, aten.addmm.default] + and args[0].is_floating_point() + ): + if func == aten.addmm.default: + assert args[1].shape[-1] == args[2].shape[0], ( + f"need mat1 shape: {args[1].shape} final" + f"dim to match mat2 shape: {args[2].shape} first dim " + ) + input_tensor, weight_tensor, bias = ( + args[1], + args[2], + args[0], + ) + input_quant_func = weight_tensor.input_quant_func + original_weight_tensor = weight_tensor.original_weight_tensor + aqt = input_quant_func(input_tensor) + return func(bias, aqt, original_weight_tensor) + else: + # aten.mm.default + assert args[0].shape[-1] == args[1].shape[0], ( + f"need mat1 shape: {args[0].shape} final dim" + f"to match mat2 shape: {args[1].shape} first dim" + ) + input_tensor, weight_tensor = ( + args[0], + args[1], + ) + input_quant_func = weight_tensor.input_quant_func + original_weight_tensor = weight_tensor.original_weight_tensor + aqt = input_quant_func(input_tensor) + return func(aqt, original_weight_tensor) + + if func is aten.detach.default: + return return_and_correct_aliasing( + func, args, kwargs, args[0]._apply_fn_to_data(torch.detach) + ) + + if func is aten.clone.default: + return return_and_correct_aliasing( + func, args, kwargs, args[0]._apply_fn_to_data(torch.clone) + ) + + if func is aten._to_copy.default: + return return_and_correct_aliasing( + func, + args, + kwargs, + args[0].to(*args[1:], **kwargs)._apply_fn_to_data(torch.clone), + ) + + if func is aten.t.default: + return return_and_correct_aliasing( + func, args, kwargs, args[0]._apply_fn_to_data(torch.t) + ) + + raise NotImplementedError( + f"LinearActQuantizedTensor dispatch: attempting to run {func}, this is not supported" + ) + +to_linear_act_quantized = LinearActQuantizedTensor.from_float diff --git a/videollama2/lib/python3.10/site-packages/torchao/quantization/utils.py b/videollama2/lib/python3.10/site-packages/torchao/quantization/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3e3943c93c3d8d248fd73b51579408ae8dfad3ee --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torchao/quantization/utils.py @@ -0,0 +1,458 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. +from typing import Dict, Optional, Tuple + +import torch +from torch.utils._python_dispatch import TorchDispatchMode +import torch.nn.utils.parametrize as parametrize +from torchao.utils import find_multiple +from .quant_primitives import ( + MappingType, + ZeroPointDomain, + choose_qparams_affine, + quantize_affine, + dequantize_affine, + int_scaled_matmul, +) + +__all__ = [ + "compute_error", + "_apply_logging_hook", + "quantize_activation_per_token_absmax", + "quant_int8_dynamic_per_token_linear", + "quant_int8_per_token_matmul", + "dynamically_quantize_per_channel", + "dequantize_per_tensor", + "dequantize_per_channel", + "get_groupwise_affine_qparams", + "pack_tinygemm_scales_and_zeros", + "unpack_tinygemm_scales_and_zeros", + "groupwise_affine_quantize_tensor_from_qparams", + "groupwise_affine_dequantize_tensor_from_qparams", + "groupwise_affine_quantize_tensor", + "groupwise_affine_dequantize_tensor", + "per_token_dynamic_quant", + "get_group_qparams_symmetric", +] + +try: + import lm_eval # pyre-ignore[21] # noqa: F401 + + _lm_eval_available = True +except: + _lm_eval_available = False + +# basic SQNR +def compute_error(x, y): + Ps = torch.linalg.norm(x) + Pn = torch.linalg.norm(x - y) + return 20 * torch.log10(Ps / Pn) + + +# logger for fqn + op + shape +# note: not safe for any kind of multithreading +_cur_fqn: Optional[str] = None + + +def _get_logging_hook(fqn): + + def forward_hook(module, input): + global _cur_fqn + _cur_fqn = fqn + + return forward_hook + + +def _apply_logging_hook(model): + for name, mod in model.named_modules(): + mod.register_forward_pre_hook(_get_logging_hook(name)) + + +# collections.defaultdict printing is weird with lambdas, so hand writing for now +_fqn_to_op_to_shape_to_count: Dict[ + Optional[str], Dict[Optional[str], Dict[Optional[str], int]] +] = {} + + +class LoggingTensorMode(TorchDispatchMode): + + def __torch_dispatch__(self, func, types, args=(), kwargs=None): + if kwargs is None: + kwargs = {} + rs = func(*args, **kwargs) + global _cur_fqn + op_name: str = f"{func.__module__}.{func.__name__}" + shape_str = "" + for arg in args: + if isinstance(arg, torch.Tensor): + shape_str += str(list(arg.shape)) + ", " + if shape_str != "": + shape_str = shape_str[:-2] + + if _cur_fqn not in _fqn_to_op_to_shape_to_count: + _fqn_to_op_to_shape_to_count[_cur_fqn] = {} + if op_name not in _fqn_to_op_to_shape_to_count[_cur_fqn]: + _fqn_to_op_to_shape_to_count[_cur_fqn][op_name] = {} + if shape_str not in _fqn_to_op_to_shape_to_count[_cur_fqn][op_name]: + _fqn_to_op_to_shape_to_count[_cur_fqn][op_name][shape_str] = 0 + _fqn_to_op_to_shape_to_count[_cur_fqn][op_name][shape_str] += 1 + + return rs + +class _MultiInput: + + def __init__(self, inputs): + + self.values = list(inputs) + + def add_input(self, input): + self.values.append(input) + return self + + def __getitem__(self, slice): + return _MultiInput(self.values[slice]) + + def cuda(self): + self.values = [ + val.cuda() if isinstance(val, torch.Tensor) else val for val in self.values + ] + + +def guard_dtype_size(tensor_arg, arg_name, dtype=None, size=None): + if dtype is not None and tensor_arg.dtype != dtype: + raise ValueError("Expected Tensor argument {arg_name} to have dtype {dtype}, but got {tensor_arg.dtype} instead.") + if size is not None and tensor_arg.size() != size: + raise ValueError("Expected Tensor argument {arg_name} to have size {size}, but got {tensor_arg.size()} instead.") + +# taken from +# https://github.com/mit-han-lab/smoothquant/blob/2f87951dacfb9238d8d657f52ae83a82a3c9ba0c/smoothquant/fake_quant.py#L26 +# and slightly modified +def quantize_activation_per_token_absmax(t): + # if the shape of t is [B, N, K], the shape of scales will be [B, N, 1] + mapping_type = MappingType.SYMMETRIC + block_size = list(t.shape) + for i in range(len(block_size) - 1): + block_size[i] = 1 + dtype = torch.int8 + eps = 1e-5 + # Note: the original smoothquant does not clamp to qmin/qmax here, + # but some of the tests with bfloat16 ended up with a flipped sign + # if we don't clamp. TODO(future) look into this further. + quant_min = -127 + quant_max = 127 + scale_dtype = torch.float32 if t.dtype == torch.float16 else None + + scale, zero_point = choose_qparams_affine(t, mapping_type, block_size, dtype, quant_min, quant_max, eps, scale_dtype=scale_dtype) + + quantized = quantize_affine(t, block_size, scale, zero_point, dtype, quant_min, quant_max) + + return quantized, scale + +def quant_int8_dynamic_per_token_linear( + x, + w_vals_int8_t, + w_scales, + bias, + out_dtype, +): + """ + like F.linear, but with int8 dynamic quantization of activation, + and a quantized weight + """ + x_vals_int8, x_scales = quantize_activation_per_token_absmax(x) + mm_out = quant_int8_per_token_matmul( + x_vals_int8, x_scales, w_vals_int8_t, w_scales, out_dtype + ) + if bias is not None: + mm_out = mm_out + bias + return mm_out + +def quant_int8_per_token_matmul( + x_vals_int8, + x_scales, + w_vals_int8_t, + w_scales, + output_dtype=torch.float32, +): + """ + Quantized matmul of int8 operands that accumulates to int32 and returns + output_dtype. For now, this is written for approximate numerical + Assumes that activation and weight quantization are symmetric, + i.e. act_zp and w_zp is 0. + Assumes that weight quantization is per-channel. + + see + https://github.com/google/gemmlowp/blob/master/doc/quantization.md + for an overview of quantized matmul compute + + in scalar form, assuming output_dtype is fp32 and zw == 0: + + Y_i_j_fp32 = sx * sw dot(X_i, W_j) + """ + + assert ( + x_vals_int8.dtype == torch.int8 + ), f"x dtype {x_vals_int8.dtype} not yet supported" + assert ( + w_vals_int8_t.dtype == torch.int8 + ), f"w dtype {w_vals_int8_t.dtype} not yet supported" + + assert x_scales.dtype in [ + torch.float, + torch.bfloat16, + ], f"x_scales needs to be a torch.float32 or torch.bfloat16 but got {x_scales.dtype}" + + # + # 1. do the matrix form of dot(X_i, W_j) + # + # + # 2. rescale the output + # + # in cases with large matrices, y_dot_int32 can grow sufficiently + # large that y_dot_int32 * a float16 scale is greater than the maximum + # value of a float 16, (which results in a value of inf even if multiplying + # by the other scale would bring it within the expected range) + + tmp = x_vals_int8.reshape(-1, x_vals_int8.shape[-1]) + y_dot_scaled = int_scaled_matmul(tmp, w_vals_int8_t, x_scales.reshape(-1, 1)) + + y = (y_dot_scaled * w_scales).reshape( + *x_vals_int8.shape[:-1], y_dot_scaled.shape[-1] + ) + + # can downcast only at the very end + y = y.to(output_dtype) + return y + +def dynamically_quantize_per_channel(x, quant_min, quant_max, target_dtype): + """ + assumes symmetric quantization + assumes axis == 0 + assumes dense memory format + TODO(future): relax ^ as needed + """ + + assert x.dim() == 2, "only support 2d Tensors" + + eps = torch.finfo(torch.float32).eps + block_size = (1, x.shape[1]) + zero_point_dtype = torch.int64 + + mapping_type = MappingType.SYMMETRIC + scale, zero_point = choose_qparams_affine(x, mapping_type, block_size, target_dtype=target_dtype, quant_min=quant_min, quant_max=quant_max, eps=eps, zero_point_dtype=zero_point_dtype) + quant = quantize_affine(x, block_size, scale, zero_point, target_dtype, quant_min, quant_max) + return quant, scale, zero_point + +# reference: https://fburl.com/code/vfsygwd0 +def dequantize_per_tensor(int_repr, scale, zero_point, out_dtype=torch.float32): + block_size = int_repr.shape + input_dtype = int_repr.dtype + assert scale.numel() == 1, f"scale size: {scale.numel()}" + dequantized = dequantize_affine(int_repr, block_size, scale, zero_point, input_dtype, output_dtype=out_dtype) + return dequantized + + +# reference: https://fburl.com/code/org0fmi3 +def dequantize_per_channel(int_repr, scales, zero_points, out_dtype=torch.float32): + assert int_repr.dim() == 2, "only support 2d Tensors" + # channel axis == 0 + # block_size before transpose should be (1, int_repr.shape[1]) for axis == 0 per channel quant + + # TODO: transpose is for perf reasons for torch.compile, we should separate this to lowering step + int_repr = int_repr.t() + # transpose for block_size as well + block_size = (int_repr.shape[0], 1) + input_dtype = int_repr.dtype + dequantized = dequantize_affine(int_repr, block_size, scales, zero_points, input_dtype, output_dtype=out_dtype) + dequantized = dequantized.t() + return dequantized + +def get_groupwise_affine_qparams(w, n_bit=4, groupsize=128, dtype=torch.bfloat16): + if groupsize > w.shape[-1]: + groupsize = w.shape[-1] + assert groupsize > 1 + assert w.shape[-1] % groupsize == 0 + assert w.dim() == 2 + assert n_bit <= 8, f"only n_bit smaller than 8 is supported, got: {n_bit}" + + mapping_type = MappingType.ASYMMETRIC + target_dtype = torch.int32 + block_size = (1, groupsize) + quant_min = 0 + quant_max = 2**n_bit - 1 + eps = 1e-6 + scale_dtype = dtype + zero_point_dtype = dtype + + scale, zero_point = choose_qparams_affine( + w, + mapping_type, + block_size, + target_dtype, + quant_min, + quant_max, + eps, + scale_dtype=scale_dtype, + zero_point_dtype=zero_point_dtype, + preserve_zero=False, + zero_point_domain=ZeroPointDomain.FLOAT + ) + + return scale.to(dtype=dtype).reshape(w.shape[0], -1), zero_point.to( + dtype=dtype + ).reshape(w.shape[0], -1) + + +def pack_tinygemm_scales_and_zeros(scales, zeros): + guard_dtype_size(scales, "scales", dtype=torch.bfloat16, size=zeros.size()) + guard_dtype_size(zeros, "zeros", dtype=torch.bfloat16) + return ( + torch.cat( + [ + scales.reshape(scales.size(0), scales.size(1), 1), + zeros.reshape(zeros.size(0), zeros.size(1), 1), + ], + 2, + ) + .transpose(0, 1) + .contiguous() + ) + + +def unpack_tinygemm_scales_and_zeros(scales_and_zeros): + assert len(scales_and_zeros.shape) == 3 and scales_and_zeros.shape[2] == 2 + return torch.split(scales_and_zeros.transpose(0, 1), 1, 2) + + +def groupwise_affine_quantize_tensor_from_qparams( + w, + scales, + zeros, + n_bit=4, + groupsize=128, +): + assert groupsize > 1 + # needed for GPTQ single column quantize + if groupsize > w.shape[-1] and scales.shape[-1] == 1: + groupsize = w.shape[-1] + + assert w.shape[-1] % groupsize == 0 + assert w.dim() == 2 + + block_size = (1, groupsize) + output_dtype = torch.int32 + quant_min = 0 + quant_max = 2 ** n_bit - 1 + + return quantize_affine(w, block_size, scales, zeros, output_dtype, quant_min, quant_max, zero_point_domain = ZeroPointDomain.FLOAT) + +def groupwise_affine_dequantize_tensor_from_qparams( + w_int4x8, + scales, + zeros, + n_bit=4, + groupsize=128, +): + assert groupsize > 1 + # needed for GPTQ single column dequantize + if groupsize > w_int4x8.shape[-1] and scales.shape[-1] == 1: + groupsize = w_int4x8.shape[-1] + assert w_int4x8.shape[-1] % groupsize == 0 + assert w_int4x8.dim() == 2 + + block_size = (1, groupsize) + input_dtype = torch.int32 + quant_min = 0 + quant_max = 2**n_bit - 1 + return dequantize_affine(w_int4x8, block_size, scales, zeros, input_dtype, quant_min, quant_max, zero_point_domain=ZeroPointDomain.FLOAT, output_dtype=scales.dtype) + + +def groupwise_affine_quantize_tensor(w, n_bit=4, groupsize=128, dtype=torch.bfloat16): + scales, zeros = get_groupwise_affine_qparams(w, n_bit, groupsize, dtype) + w_int4x8 = groupwise_affine_quantize_tensor_from_qparams( + w, scales, zeros, n_bit, groupsize + ) + scales_and_zeros = pack_tinygemm_scales_and_zeros(scales, zeros) + return w_int4x8, scales_and_zeros + + +def groupwise_affine_dequantize_tensor( + w_int4x8, + scales_and_zeros, + n_bit=4, + groupsize=128, +): + scales, zeros = unpack_tinygemm_scales_and_zeros(scales_and_zeros) + return groupwise_affine_dequantize_tensor_from_qparams( + w_int4x8, scales, zeros, n_bit, groupsize + ) + + +# TODO: separate scale and zero point precision +def get_group_qparams_symmetric(w, n_bit=4, groupsize=128, precision=torch.float32): + # needed for GPTQ with padding + if groupsize > w.shape[-1]: + groupsize = w.shape[-1] + assert groupsize > 1 + assert w.shape[-1] % groupsize == 0 + assert w.dim() == 2 + assert n_bit <= 8, f"unsupported n_bit: {n_bit}" + + mapping_type = MappingType.SYMMETRIC + block_size = (1, groupsize) + eps = torch.finfo(torch.float32).eps + ranges = {} + ranges[1] = (-1, 0) + # generating ranges for bit 2 to 8 + for i in range(2, 9): + ranges[i] = (-(2 ** (i - 1)), 2 ** (i - 1) - 1) + quant_min, quant_max = ranges[n_bit] + scale, zero_point = choose_qparams_affine(w, mapping_type, block_size, target_dtype=torch.int8, quant_min=quant_min, quant_max=quant_max, eps=eps, scale_dtype=precision, zero_point_dtype=precision) + return scale.reshape(w.shape[0], -1), zero_point.reshape(w.shape[0], -1) + + +def group_quantize_tensor_symmetric( + w, + n_bit=4, + group_size=128, + precision=torch.float32, +): + scales, zeros = get_group_qparams_symmetric(w, n_bit, group_size, precision) + n_bit = 4 + max_int = 2 ** (n_bit - 1) - 1 + min_int = -(2 ** (n_bit - 1)) + # TODO: currently we don't know how to express torch.int4, we'll + # add torch.int4 to core later + from torchao._executorch_ops import _quantized_decomposed_quantize_per_channel_group_wrapper + w_int8 = _quantized_decomposed_quantize_per_channel_group_wrapper( + w, scales, zeros, min_int, max_int, torch.int8, group_size + ) + + return w_int8, scales, zeros + +def per_token_dynamic_quant(input: torch.Tensor) -> torch.Tensor: + orig_dtype = input.dtype + # TODO: we may need to make the choose_qparams op configurable + from torchao._executorch_ops import _quantized_decomposed_choose_qparams_per_token_asymmetric_wrapper + ( + scales, + zero_points, + ) = _quantized_decomposed_choose_qparams_per_token_asymmetric_wrapper( + input, torch.int8 + ) + + # TODO: get these from torch.int8 + quant_min = -128 + quant_max = 127 + from torchao._executorch_ops import _quantized_decomposed_quantize_per_token_wrapper + input = _quantized_decomposed_quantize_per_token_wrapper( + input, scales, zero_points, quant_min, quant_max, torch.int8 + ) + from torchao._executorch_ops import _quantized_decomposed_dequantize_per_token_wrapper + input = _quantized_decomposed_dequantize_per_token_wrapper( + input, scales, zero_points, quant_min, quant_max, torch.int8, orig_dtype + ) + return input.to(orig_dtype) diff --git a/vllm/lib/python3.10/site-packages/torch/distributed/_composable/__init__.py b/vllm/lib/python3.10/site-packages/torch/distributed/_composable/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0f6f9ccfa27ee04f0138daa65df48470fe24d770 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/distributed/_composable/__init__.py @@ -0,0 +1,4 @@ +from .checkpoint_activation import checkpoint +from .contract import _get_registry, contract +from .fully_shard import fully_shard +from .replicate import replicate diff --git a/vllm/lib/python3.10/site-packages/torch/distributed/_composable/__pycache__/checkpoint_activation.cpython-310.pyc b/vllm/lib/python3.10/site-packages/torch/distributed/_composable/__pycache__/checkpoint_activation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..742a0b130e650c44782630d5d4d7c0f0177e7d06 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/torch/distributed/_composable/__pycache__/checkpoint_activation.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/torch/distributed/_composable/checkpoint_activation.py b/vllm/lib/python3.10/site-packages/torch/distributed/_composable/checkpoint_activation.py new file mode 100644 index 0000000000000000000000000000000000000000..88253abb4b9cbb6f31e5eb9cc25003d654d82ee1 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/distributed/_composable/checkpoint_activation.py @@ -0,0 +1,126 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +from contextlib import contextmanager, nullcontext +from typing import Any, ContextManager, Dict, Optional, Tuple + +import torch +import torch.nn as nn +from torch.utils.checkpoint import ( + _checkpoint_without_reentrant_generator, + _DEFAULT_DETERMINISM_MODE, +) + +from .contract import contract + + +@contextmanager +def _no_hook(module: nn.Module, user_ctx: Optional[ContextManager] = None): + r""" + Disable hooks installed by checkpoint to avoid unintentional recursion + during backward recomputation. + """ + + with user_ctx if user_ctx else nullcontext(): + orig_enable_hook = checkpoint.state(module).enable_hook + checkpoint.state(module).enable_hook = False + try: + yield + finally: + checkpoint.state(module).enable_hook = orig_enable_hook + + +@contract() +def checkpoint(module: nn.Module, **kwargs) -> nn.Module: + r""" + This is a composable activation checkpointing API. Unlike functional + activation checkpointing APIs, this one does not require changing model + source code. Unlike ``nn.Module`` wrapper activation checkpointing APIs, + this one does not modify model structure or fully-qualified names either. + Under the hood, it registers activation checkpointing logic as pre- and + post-forward hooks. Hence, this API can be easily applied to any model or + sub-modules in the model. + + Args: + module (nn.Module): the target model or sub-module to apply activation + checkpointing. + + Example:: + >>> # xdoctest: +SKIP + >>> import torch.nn as nn + >>> + >>> class MyModel(nn.Module): + >>> def __init__(self) -> None: + >>> super().__init__() + >>> self.l1 = nn.Linear(10, 10) + >>> self.l2 = nn.Linear(10, 10) + >>> + >>> def forward(self, x): + >>> return self.l2(self.l1(x)) + >>> + >>> model = MyModel() + >>> checkpoint(model.l1) # apply activation checkpointing only to l1 + >>> model(torch.zeros(2, 10)).sum().backward() + + """ + torch._C._log_api_usage_once("torch.distributed.checkpoint") + + use_reentrant = kwargs.pop("use_reentrant", False) + if use_reentrant: + raise NotImplementedError( + "use_reentrant=True is not supported in composable checkpoint. " + "Please use torch.utils.checkpoint.checkpoint instead." + ) + preserve_rng_state = kwargs.pop("preserve_rng_state", True) + user_context_fns = kwargs.pop("context_fn", None) + determinism_check = kwargs.pop("determinism_check", _DEFAULT_DETERMINISM_MODE) + debug = kwargs.pop("debug", False) + + if kwargs: + raise ValueError( + "Unexpected keyword arguments: " + ",".join(arg for arg in kwargs) + ) + + def forward_pre_hook( + module: nn.Module, args: Tuple[Any, ...], kwargs: Dict[str, Any] + ) -> None: + if checkpoint.state(module).enable_hook: + + def context_fns(): + if user_context_fns is not None: + ctx1, ctx2 = user_context_fns() + return ctx1, _no_hook(module, ctx2) + else: + return nullcontext(), _no_hook(module) + + checkpoint.state( + module + )._ac_generator = _checkpoint_without_reentrant_generator( + module, + preserve_rng_state, + context_fns, + determinism_check, + debug, + *args, + **kwargs, + ) + next(checkpoint.state(module)._ac_generator) + + def forward_hook(module: nn.Module, inputs: Tuple[Any, ...], output: Any) -> Any: + if checkpoint.state(module).enable_hook: + try: + next(checkpoint.state(module)._ac_generator) + except StopIteration: + pass + else: + raise RuntimeError( + "Expected non-reentrant activation checkpoint generator to be exhausted, but it was not!" + ) + + # Ensure that we no longer hold on to the generator. always_call=True helps ensure we + # clear this even in the case of exception in fwd pass. + checkpoint.state(module)._ac_generator = None + + checkpoint.state(module).enable_hook = True + module.register_forward_pre_hook(forward_pre_hook, with_kwargs=True) + module.register_forward_hook(forward_hook, prepend=True, always_call=True) + return module diff --git a/vllm/lib/python3.10/site-packages/torch/distributed/_composable/fsdp/_fsdp_common.py b/vllm/lib/python3.10/site-packages/torch/distributed/_composable/fsdp/_fsdp_common.py new file mode 100644 index 0000000000000000000000000000000000000000..31b74079aaa8be31ef27ddcccf6ead55a56ac2f2 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/distributed/_composable/fsdp/_fsdp_common.py @@ -0,0 +1,152 @@ +# mypy: allow-untyped-defs +import math +import traceback +from dataclasses import dataclass +from enum import auto, Enum +from typing import Any, cast, List, Optional + +import torch +import torch._dynamo.compiled_autograd as ca +import torch.distributed as dist +import torch.nn as nn +from torch.distributed._composable.contract import _get_registry +from torch.distributed.tensor import DeviceMesh, DTensor +from torch.distributed.tensor._dtensor_spec import DTensorSpec + + +@dataclass +class DataParallelMeshInfo: + mesh: DeviceMesh + shard_mesh_dim: Optional[int] = None + replicate_mesh_dim: Optional[int] = None + + def __post_init__(self): + if self.shard_mesh_dim is None and self.replicate_mesh_dim is None: + raise AssertionError( + "At least one of shard_mesh_dim and replicate_mesh_dim must not be None" + ) + + +@dataclass +class FSDPMeshInfo(DataParallelMeshInfo): + def __post_init__(self): + super().__post_init__() + if self.shard_mesh_dim is None: + raise AssertionError("Expects non-None shard_mesh_dim") + self.shard_mesh_size: int = self.mesh.size(self.shard_mesh_dim) + self.shard_process_group = self.mesh.get_group(self.shard_mesh_dim) + self.shard_mesh_rank: int = self.shard_process_group.rank() + + +@dataclass +class DDPMeshInfo(DataParallelMeshInfo): + def __post_init__(self): + super().__post_init__() + if self.replicate_mesh_dim is None: + raise AssertionError("Expects non-None replicate_mesh_dim") + self.replicate_mesh_size: int = self.mesh.size(self.replicate_mesh_dim) + self.replicate_process_group = self.mesh.get_group(self.replicate_mesh_dim) + self.replicate_mesh_rank: int = self.replicate_process_group.rank() + + +@dataclass +class HSDPMeshInfo(FSDPMeshInfo, DDPMeshInfo): + def __post_init__(self): + # Calls `FSDPMeshInfo` -> `DDPMeshInfo` -> `DataParallelMeshInfo` + super().__post_init__() + + +class TrainingState(Enum): + """Describes the training state of one FSDP state / parameter group.""" + + # Transition to forward starting pre-forward until post-forward + FORWARD = auto() + # Transition to pre-backward when unsharding in backward + PRE_BACKWARD = auto() + # Transition to post-backward when resharding and reducing gradients + POST_BACKWARD = auto() + # Idle before/after forward or before pre-backward/after post-backward + IDLE = auto() + + +def _raise_assert_with_print(*args: Any, **kwargs: Any): + print(f"[Rank {dist.get_rank()}] ", end="") + print(*args, **kwargs) + traceback.print_stack() + raise AssertionError(*args, **kwargs) + + +def _is_composable_with_fsdp(module: nn.Module) -> bool: + registry = _get_registry(module) + if registry is None: + return True + # Registry keys by function name + return "replicate" not in registry + + +def _get_dim0_padded_size(tensor_size: torch.Size, dim0_factor: int) -> torch.Size: + padded_dim0 = math.ceil(tensor_size[0] / dim0_factor) * dim0_factor + return cast(torch.Size, torch.Size([padded_dim0]) + tensor_size[1:]) + + +def _chunk_with_empty( + tensor: torch.Tensor, num_chunks: int, dim: int +) -> List[torch.Tensor]: + chunks = list(torch.chunk(tensor, num_chunks, dim=dim)) + while len(chunks) < num_chunks: + chunks.append(chunks[0].new_empty(0)) + return chunks + + +def _get_dim0_chunked_size( + chunk: torch.Tensor, unchunked_size: torch.Size +) -> torch.Size: + if chunk.numel() > 0: + return chunk.size() + # For 0 numel, we need to preserve trailing dims for DTensor APIs + return cast(torch.Size, torch.Size([0]) + unchunked_size[1:]) + + +def _from_local_no_grad( + local_tensor: torch.Tensor, + sharding_spec: DTensorSpec, +) -> DTensor: + """ + This method is similar to ``DTensor.from_local()`` except that in eager mode + it avoids some CPU overhead by avoiding default args and not being differentiable. + """ + + if not ca.compiled_autograd_enabled: + return DTensor( + # Use the local tensor directly instead of constructing a new tensor + # variable, e.g. with `view_as()`, since this is not differentiable + local_tensor, + sharding_spec, + requires_grad=local_tensor.requires_grad, + ) + else: + return DTensor.from_local( + local_tensor, + sharding_spec.mesh, + sharding_spec.placements, + shape=sharding_spec.shape, + stride=sharding_spec.stride, + ) + + +def _to_dtype_if_needed( + tensor: torch.Tensor, dtype: Optional[torch.dtype] +) -> torch.Tensor: + if dtype is not None and tensor.dtype != dtype: + return tensor.to(dtype) + return tensor + + +def _cast_fp_tensor(dtype: torch.dtype, x: torch.Tensor) -> torch.Tensor: + if ( + not isinstance(x, torch.Tensor) + or not torch.is_floating_point(x) + or x.dtype == dtype + ): + return x + return x.to(dtype) diff --git a/vllm/lib/python3.10/site-packages/torch/distributed/_composable/fully_shard.py b/vllm/lib/python3.10/site-packages/torch/distributed/_composable/fully_shard.py new file mode 100644 index 0000000000000000000000000000000000000000..4afa0f431075f7499b5808161fb42925494f1185 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/distributed/_composable/fully_shard.py @@ -0,0 +1,131 @@ +# mypy: allow-untyped-decorators +from typing import Callable, Iterable, Optional, Union +from typing_extensions import deprecated + +import torch +import torch.distributed as dist +import torch.nn as nn +from torch.distributed._composable.contract import contract +from torch.distributed._composable_state import _get_module_state, _insert_module_state +from torch.distributed.fsdp._common_utils import _FSDPState +from torch.distributed.fsdp._dynamo_utils import _annotate_modules_for_dynamo +from torch.distributed.fsdp._init_utils import ( + _init_buffer_state, + _init_core_state, + _init_device_handle, + _init_ignored_module_states, + _init_param_handle_from_module, + _init_prefetching_state, + _init_process_group_state, + _init_runtime_state, + _init_state_dict_state, + HYBRID_SHARDING_STRATEGIES, +) +from torch.distributed.fsdp._runtime_utils import ( + _register_post_forward_hook, + _register_pre_forward_hook, + _register_root_pre_forward_hook, +) +from torch.distributed.fsdp._state_dict_utils import _register_all_state_dict_hooks +from torch.distributed.fsdp._wrap_utils import _auto_wrap +from torch.distributed.fsdp.api import ( + BackwardPrefetch, + CPUOffload, + MixedPrecision, + ShardingStrategy, +) +from torch.distributed.fsdp.wrap import _Policy + + +@contract(state_cls=_FSDPState) +@deprecated( + "`torch.distributed._composable.fully_shard` is being deprecated. " + "You can continue to use the wrapper based FSDP. " + "See usage in: https://github.com/pytorch/pytorch/blob/main/torch/distributed/fsdp/fully_sharded_data_parallel.py. " + "`torch.distributed._composable.fully_shard` will be removed after PyTorch 2.5.", + category=FutureWarning, +) +def fully_shard( + module: nn.Module, + *, + process_group: Optional[dist.ProcessGroup] = None, + policy: Optional[_Policy] = None, + strategy: Optional[ShardingStrategy] = None, + mixed_precision: Optional[MixedPrecision] = None, + cpu_offload: Optional[CPUOffload] = None, + ignored_modules: Optional[Iterable[torch.nn.Module]] = None, + device_id: Optional[Union[int, torch.device]] = None, + param_init_fn: Optional[Callable[[nn.Module], None]] = None, + sync_module_states: bool = False, + forward_prefetch: bool = False, + ignored_states: Union[ + Optional[Iterable[torch.nn.Parameter]], Optional[Iterable[torch.nn.Module]] + ] = None, +) -> nn.Module: + """Applies ``FullyShardedDataParallel`` (FSDP) semantics to ``module``.""" + torch._C._log_api_usage_once("torch.distributed.fully_shard") + # Enforce the new auto wrap policy + if policy is not None and not isinstance(policy, _Policy): + raise ValueError(f"Expects a `_Policy` but got {policy}") + state = fully_shard.state(module) + state = _init_ignored_module_states(state, module, ignored_modules, ignored_states) + state = _init_device_handle(state, module, state._ignored_params, device_id) + _annotate_modules_for_dynamo(module, state._ignored_modules, True) + state = _init_process_group_state(state, process_group, strategy, policy) + if policy is not None: + root_kwargs = { + "process_group": process_group, + "strategy": strategy, + "mixed_precision": mixed_precision, + "cpu_offload": cpu_offload, + "ignored_modules": ignored_modules, + "device_id": device_id, + "param_init_fn": param_init_fn, + "sync_module_states": sync_module_states, + "forward_prefetch": forward_prefetch, + "ignored_states": ignored_states, + } + if strategy in HYBRID_SHARDING_STRATEGIES: + root_kwargs["process_group"] = (state.process_group, state._inter_node_pg) + _auto_wrap( + module, + policy, + state._ignored_modules, + state._ignored_params, + root_kwargs, + fully_shard, + ) + state = _init_core_state( + state, + strategy or ShardingStrategy.FULL_SHARD, + mixed_precision, + cpu_offload, + limit_all_gathers=True, + use_orig_params=True, + backward_prefetch_limit=1, + forward_prefetch_limit=1, + ) + state = _init_runtime_state(state) + state = _init_prefetching_state( + state, BackwardPrefetch.BACKWARD_PRE, forward_prefetch=forward_prefetch + ) + state = _init_buffer_state(state, module) + state = _init_param_handle_from_module( + state, module, device_id, param_init_fn, sync_module_states + ) + state = _init_state_dict_state(state) + _register_all_state_dict_hooks(state) + _register_pre_forward_hook(state, module) + _register_post_forward_hook(state, module) + _register_root_pre_forward_hook(state, module) # prepend last + # Always insert the state for the passed-in module even if it has no + # managed parameters, in which case it has no handles and does not appear + # in `_fully_sharded_module_to_handles` + _insert_module_state(module, state) + for submodule in module.modules(): + if ( + submodule in state._fully_sharded_module_to_handle + and _get_module_state(submodule) is None + ): + _insert_module_state(submodule, state) + return module diff --git a/vllm/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/rref_proxy.cpython-310.pyc b/vllm/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/rref_proxy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85ec8a4e756ca3be5f96337a6369452866a0a664 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/rref_proxy.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/torch/distributed/rpc/_testing/__init__.py b/vllm/lib/python3.10/site-packages/torch/distributed/rpc/_testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8ac1c02f4cee4c38c896cacd245b9ededf9a8a29 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/distributed/rpc/_testing/__init__.py @@ -0,0 +1,20 @@ +# mypy: allow-untyped-defs + +import torch + + +def is_available(): + return hasattr(torch._C, "_faulty_agent_init") + + +if is_available() and not torch._C._faulty_agent_init(): + raise RuntimeError("Failed to initialize torch.distributed.rpc._testing") + +if is_available(): + # Registers FAULTY_TENSORPIPE RPC backend. + from torch._C._distributed_rpc_testing import ( + FaultyTensorPipeAgent, + FaultyTensorPipeRpcBackendOptions, + ) + + from . import faulty_agent_backend_registry diff --git a/vllm/lib/python3.10/site-packages/torch/distributed/rpc/_testing/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/torch/distributed/rpc/_testing/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ff8d93cfd49f5e187eac34ae92fb465cc6ecfcd Binary files /dev/null and b/vllm/lib/python3.10/site-packages/torch/distributed/rpc/_testing/__pycache__/__init__.cpython-310.pyc differ