diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/__pycache__/app.cpython-311.pyc b/__pycache__/app.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6c9fdec82bcf53b765e1b6e5c246c9ebf06a0cc Binary files /dev/null and b/__pycache__/app.cpython-311.pyc differ diff --git a/app.py b/app.py new file mode 100644 index 0000000000000000000000000000000000000000..308be2c61eb5f9565054c675398635187976bc1c --- /dev/null +++ b/app.py @@ -0,0 +1,113 @@ +import sys +import os +import argparse +import time +import subprocess + + +# subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-e','.']) + +import llava.serve.gradio_web_server as gws + +# Execute the pip install command with additional options + + +subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'flash-attn', '--no-build-isolation', '-U']) + + +def start_controller(): + print("Starting the controller") + controller_command = [ + sys.executable, + "-m", + "llava.serve.controller", + "--host", + "0.0.0.0", + "--port", + "10000", + ] + print(controller_command) + return subprocess.Popen(controller_command) + + +def start_worker(model_path: str, bits=4): + print(f"Starting the model worker for the model {model_path}") + model_name = model_path.strip("/").split("/")[-1] + assert bits in [4, 8, 16], "It can be only loaded with 16-bit, 8-bit, and 4-bit." + if bits != 16: + model_name += f"-{bits}bit" + worker_command = [ + sys.executable, + "-m", + "llava.serve.model_worker", + "--host", + "0.0.0.0", + "--controller", + "http://localhost:10000", + "--model-path", + model_path, + "--model-name", + 'llava-v1.5-UGround_v1', + "--use-flash-attn", + ] + if bits != 16: + worker_command += [f"--load-{bits}bit"] + print(worker_command) + return subprocess.Popen(worker_command) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--host", type=str, default="0.0.0.0") + parser.add_argument("--port", type=int) + parser.add_argument("--controller-url", type=str, default="http://localhost:10000") + parser.add_argument("--concurrency-count", type=int, default=1) + parser.add_argument("--model-list-mode", type=str, default="reload", choices=["once", "reload"]) + parser.add_argument("--share", action="store_true") + parser.add_argument("--moderate", action="store_true") + parser.add_argument("--embed", action="store_true") + gws.args = parser.parse_args() + gws.models = [] + + gws.title_markdown += """ +This is a demo for UGround from *Navigating the Digital World as Humans Do: Universal Visual Grounding for GUI Agents*. We load the 4bit model by default. +""" + + print(f"args: {gws.args}") + + # model_path = os.getenv("model", "osunlp/UGround") + model_path = "osunlp/UGround" + # "osunlp/UGround" + bits = int(os.getenv("bits", 4)) + concurrency_count = int(os.getenv("concurrency_count", 1)) + + controller_proc = start_controller() + worker_proc = start_worker(model_path, bits=bits) + + # Wait for worker and controller to start + time.sleep(10) + + exit_status = 0 + try: + demo = gws.build_demo(embed_mode=False, cur_dir='./', concurrency_count=concurrency_count) + demo.queue( + status_update_rate=10, + api_open=False + ).launch( + server_name=gws.args.host, + server_port=gws.args.port, + share=gws.args.share + ) + + except Exception as e: + print(e) + exit_status = 1 + finally: + worker_proc.kill() + controller_proc.kill() + + sys.exit(exit_status) + + +#preload_from_hub: +# - "osunlp/UGround" \ No newline at end of file diff --git a/controller.log b/controller.log new file mode 100644 index 0000000000000000000000000000000000000000..5fa7228a770cd4637042726e1eeb503cea9a66ec --- /dev/null +++ b/controller.log @@ -0,0 +1,81 @@ +2024-10-09 14:33:33 | INFO | controller | args: Namespace(host='0.0.0.0', port=10000, dispatch_method='shortest_queue') +2024-10-09 14:33:33 | INFO | controller | Init controller +2024-10-09 14:33:33 | ERROR | stderr | INFO: Started server process [67560] +2024-10-09 14:33:33 | ERROR | stderr | INFO: Waiting for application startup. +2024-10-09 14:33:33 | ERROR | stderr | INFO: Application startup complete. +2024-10-09 14:33:33 | ERROR | stderr | INFO: Uvicorn running on http://0.0.0.0:10000 (Press CTRL+C to quit) +2024-10-09 14:34:27 | ERROR | stderr | INFO: Shutting down +2024-10-09 14:34:27 | ERROR | stderr | INFO: Waiting for application shutdown. +2024-10-09 14:34:27 | ERROR | stderr | INFO: Application shutdown complete. +2024-10-09 14:34:27 | ERROR | stderr | INFO: Finished server process [67560] +2024-10-09 14:34:36 | INFO | controller | args: Namespace(host='0.0.0.0', port=10000, dispatch_method='shortest_queue') +2024-10-09 14:34:36 | INFO | controller | Init controller +2024-10-09 14:34:36 | ERROR | stderr | INFO: Started server process [67981] +2024-10-09 14:34:36 | ERROR | stderr | INFO: Waiting for application startup. +2024-10-09 14:34:36 | ERROR | stderr | INFO: Application startup complete. +2024-10-09 14:34:36 | ERROR | stderr | INFO: Uvicorn running on http://0.0.0.0:10000 (Press CTRL+C to quit) +2024-10-09 14:38:20 | ERROR | stderr | INFO: Shutting down +2024-10-09 14:38:21 | ERROR | stderr | INFO: Waiting for application shutdown. +2024-10-09 14:38:21 | ERROR | stderr | INFO: Application shutdown complete. +2024-10-09 14:38:21 | ERROR | stderr | INFO: Finished server process [67981] +2024-10-09 14:38:29 | INFO | controller | args: Namespace(host='0.0.0.0', port=10000, dispatch_method='shortest_queue') +2024-10-09 14:38:29 | INFO | controller | Init controller +2024-10-09 14:38:29 | ERROR | stderr | INFO: Started server process [68570] +2024-10-09 14:38:29 | ERROR | stderr | INFO: Waiting for application startup. +2024-10-09 14:38:29 | ERROR | stderr | INFO: Application startup complete. +2024-10-09 14:38:29 | ERROR | stderr | INFO: Uvicorn running on http://0.0.0.0:10000 (Press CTRL+C to quit) +2024-10-09 14:39:53 | INFO | controller | args: Namespace(host='0.0.0.0', port=10000, dispatch_method='shortest_queue') +2024-10-09 14:39:53 | INFO | controller | Init controller +2024-10-09 14:39:53 | ERROR | stderr | INFO: Started server process [68631] +2024-10-09 14:39:53 | ERROR | stderr | INFO: Waiting for application startup. +2024-10-09 14:39:53 | ERROR | stderr | INFO: Application startup complete. +2024-10-09 14:39:53 | ERROR | stderr | INFO: Uvicorn running on http://0.0.0.0:10000 (Press CTRL+C to quit) +2024-10-09 14:39:59 | INFO | stdout | INFO: 127.0.0.1:58494 - "GET / HTTP/1.1" 404 Not Found +2024-10-09 14:40:33 | INFO | controller | args: Namespace(host='0.0.0.0', port=10000, dispatch_method='shortest_queue') +2024-10-09 14:40:33 | INFO | controller | Init controller +2024-10-09 14:40:33 | ERROR | stderr | INFO: Started server process [68681] +2024-10-09 14:40:33 | ERROR | stderr | INFO: Waiting for application startup. +2024-10-09 14:40:33 | ERROR | stderr | INFO: Application startup complete. +2024-10-09 14:40:33 | ERROR | stderr | INFO: Uvicorn running on http://0.0.0.0:10000 (Press CTRL+C to quit) +2024-10-09 14:40:41 | INFO | stdout | INFO: 127.0.0.1:58574 - "GET / HTTP/1.1" 404 Not Found +2024-10-09 14:47:47 | ERROR | stderr | INFO: Shutting down +2024-10-09 14:47:48 | ERROR | stderr | INFO: Waiting for application shutdown. +2024-10-09 14:47:48 | ERROR | stderr | INFO: Application shutdown complete. +2024-10-09 14:47:48 | ERROR | stderr | INFO: Finished server process [68681] +2024-10-09 14:47:54 | INFO | controller | args: Namespace(host='0.0.0.0', port=10000, dispatch_method='shortest_queue') +2024-10-09 14:47:54 | INFO | controller | Init controller +2024-10-09 14:47:54 | ERROR | stderr | INFO: Started server process [69107] +2024-10-09 14:47:54 | ERROR | stderr | INFO: Waiting for application startup. +2024-10-09 14:47:54 | ERROR | stderr | INFO: Application startup complete. +2024-10-09 14:47:54 | ERROR | stderr | INFO: Uvicorn running on http://0.0.0.0:10000 (Press CTRL+C to quit) +2024-10-09 14:48:02 | INFO | stdout | INFO: 127.0.0.1:59180 - "GET / HTTP/1.1" 404 Not Found +2024-10-09 14:50:56 | INFO | controller | args: Namespace(host='0.0.0.0', port=10000, dispatch_method='shortest_queue') +2024-10-09 14:50:56 | INFO | controller | Init controller +2024-10-09 14:50:56 | ERROR | stderr | INFO: Started server process [69357] +2024-10-09 14:50:56 | ERROR | stderr | INFO: Waiting for application startup. +2024-10-09 14:50:56 | ERROR | stderr | INFO: Application startup complete. +2024-10-09 14:50:56 | ERROR | stderr | INFO: Uvicorn running on http://0.0.0.0:10000 (Press CTRL+C to quit) +2024-10-09 14:51:43 | INFO | controller | args: Namespace(host='0.0.0.0', port=10000, dispatch_method='shortest_queue') +2024-10-09 14:51:43 | INFO | controller | Init controller +2024-10-09 14:51:43 | ERROR | stderr | INFO: Started server process [69433] +2024-10-09 14:51:43 | ERROR | stderr | INFO: Waiting for application startup. +2024-10-09 14:51:43 | ERROR | stderr | INFO: Application startup complete. +2024-10-09 14:51:43 | ERROR | stderr | INFO: Uvicorn running on http://0.0.0.0:10000 (Press CTRL+C to quit) +2024-10-09 14:53:04 | INFO | controller | args: Namespace(host='0.0.0.0', port=10000, dispatch_method='shortest_queue') +2024-10-09 14:53:04 | INFO | controller | Init controller +2024-10-09 14:53:04 | ERROR | stderr | INFO: Started server process [69542] +2024-10-09 14:53:04 | ERROR | stderr | INFO: Waiting for application startup. +2024-10-09 14:53:04 | ERROR | stderr | INFO: Application startup complete. +2024-10-09 14:53:04 | ERROR | stderr | INFO: Uvicorn running on http://0.0.0.0:10000 (Press CTRL+C to quit) +2024-10-09 14:53:57 | INFO | controller | args: Namespace(host='0.0.0.0', port=10000, dispatch_method='shortest_queue') +2024-10-09 14:53:57 | INFO | controller | Init controller +2024-10-09 14:53:57 | ERROR | stderr | INFO: Started server process [69660] +2024-10-09 14:53:57 | ERROR | stderr | INFO: Waiting for application startup. +2024-10-09 14:53:57 | ERROR | stderr | INFO: Application startup complete. +2024-10-09 14:53:57 | ERROR | stderr | INFO: Uvicorn running on http://0.0.0.0:10000 (Press CTRL+C to quit) +2024-10-09 14:54:37 | INFO | controller | args: Namespace(host='0.0.0.0', port=10000, dispatch_method='shortest_queue') +2024-10-09 14:54:37 | INFO | controller | Init controller +2024-10-09 14:54:37 | ERROR | stderr | INFO: Started server process [69742] +2024-10-09 14:54:37 | ERROR | stderr | INFO: Waiting for application startup. +2024-10-09 14:54:37 | ERROR | stderr | INFO: Application startup complete. +2024-10-09 14:54:37 | ERROR | stderr | INFO: Uvicorn running on http://0.0.0.0:10000 (Press CTRL+C to quit) diff --git a/data/prompts/complex_reasoning/000_caps.txt b/data/prompts/complex_reasoning/000_caps.txt new file mode 100644 index 0000000000000000000000000000000000000000..358155c384a2d18e6927d62562ac3f12eef36a87 --- /dev/null +++ b/data/prompts/complex_reasoning/000_caps.txt @@ -0,0 +1,18 @@ +A man wearing multiple neck ties making a goofy face. +A man in a white shirt wearing very many ties. +a man with ties on poses for a picture +A man wearing multiple ties on his neck. +A young man smiles while wearing several ties. + +tie: [0.574, 0.298, 0.752, 0.704] +tie: [0.464, 0.339, 0.639, 0.789] +tie: [0.349, 0.363, 0.563, 0.732] +tie: [0.259, 0.255, 0.668, 0.805] +person: [0.019, 0.065, 0.962, 0.988] +person: [0.0, 0.24, 0.214, 1.0] +tie: [0.316, 0.778, 0.443, 0.867] +tie: [0.386, 0.707, 0.496, 0.801] +tie: [0.251, 0.354, 0.402, 0.747] +tie: [0.44, 0.318, 0.63, 0.397] +tie: [0.566, 0.33, 0.655, 0.543] +tie: [0.25, 0.409, 0.359, 0.556] \ No newline at end of file diff --git a/data/prompts/complex_reasoning/000_conv.txt b/data/prompts/complex_reasoning/000_conv.txt new file mode 100644 index 0000000000000000000000000000000000000000..04f47a91a74af9ba5686107fb6a4441117494a56 --- /dev/null +++ b/data/prompts/complex_reasoning/000_conv.txt @@ -0,0 +1,5 @@ +Question: +What is unusual about this photo? +=== +Answer: +In the photo, the man is wearing a total of ten ties around his neck. This is considered unusual because it is not common for someone to wear multiple ties at once. In a typical setting, a person would wear only one tie. The man's goofy facial expression also adds to the unconventional and humorous nature of the image. \ No newline at end of file diff --git a/data/prompts/complex_reasoning/001_caps.txt b/data/prompts/complex_reasoning/001_caps.txt new file mode 100644 index 0000000000000000000000000000000000000000..2065dfb20a6e40128749d507ecc27d01349e2ad9 --- /dev/null +++ b/data/prompts/complex_reasoning/001_caps.txt @@ -0,0 +1,18 @@ +A group of people standing outside of a black vehicle with various luggage. +Luggage surrounds a vehicle in an underground parking area +People try to fit all of their luggage in an SUV. +The sport utility vehicle is parked in the public garage, being packed for a trip +Some people with luggage near a van that is transporting it. + +person: [0.681, 0.242, 0.774, 0.694] +person: [0.63, 0.222, 0.686, 0.516] +person: [0.444, 0.233, 0.487, 0.34] +backpack: [0.384, 0.696, 0.485, 0.914] +backpack: [0.755, 0.413, 0.846, 0.692] +suitcase: [0.758, 0.413, 0.845, 0.69] +suitcase: [0.1, 0.497, 0.173, 0.579] +bicycle: [0.282, 0.363, 0.327, 0.442] +car: [0.786, 0.25, 0.848, 0.322] +car: [0.783, 0.27, 0.827, 0.335] +car: [0.86, 0.254, 0.891, 0.3] +car: [0.261, 0.101, 0.787, 0.626] \ No newline at end of file diff --git a/data/prompts/complex_reasoning/001_conv.txt b/data/prompts/complex_reasoning/001_conv.txt new file mode 100644 index 0000000000000000000000000000000000000000..b293aecb87839015f8ab37943afe71c2f8904871 --- /dev/null +++ b/data/prompts/complex_reasoning/001_conv.txt @@ -0,0 +1,5 @@ +Question: +What challenges do these people face? +=== +Answer: +In the image, a group of people is standing outside a black SUV in a parking area, surrounded by various pieces of luggage, including suitcases and backpacks. They are facing the challenge of fitting all their luggage into the black SUV. There are multiple suitcases and backpacks to be packed, which suggests that the group has a significant amount of belongings to accommodate. They might have to strategize and arrange the luggage efficiently to ensure that everything fits properly into the vehicle. Additionally, they need to consider the comfort of the passengers and visibility while driving, so the placement of the luggage must not obstruct the driver's view or make the passengers uncomfortable during the trip. \ No newline at end of file diff --git a/data/prompts/complex_reasoning/002_caps.txt b/data/prompts/complex_reasoning/002_caps.txt new file mode 100644 index 0000000000000000000000000000000000000000..8fb59f2eb46c7e0db50d2994b2e9102d46def656 --- /dev/null +++ b/data/prompts/complex_reasoning/002_caps.txt @@ -0,0 +1,7 @@ +There is a movie theater that displays the show times above the doors. +A red fire hydrant is deep in the snow. +The fire hydrant is in the snow near a recently plowed sidewalk. +This city has had a very hard winter with snow. +A hotel for dogs in the snow in winter. + +fire hydrant: [0.326, 0.612, 0.426, 0.72] \ No newline at end of file diff --git a/data/prompts/complex_reasoning/002_conv.txt b/data/prompts/complex_reasoning/002_conv.txt new file mode 100644 index 0000000000000000000000000000000000000000..8a2c7f35b9fe3961f0d974ee4799fa517922df83 --- /dev/null +++ b/data/prompts/complex_reasoning/002_conv.txt @@ -0,0 +1,5 @@ +Question: +What challenges might this city face? +=== +Answer: +The city faces challenges due to the harsh winter conditions and heavy snowfall. In the image, a red fire hydrant is almost buried deep in the snow, which indicates the significant amount of snow the city has experienced. This can lead to various challenges such as difficulties in transportation, increased risk of accidents, and disruptions to daily life. For example, the recently plowed sidewalk near the fire hydrant shows that the city has to constantly clear snow from roads and sidewalks to maintain access and safety for pedestrians and vehicles. Moreover, emergency services, like firefighters, might face challenges accessing crucial equipment, such as fire hydrants, during emergencies due to the snow accumulation. This highlights the importance of effective snow management strategies and preparedness in such cities to minimize the impact of harsh winter conditions on residents and essential services. \ No newline at end of file diff --git a/data/prompts/complex_reasoning/system_message.txt b/data/prompts/complex_reasoning/system_message.txt new file mode 100644 index 0000000000000000000000000000000000000000..a394efd653554ce687ab8f0c908238bef4f27dee --- /dev/null +++ b/data/prompts/complex_reasoning/system_message.txt @@ -0,0 +1,10 @@ +You are an AI visual assistant that can analyze a single image. You receive five sentences, each describing the same image you are observing. In addition, specific object locations within the image are given, along with detailed coordinates. These coordinates are in the form of bounding boxes, represented as (x1, y1, x2, y2) with floating numbers ranging from 0 to 1. These values correspond to the top left x, top left y, bottom right x, and bottom right y. + +The task is to use the provided caption and bounding box information, create a plausible question about the image, and provide the answer in detail. + +Create complex questions beyond describing the scene. +To answer such questions, one should require first understanding the visual content, then based on the background knowledge or reasoning, either explain why the things are happening that way, or provide guides and help to user's request. Make the question challenging by not including the visual content details in the question so that the user needs to reason about that first. + +Instead of directly mentioning the bounding box coordinates, utilize this data to explain the scene using natural language. Include details like object counts, position of the objects, relative position between the objects. + +When using the information from the caption and coordinates, directly explain the scene, and do not mention that the information source is the caption or the bounding box. Always answer as if you are directly looking at the image. \ No newline at end of file diff --git a/data/prompts/conversation/000_caps.txt b/data/prompts/conversation/000_caps.txt new file mode 100644 index 0000000000000000000000000000000000000000..3139b31b27e6e67b31b27cf0ac7bda317f46d6b8 --- /dev/null +++ b/data/prompts/conversation/000_caps.txt @@ -0,0 +1,5 @@ +There is a movie theater that displays the show times above the doors. +A red fire hydrant is deep in the snow. +The fire hydrant is in the snow near a recently plowed sidewalk. +This city has had a very hard winter with snow. +A hotel for dogs in the snow in winter. \ No newline at end of file diff --git a/data/prompts/conversation/000_conv.txt b/data/prompts/conversation/000_conv.txt new file mode 100644 index 0000000000000000000000000000000000000000..1300cd49992d8c342396cebfebc592909d6391e4 --- /dev/null +++ b/data/prompts/conversation/000_conv.txt @@ -0,0 +1,29 @@ +Question: +What color is the fire hydrant in the image? +=== +Answer: +The fire hydrant in the image is red. +=== +Question: +Is the fire hydrant fully covered by snow or partially visible? +=== +Answer: +The fire hydrant is partially visible, with a significant portion of it covered by the deep snow. +=== +Question: +What is the condition of the sidewalk near the fire hydrant? +=== +Answer: +The sidewalk near the fire hydrant has been recently plowed, so it is relatively clear of snow compared to the surrounding area. +=== +Question: +What does the image suggest about the winter season in the city? +=== +Answer: +The image suggests that the winter season in the city has been quite harsh and challenging. The significant snow accumulation seen in the image indicates that the city has experienced heavy snowfall, which can lead to various difficulties and disruptions for its residents. + +For instance, the deep snow covering the fire hydrant could potentially hinder its accessibility in case of emergencies, which poses safety concerns. The recently plowed sidewalk implies that the city's maintenance crews have been actively working to keep the walkways clear and safe for pedestrians, but the sheer amount of snowfall might make it difficult to keep up with the continuous snow removal efforts. + +Furthermore, such extreme winter conditions can impact transportation, leading to traffic issues, delays in public transit, and increased risks of accidents due to slippery roads. It can also cause problems for businesses and schools, as people might face challenges commuting to work or attending classes. Additionally, the heavy snow can put extra strain on infrastructure, such as roofs and power lines, increasing the likelihood of structural damage or power outages. + +In conclusion, the image of the red fire hydrant deep in the snow and the recently plowed sidewalk suggest that the city has faced a particularly severe winter season, with substantial snowfall that has likely caused various challenges and disruptions for its residents and infrastructure. \ No newline at end of file diff --git a/data/prompts/conversation/001_caps.txt b/data/prompts/conversation/001_caps.txt new file mode 100644 index 0000000000000000000000000000000000000000..02a8c6d8dda4f5ac338983251adcdc1d3a99a3f3 --- /dev/null +++ b/data/prompts/conversation/001_caps.txt @@ -0,0 +1,5 @@ +A man is skiing in the open snow covered hills +A skier is making his way into the snow. +A skier on the foothills of a huge mountain range. +A skier looks at mountains while standing near a trail sign. +a single person skiing by an area with a lot of bushes \ No newline at end of file diff --git a/data/prompts/conversation/001_conv.txt b/data/prompts/conversation/001_conv.txt new file mode 100644 index 0000000000000000000000000000000000000000..8dac93823203ead2af275b908f3b3c5e4ccbe631 --- /dev/null +++ b/data/prompts/conversation/001_conv.txt @@ -0,0 +1,37 @@ +Question: +What is the skier doing? +=== +Answer: +The skier is skiing in the snow-covered hills, making his way through the snow and enjoying the beautiful mountain scenery. They are also standing near a trail sign, which indicates their location on the mountain. +=== +Question: +Are there any other people or skiers visible in the image? +=== +Answer: +No, there is only a single person skiing in the image, and they are surrounded by an area with a lot of bushes. +=== +Question: +What kind of skiing is the person doing? Cross-country or downhill? +=== +Answer: +Based on what I can see in the photo, it is not possible to definitively determine whether the skier is doing cross-country or downhill skiing. However, given the presence of a trail sign and the fact that they are skiing in the foothills, it is more likely that the skier is engaged in cross-country skiing. Downhill skiing typically takes place on more steep slopes and involves ski lifts, whereas cross-country skiing often occurs on relatively flatter terrain with marked trails. +=== +Question: +Can you explain cross-country and downhill skiing a bit more? +=== +Answer: +Cross-country skiing and downhill skiing are two distinct types of skiing, each with its own techniques, equipment, and terrain preferences. + +1. Cross-Country Skiing: +Also known as Nordic skiing, cross-country skiing involves traversing relatively flat terrain or gentle slopes using skis and poles. It is a popular recreational and competitive sport that focuses on endurance, balance, and aerobic fitness. Cross-country skiers use their own locomotion to move across snow-covered terrain, rather than relying on ski lifts or other forms of assistance. +There are two main techniques in cross-country skiing: +- Classic: This technique involves skiing in parallel tracks, using a forward-and-backward gliding motion while keeping the skis parallel to each other. The skier uses their poles to propel themselves forward. +- Skate skiing: This technique is similar to ice skating, where the skier pushes off one ski at an angle and glides on the other. It requires a smooth, groomed surface and is typically faster than the classic technique. +Cross-country ski equipment consists of lightweight skis, boots, bindings, and poles. The boots are more flexible than those used in downhill skiing, allowing for better ankle movement and control. + +2. Downhill Skiing: +Also known as alpine skiing, downhill skiing involves descending slopes at high speeds using skis and poles for balance and control. This sport is more focused on speed, technique, and navigating challenging terrain, including steep slopes, moguls, and even jumps. +Downhill skiing can be further categorized into several disciplines, such as slalom, giant slalom, super-G, and downhill racing. Each discipline has its own set of rules, courses, and ski equipment. +Downhill ski equipment includes heavier and stiffer skis, boots, bindings, and poles than those used in cross-country skiing. The boots are more rigid to provide better support and control during high-speed descents and sharp turns. + +In summary, cross-country skiing is an endurance-based sport that involves traveling across flat or gently sloping terrain, while downhill skiing is focused on speed and technique as skiers navigate steeper slopes and challenging terrain. Both sports require specialized equipment and techniques, but they offer different experiences and challenges to participants. \ No newline at end of file diff --git a/data/prompts/conversation/system_message.txt b/data/prompts/conversation/system_message.txt new file mode 100644 index 0000000000000000000000000000000000000000..6eb89c0c1408299f1423064814d78c293acf9da2 --- /dev/null +++ b/data/prompts/conversation/system_message.txt @@ -0,0 +1,12 @@ +You are an AI visual assistant, and you are seeing a single image. What you see are provided with five sentences, describing the same image you are looking at. Answer all questions as you are seeing the image. + +Design a conversation between you and a person asking about this photo. The answers should be in a tone that a visual AI assistant is seeing the image and answering the question. +Ask diverse questions and give corresponding answers. + +Include questions asking about the visual content of the image, including the object types, counting the objects, object actions, object locations, relative positions between objects, etc. Only include questions that have definite answers: +(1) one can see the content in the image that the question asks about and can answer confidently; +(2) one can determine confidently from the image that it is not in the image. +Do not ask any question that cannot be answered confidently. + +Also include complex questions that are relevant to the content in the image, for example, asking about background knowledge of the objects in the image, asking to discuss about events happening in the image, etc. Again, do not ask about uncertain details. +Provide detailed answers when answering complex questions. For example, give detailed examples or reasoning steps to make the content more convincing and well-organized. You can include multiple paragraphs if necessary. \ No newline at end of file diff --git a/data/prompts/detail_description/000_caps.txt b/data/prompts/detail_description/000_caps.txt new file mode 100644 index 0000000000000000000000000000000000000000..c8c10e30e2d7f9bde33105715b04f5251d5c1950 --- /dev/null +++ b/data/prompts/detail_description/000_caps.txt @@ -0,0 +1,18 @@ +A harbor filled with lots of boats next to a building. +A bicycle parked in front of several boats at a dock. +A red bicycle in front of a line of docked white yachts +A bike sits before boats which sit before a long building. +A bicycle is a convenient means of land transportation when you live on a boat. + +bicycle: [0.287, 0.641, 0.507, 0.874] +bicycle: [0.566, 0.667, 0.63, 0.731] +boat: [0.318, 0.579, 0.575, 0.724] +boat: [0.704, 0.607, 0.818, 0.727] +boat: [0.818, 0.601, 0.942, 0.744] +boat: [0.002, 0.53, 0.243, 0.71] +boat: [0.541, 0.611, 0.668, 0.731] +person: [0.778, 0.527, 0.797, 0.57] +cup: [0.708, 0.733, 0.724, 0.758] +boat: [0.236, 0.532, 0.404, 0.64] +boat: [0.81, 0.632, 0.836, 0.676] +boat: [0.957, 0.526, 1.0, 0.752] \ No newline at end of file diff --git a/data/prompts/detail_description/000_conv.txt b/data/prompts/detail_description/000_conv.txt new file mode 100644 index 0000000000000000000000000000000000000000..d4a24572427098354f723fad5e737ff6dfe223fb --- /dev/null +++ b/data/prompts/detail_description/000_conv.txt @@ -0,0 +1,3 @@ +It is a harbor filled with numerous boats of various sizes docked next to a long building. Among the boats, there are a few white yachts lined up, standing out from the rest. There is a red bicycle prominently parked in front of the line of docked boats, serving as a convenient means of land transportation for those living on the boats. Another bicycle can be seen further back in the scene, near the middle of the harbor. + +A person is visible near the right side of the harbor, possibly enjoying the view or attending to their boat. Additionally, there is a cup placed on a surface near the middle of the scene. \ No newline at end of file diff --git a/data/prompts/detail_description/001_caps.txt b/data/prompts/detail_description/001_caps.txt new file mode 100644 index 0000000000000000000000000000000000000000..2065dfb20a6e40128749d507ecc27d01349e2ad9 --- /dev/null +++ b/data/prompts/detail_description/001_caps.txt @@ -0,0 +1,18 @@ +A group of people standing outside of a black vehicle with various luggage. +Luggage surrounds a vehicle in an underground parking area +People try to fit all of their luggage in an SUV. +The sport utility vehicle is parked in the public garage, being packed for a trip +Some people with luggage near a van that is transporting it. + +person: [0.681, 0.242, 0.774, 0.694] +person: [0.63, 0.222, 0.686, 0.516] +person: [0.444, 0.233, 0.487, 0.34] +backpack: [0.384, 0.696, 0.485, 0.914] +backpack: [0.755, 0.413, 0.846, 0.692] +suitcase: [0.758, 0.413, 0.845, 0.69] +suitcase: [0.1, 0.497, 0.173, 0.579] +bicycle: [0.282, 0.363, 0.327, 0.442] +car: [0.786, 0.25, 0.848, 0.322] +car: [0.783, 0.27, 0.827, 0.335] +car: [0.86, 0.254, 0.891, 0.3] +car: [0.261, 0.101, 0.787, 0.626] \ No newline at end of file diff --git a/data/prompts/detail_description/001_conv.txt b/data/prompts/detail_description/001_conv.txt new file mode 100644 index 0000000000000000000000000000000000000000..d2eaef8ea3754d8ec0695e328907a8d62553de46 --- /dev/null +++ b/data/prompts/detail_description/001_conv.txt @@ -0,0 +1,5 @@ +The image is an underground parking area with a black sport utility vehicle (SUV) parked. There are three people in the scene, with one person standing closer to the left side of the vehicle, another person in the middle, and the third person on the right side. They are all working together to pack their luggage into the SUV for a trip. + +In the parking area, various luggage items are scattered around the vehicle. There are two backpacks, one located near the left rear wheel and the other closer to the right side of the vehicle. Additionally, there are two suitcases, one on the right side of the car and another further away near the center of the parking area. A bicycle can also be seen on the left side of the vehicle. + +Other cars are parked around the main SUV, with one car positioned behind it and slightly to the left, another behind and slightly to the right, and the third car further behind on the right side. \ No newline at end of file diff --git a/data/prompts/detail_description/002_caps.txt b/data/prompts/detail_description/002_caps.txt new file mode 100644 index 0000000000000000000000000000000000000000..70284585018497b091ba797a05d57c07e8bce3b6 --- /dev/null +++ b/data/prompts/detail_description/002_caps.txt @@ -0,0 +1,15 @@ +A man holds a Wii-mote above his head while another looks on. +A guy and his friend are playing Nintendo Wii. +A young man is holding a video game remote over his head. +two men standing in a room while one plays with a wii mote +Some guys standing and playing a video game. + +couch: [0.697, 0.759, 0.995, 1.0] +dining table: [0.426, 0.755, 1.0, 0.987] +person: [0.082, 0.252, 0.342, 1.0] +person: [0.399, 0.085, 0.742, 0.982] +remote: [0.477, 0.135, 0.516, 0.187] +sink: [0.016, 0.501, 0.063, 0.52] +potted plant: [0.798, 0.384, 0.888, 0.645] +refrigerator: [0.305, 0.389, 0.414, 0.547] +chair: [0.72, 0.509, 0.858, 0.725] \ No newline at end of file diff --git a/data/prompts/detail_description/002_conv.txt b/data/prompts/detail_description/002_conv.txt new file mode 100644 index 0000000000000000000000000000000000000000..56881c770ec5aca56bc2bf6c38cb6101ae58fa24 --- /dev/null +++ b/data/prompts/detail_description/002_conv.txt @@ -0,0 +1,3 @@ +The image shows two men standing in a room, engaged in playing a video game on a Nintendo Wii console. One of the men is holding a Wii remote above his head with enthusiasm, while the other man looks on, likely enjoying the friendly competition. + +The room appears to be a living space with a couch located in the background and a dining table nearby. A potted plant can be seen placed close to the couch, and a chair is situated in the middle of the room. The room also features a kitchen area with a sink and a refrigerator visible in the background. \ No newline at end of file diff --git a/data/prompts/detail_description/system_message.txt b/data/prompts/detail_description/system_message.txt new file mode 100644 index 0000000000000000000000000000000000000000..fa836ca4b4d836a539f7e6d0aa2a012e6996edf5 --- /dev/null +++ b/data/prompts/detail_description/system_message.txt @@ -0,0 +1,7 @@ +You are an AI visual assistant that can analyze a single image. You receive five sentences, each describing the same image you are observing. In addition, specific object locations within the image are given, along with detailed coordinates. These coordinates are in the form of bounding boxes, represented as (x1, y1, x2, y2) with floating numbers ranging from 0 to 1. These values correspond to the top left x, top left y, bottom right x, and bottom right y. + +Using the provided caption and bounding box information, describe the scene in a detailed manner. + +Instead of directly mentioning the bounding box coordinates, utilize this data to explain the scene using natural language. Include details like object counts, position of the objects, relative position between the objects. + +When using the information from the caption and coordinates, directly explain the scene, and do not mention that the information source is the caption or the bounding box. Always answer as if you are directly looking at the image. \ No newline at end of file diff --git a/docs/Customize_Component.md b/docs/Customize_Component.md new file mode 100644 index 0000000000000000000000000000000000000000..e99a60879920b389799fb3a0baf1fd864ee0bccc --- /dev/null +++ b/docs/Customize_Component.md @@ -0,0 +1,20 @@ +# Customize Components in LLaVA + +This is an initial guide on how to replace the LLMs, visual encoders, etc. with your choice of components. + +## LLM + +It is quite simple to swap out LLaMA to any other LLMs. You can refer to our implementation of [`llava_llama.py`](https://raw.githubusercontent.com/haotian-liu/LLaVA/main/llava/model/language_model/llava_llama.py) for an example of how to replace the LLM. + +Although it may seem that it still needs ~100 lines of code, most of them are copied from the original `llama.py` from HF. The only part that is different is to insert some lines for processing the multimodal inputs. + +In `forward` function, you can see that we call `self.prepare_inputs_labels_for_multimodal` to process the multimodal inputs. This function is defined in `LlavaMetaForCausalLM` and you just need to insert it into the `forward` function of your LLM. + +In `prepare_inputs_for_generation` function, you can see that we add `images` to the `model_inputs`. This is because we need to pass the images to the LLM during generation. + +These are basically all the changes you need to make to replace the LLM. + +## Visual Encoder + +You can check out [`clip_encoder.py`](https://github.com/haotian-liu/LLaVA/blob/main/llava/model/multimodal_encoder/clip_encoder.py) on how we implement the CLIP visual encoder. + diff --git a/docs/Data.md b/docs/Data.md new file mode 100644 index 0000000000000000000000000000000000000000..84807ec252858cd78bf96b3fce6f42f66b20126f --- /dev/null +++ b/docs/Data.md @@ -0,0 +1,29 @@ +## Data + +| Data file name | Size | +| --- | ---: | +| [llava_instruct_150k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava_instruct_150k.json) | 229 MB | +| [llava_instruct_80k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava_instruct_80k.json) | 229 MB | +| [conversation_58k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/conversation_58k.json) | 126 MB | +| [detail_23k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/detail_23k.json) | 20.5 MB | +| [complex_reasoning_77k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/complex_reasoning_77k.json) | 79.6 MB | + +### Pretraining Dataset +The pretraining dataset used in this release is a subset of CC-3M dataset, filtered with a more balanced concept coverage distribution. Please see [here](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K) for a detailed description of the dataset structure and how to download the images. + +If you already have CC-3M dataset on your disk, the image names follow this format: `GCC_train_000000000.jpg`. You may edit the `image` field correspondingly if necessary. + +| Data | Chat File | Meta Data | Size | +| --- | --- | --- | ---: | +| CC-3M Concept-balanced 595K | [chat.json](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K/blob/main/chat.json) | [metadata.json](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K/blob/main/metadata.json) | 211 MB +| LAION/CC/SBU BLIP-Caption Concept-balanced 558K | [blip_laion_cc_sbu_558k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Pretrain/blob/main/blip_laion_cc_sbu_558k.json) | [metadata.json](#) | 181 MB + +**Important notice**: Upon the request from the community, as ~15% images of the original CC-3M dataset are no longer accessible, we upload [`images.zip`](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K/blob/main/images.zip) for better reproducing our work in research community. It must not be used for any other purposes. The use of these images must comply with the CC-3M license. This may be taken down at any time when requested by the original CC-3M dataset owner or owners of the referenced images. + +### GPT-4 Prompts + +We provide our prompts and few-shot samples for GPT-4 queries, to better facilitate research in this domain. Please check out the [`prompts`](playground/data/prompts) folder for three kinds of questions: conversation, detail description, and complex reasoning. + +They are organized in a format of `system_message.txt` for system message, pairs of `abc_caps.txt` for few-shot sample user input, and `abc_conv.txt` for few-shot sample reference output. + +Note that you may find them in different format. For example, `conversation` is in `jsonl`, and detail description is answer-only. The selected format in our preliminary experiments works slightly better than a limited set of alternatives that we tried: `jsonl`, more natural format, answer-only. If interested, you may try other variants or conduct more careful study in this. Contributions are welcomed! diff --git a/docs/LLaVA_Bench.md b/docs/LLaVA_Bench.md new file mode 100644 index 0000000000000000000000000000000000000000..5921964c43f599b2d820de5092a1c3b4c39de60f --- /dev/null +++ b/docs/LLaVA_Bench.md @@ -0,0 +1,31 @@ +# LLaVA-Bench [[Download](https://huggingface.co/datasets/liuhaotian/llava-bench-in-the-wild)] + +**-Introduction-** Large commercial multimodal chatbots have been released in this week, including +- [Multimodal Bing-Chat by Microsoft](https://blogs.bing.com/search/july-2023/Bing-Chat-Enterprise-announced,-multimodal-Visual-Search-rolling-out-to-Bing-Chat) (July 18, 2023) +- [Multimodal Bard by Google](https://bard.google.com/). + +These chatbots are presumably supported by proprietary large multimodal models (LMM). Compared with the open-source LMM such as LLaVA, proprietary LMM represent the scaling success upperbound of the current SoTA techniques. They share the goal of developing multimodal chatbots that follow human intents to complete various daily-life visual tasks in the wild. While it remains less unexplored how to evaluate multimodal chat ability, it provides useful feedback to study open-source LMMs against the commercial multimodal chatbots. In addition to the *LLaVA-Bench (COCO)* dataset we used to develop the early versions of LLaVA, we are releasing [*LLaVA-Bench (In-the-Wild)*](https://huggingface.co/datasets/liuhaotian/llava-bench-in-the-wild) to the community for the public use. + +## LLaVA-Bench (In-the-Wild *[Ongoing work]*) + +To evaluate the model's capability in more challenging tasks and generalizability to novel domains, we collect a diverse set of 24 images with 60 questions in total, including indoor and outdoor scenes, memes, paintings, sketches, etc, and associate each image with a highly-detailed and manually-curated description and a proper selection of questions. Such design also assesses the model's robustness to different prompts. In this release, we also categorize questions into three categories: conversation (simple QA), detailed description, and complex reasoning. We continue to expand and improve the diversity of the LLaVA-Bench (In-the-Wild). We manually query Bing-Chat and Bard to get the responses. + +### Results + +The score is measured by comparing against a reference answer generated by text-only GPT-4. It is generated by feeding the question, along with the ground truth image annotations as the context. A text-only GPT-4 evaluator rates both answers. We query GPT-4 by putting the reference answer first, and then the answer generated by the candidate model. We upload images at their original resolution to Bard and Bing-Chat to obtain the results. + +| Approach | Conversation | Detail | Reasoning | Overall | +|----------------|--------------|--------|-----------|---------| +| Bard-0718 | 83.7 | 69.7 | 78.7 | 77.8 | +| Bing-Chat-0629 | 59.6 | 52.2 | 90.1 | 71.5 | +| LLaVA-13B-v1-336px-0719 (beam=1) | 64.3 | 55.9 | 81.7 | 70.1 | +| LLaVA-13B-v1-336px-0719 (beam=5) | 68.4 | 59.9 | 84.3 | 73.5 | + +Note that Bard sometimes refuses to answer questions about images containing humans, and Bing-Chat blurs the human faces in the images. We also provide the benchmark score for the subset without humans. + +| Approach | Conversation | Detail | Reasoning | Overall | +|----------------|--------------|--------|-----------|---------| +| Bard-0718 | 94.9 | 74.3 | 84.3 | 84.6 | +| Bing-Chat-0629 | 55.8 | 53.6 | 93.5 | 72.6 | +| LLaVA-13B-v1-336px-0719 (beam=1) | 62.2 | 56.4 | 82.2 | 70.0 | +| LLaVA-13B-v1-336px-0719 (beam=5) | 65.6 | 61.7 | 85.0 | 73.6 | diff --git a/docs/LLaVA_from_LLaMA2.md b/docs/LLaVA_from_LLaMA2.md new file mode 100644 index 0000000000000000000000000000000000000000..b4163668a33ff705c28f5b103b727514161e5652 --- /dev/null +++ b/docs/LLaVA_from_LLaMA2.md @@ -0,0 +1,29 @@ +# LLaVA (based on Llama 2 LLM, Preview) + +*NOTE: This is a technical preview. We are still running hyperparameter search, and will release the final model soon. If you'd like to contribute to this, please contact us.* + +:llama: **-Introduction-** [Llama 2 is an open-source LLM released by Meta AI](https://about.fb.com/news/2023/07/llama-2/) today (July 18, 2023). Compared with its early version [Llama 1](https://ai.meta.com/blog/large-language-model-llama-meta-ai/), Llama 2 is more favored in ***stronger language performance***, ***longer context window***, and importantly ***commercially usable***! While Llama 2 is changing the LLM market landscape in the language space, its multimodal ability remains unknown. We quickly develop the LLaVA variant based on the latest Llama 2 checkpoints, and release it to the community for the public use. + +You need to apply for and download the lastest Llama 2 checkpoints to start your own training (apply [here](https://ai.meta.com/resources/models-and-libraries/llama-downloads/)) + + +## Training + +Please checkout [`pretrain.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/pretrain.sh), [`finetune.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune.sh), [`finetune_lora.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_lora.sh). + +## LLaVA (based on Llama 2), What is different? + +:volcano: How is the new LLaVA based on Llama 2 different from Llama 1? The comparisons of the training process are described: +- **Pre-training**. The pre-trained base LLM is changed from Llama 1 to Llama 2 +- **Language instruction-tuning**. The previous LLaVA model starts with Vicuna, which is instruct tuned on ShareGPT data from Llama 1; The new LLaVA model starts with Llama 2 Chat, which is an instruct tuned checkpoint on dialogue data from Llama 2. +- **Multimodal instruction-tuning**. The same LLaVA-Lighting process is applied. + + +### Results + +- Llama 2 is better at following the instructions of role playing; Llama 2 fails in following the instructions of translation +- The quantitative evaluation on [LLaVA-Bench](https://github.com/haotian-liu/LLaVA/blob/main/docs/LLaVA_Bench.md) demonstrates on-par performance between Llama 2 and Llama 1 in LLaVA's multimodal chat ability. + + + + diff --git a/docs/LoRA.md b/docs/LoRA.md new file mode 100644 index 0000000000000000000000000000000000000000..369fe92579051f98a0724a92e52e65e014a0de2f --- /dev/null +++ b/docs/LoRA.md @@ -0,0 +1,46 @@ +# LLaVA (LoRA, Preview) + +NOTE: This is a technical preview, and is not yet ready for production use. We are still running hyperparameter search for the LoRA model, and will release the final model soon. If you'd like to contribute to this, please contact us. + +You need latest code base for LoRA support (instructions [here](https://github.com/haotian-liu/LLaVA#upgrade-to-latest-code-base)) + +## Demo (Web UI) + +Please execute each of the command below one by one (after the previous one has finished). The commands are the same as launching other demos except for an additional `--model-base` flag to specify the base model to use. Please make sure the base model corresponds to the LoRA checkpoint that you are using. For this technical preview, you need Vicuna v1.1 (7B) checkpoint (if you do not have that already, follow the instructions [here](https://github.com/lm-sys/FastChat#vicuna-weights)). + +#### Launch a controller +```Shell +python -m llava.serve.controller --host 0.0.0.0 --port 10000 +``` + +#### Launch a gradio web server. +```Shell +python -m llava.serve.gradio_web_server --controller http://localhost:10000 --model-list-mode reload +``` +You just launched the Gradio web interface. Now, you can open the web interface with the URL printed on the screen. You may notice that there is no model in the model list. Do not worry, as we have not launched any model worker yet. It will be automatically updated when you launch a model worker. + +#### Launch a model worker +```Shell +python -m llava.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port 40000 --worker http://localhost:40000 --model-path liuhaotian/llava-vicuna-7b-v1.1-lcs_558k-instruct_80k_3e-lora-preview-alpha --model-base /path/to/vicuna-v1.1 +``` +Wait until the process finishes loading the model and you see "Uvicorn running on ...". Now, refresh your Gradio web UI, and you will see the model you just launched in the model list. + +You can launch as many workers as you want, and compare between different model checkpoints in the same Gradio interface. Please keep the `--controller` the same, and modify the `--port` and `--worker` to a different port number for each worker. + + +## Training + +Please see sample training scripts for [LoRA](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_lora.sh) and [QLoRA](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_qlora.sh). + +We provide sample DeepSpeed configs, [`zero3.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero3.json) is more like PyTorch FSDP, and [`zero3_offload.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero3_offload.json) can further save memory consumption by offloading parameters to CPU. `zero3.json` is usually faster than `zero3_offload.json` but requires more GPU memory, therefore, we recommend trying `zero3.json` first, and if you run out of GPU memory, try `zero3_offload.json`. You can also tweak the `per_device_train_batch_size` and `gradient_accumulation_steps` in the config to save memory, and just to make sure that `per_device_train_batch_size` and `gradient_accumulation_steps` remains the same. + +If you are having issues with ZeRO-3 configs, and there are enough VRAM, you may try [`zero2.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero2.json). This consumes slightly more memory than ZeRO-3, and behaves more similar to PyTorch FSDP, while still supporting parameter-efficient tuning. + +## Create Merged Checkpoints + +```Shell +python scripts/merge_lora_weights.py \ + --model-path /path/to/lora_model \ + --model-base /path/to/base_model \ + --save-model-path /path/to/merge_model +``` diff --git a/docs/MODEL_ZOO.md b/docs/MODEL_ZOO.md new file mode 100644 index 0000000000000000000000000000000000000000..d7d50a17cadf751f17f40cb0630ad3becd97fbbf --- /dev/null +++ b/docs/MODEL_ZOO.md @@ -0,0 +1,136 @@ +# Model Zoo + +**To Use LLaVA-1.5 checkpoints, your llava package version must be newer than 1.1.0. [Instructions](https://github.com/haotian-liu/LLaVA#upgrade-to-latest-code-base) on how to upgrade.** + +If you are interested in including any other details in Model Zoo, please open an issue :) + +The model weights below are *merged* weights. You do not need to apply delta. The usage of LLaVA checkpoints should comply with the base LLM's model license: [LLaMA](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md). + +## LLaVA-v1.5 + +| Version | Size | Schedule | Checkpoint | VQAv2 | GQA | VizWiz | SQA | T-VQA | POPE | MME | MM-Bench | MM-Bench-CN | SEED | LLaVA-Bench-Wild | MM-Vet | +|----------|----------|-----------|-----------|---|---|---|---|---|---|---|---|---|---|---|---| +| LLaVA-1.5 | 7B | full_ft-1e | [liuhaotian/llava-v1.5-7b](https://huggingface.co/liuhaotian/llava-v1.5-7b) | 78.5 | 62.0 | 50.0 | 66.8 | 58.2 | 85.9 | 1510.7 | 64.3 | 58.3 | 58.6 | 63.4 | 30.5 | +| LLaVA-1.5 | 13B | full_ft-1e | [liuhaotian/llava-v1.5-13b](https://huggingface.co/liuhaotian/llava-v1.5-13b) | 80.0 | 63.3 | 53.6 | 71.6 | 61.3 | 85.9 | 1531.3 | 67.7 | 63.6 | 61.6 | 70.7 | 35.4 | +| LLaVA-1.5 | 7B | lora-1e | coming soon | +| LLaVA-1.5 | 13B | lora-1e | coming soon | + +

+
+ LLaVA-1.5 achieves SoTA performance across 11 benchmarks. +

+ + +## LLaVA-v1 + +*Note: We recommend using the most capable LLaVA-v1.5 series above for the best performance.* + +| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | LLaVA-Bench-Conv | LLaVA-Bench-Detail | LLaVA-Bench-Complex | LLaVA-Bench-Overall | Download | +|----------|----------------|---------------|----------------------|-----------------|--------------------|------------------|--------------------|---------------------|---------------------|---------------------| +| Vicuna-13B-v1.3 | CLIP-L-336px | LCS-558K | 1e | LLaVA-Instruct-80K | proj-1e, lora-1e | 64.3 | 55.9 | 81.7 | 70.1 | [LoRA](https://huggingface.co/liuhaotian/llava-v1-0719-336px-lora-vicuna-13b-v1.3) [LoRA-Merged](https://huggingface.co/liuhaotian/llava-v1-0719-336px-lora-merge-vicuna-13b-v1.3) | +| LLaMA-2-13B-Chat | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | full_ft-1e | 56.7 | 58.6 | 80.0 | 67.9 | [ckpt](https://huggingface.co/liuhaotian/llava-llama-2-13b-chat-lightning-preview) | +| LLaMA-2-7B-Chat | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | lora-1e | 51.2 | 58.9 | 71.6 | 62.8 | [LoRA](https://huggingface.co/liuhaotian/llava-llama-2-7b-chat-lightning-lora-preview) | + + +## Projector weights + +The model weights below are projector weights we have pretrained. You can use these projector weights for visual instruction tuning. We'll add more projector weights into model zoo very soon. + +**NOTE**: These projector weights are only compatible with the `llava>=1.0.0`, please check out the latest code base if your local code version is below `v1.0.0`. + +**NOTE**: When you use our pretrained projector for visual instruction tuning, it is very important to **use the same base LLM and vision encoder** as the one we used for pretraining the projector. Otherwise, the performance will be very bad. + +When using these projector weights to instruction tune your LMM, please make sure that these options are correctly set as follows, + +```Shell +--mm_use_im_start_end False +--mm_use_im_patch_token False +``` + +| Base LLM | Vision Encoder | Projection | Pretrain Data | Pretraining schedule | Download | +|----------|----------------|---------------|----------------------|----------|----------| +| Vicuna-13B-v1.5 | CLIP-L-336px | MLP-2x | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-v1.5-mlp2x-336px-pretrain-vicuna-13b-v1.5) | +| Vicuna-7B-v1.5 | CLIP-L-336px | MLP-2x | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-v1.5-mlp2x-336px-pretrain-vicuna-7b-v1.5) | +| LLaMA-2-13B-Chat | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-llama-2-13b-chat) | +| LLaMA-2-7B-Chat | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-llama-2-7b-chat) | +| LLaMA-2-13B-Chat | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-llama-2-13b-chat) | +| LLaMA-2-7B-Chat | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-llama-2-7b-chat) | +| Vicuna-13B-v1.3 | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-vicuna-13b-v1.3) | +| Vicuna-7B-v1.3 | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-vicuna-7b-v1.3) | +| Vicuna-13B-v1.3 | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-vicuna-13b-v1.3) | +| Vicuna-7B-v1.3 | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-vicuna-7b-v1.3) | + + +## Science QA Checkpoints + +| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download | +|----------|----------------|---------------|----------------------|-----------------|--------------------|---------------------| +| Vicuna-13B-v1.3 | CLIP-L | LCS-558K | 1e | ScienceQA | full_ft-12e | [ckpt](https://huggingface.co/liuhaotian/llava-lcs558k-scienceqa-vicuna-13b-v1.3) | + + +## Legacy Models (merged weights) + +The model weights below are *merged* weights. You do not need to apply delta. The usage of LLaVA checkpoints should comply with the base LLM's model license. + +| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download | +|----------|----------------|---------------|----------------------|-----------------|--------------------|------------------| +| MPT-7B-Chat | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | full_ft-1e | [preview](https://huggingface.co/liuhaotian/LLaVA-Lightning-MPT-7B-preview) | + + +## Legacy Models (delta weights) + +The model weights below are *delta* weights. The usage of LLaVA checkpoints should comply with the base LLM's model license: [LLaMA](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md). + +You can add our delta to the original LLaMA weights to obtain the LLaVA weights. + +Instructions: + +1. Get the original LLaMA weights in the huggingface format by following the instructions [here](https://huggingface.co/docs/transformers/main/model_doc/llama). +2. Use the following scripts to get LLaVA weights by applying our delta. It will automatically download delta weights from our Hugging Face account. In the script below, we use the delta weights of [`liuhaotian/LLaVA-7b-delta-v0`](https://huggingface.co/liuhaotian/LLaVA-7b-delta-v0) as an example. It can be adapted for other delta weights by changing the `--delta` argument (and base/target accordingly). + +```bash +python3 -m llava.model.apply_delta \ + --base /path/to/llama-7b \ + --target /output/path/to/LLaVA-7B-v0 \ + --delta liuhaotian/LLaVA-7b-delta-v0 +``` + +| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download | +|----------|----------------|---------------|----------------------|-----------------|--------------------|------------------| +| Vicuna-13B-v1.1 | CLIP-L | CC-595K | 1e | LLaVA-Instruct-158K | full_ft-3e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v1-1) | +| Vicuna-7B-v1.1 | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | full_ft-1e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-Lightning-7B-delta-v1-1) | +| Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | LLaVA-Instruct-158K | full_ft-3e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v0) | +| Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | ScienceQA | full_ft-12e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v0-science_qa) | +| Vicuna-7B-v0 | CLIP-L | CC-595K | 1e | LLaVA-Instruct-158K | full_ft-3e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-7b-delta-v0) | + + + +## Legacy Projector weights + +The following projector weights are deprecated, and the support for them may be removed in the future. They do not support zero-shot inference. Please use the projector weights in the [table above](#projector-weights) if possible. + +**NOTE**: When you use our pretrained projector for visual instruction tuning, it is very important to **use the same base LLM and vision encoder** as the one we used for pretraining the projector. Otherwise, the performance will be very bad. + +When using these projector weights to instruction tune your LMM, please make sure that these options are correctly set as follows, + +```Shell +--mm_use_im_start_end True +--mm_use_im_patch_token False +``` + +| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Download | +|----------|----------------|---------------|----------------------|----------| +| Vicuna-7B-v1.1 | CLIP-L | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-7b-pretrain-projector-v1-1-LCS-558K-blip_caption.bin) | +| Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-13b-pretrain-projector-v0-CC3M-595K-original_caption.bin) | +| Vicuna-7B-v0 | CLIP-L | CC-595K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-7b-pretrain-projector-v0-CC3M-595K-original_caption.bin) | + +When using these projector weights to instruction tune your LMM, please make sure that these options are correctly set as follows, + +```Shell +--mm_use_im_start_end False +--mm_use_im_patch_token False +``` + +| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Download | +|----------|----------------|---------------|----------------------|----------| +| Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-13b-pretrain-projector-v0-CC3M-595K-original_caption-no_im_token.bin) | diff --git a/docs/ScienceQA.md b/docs/ScienceQA.md new file mode 100644 index 0000000000000000000000000000000000000000..8881c41c67002a3798435b051c9a609dd1c0d506 --- /dev/null +++ b/docs/ScienceQA.md @@ -0,0 +1,53 @@ +### ScienceQA + +#### Prepare Data +1. Please see ScienceQA [repo](https://github.com/lupantech/ScienceQA) for setting up the dataset. +2. Generate ScienceQA dataset for LLaVA conversation-style format. + +```Shell +python scripts/convert_sqa_to_llava.py \ + convert_to_llava \ + --base-dir /path/to/ScienceQA/data/scienceqa \ + --prompt-format "QCM-LEA" \ + --split {train,val,minival,test,minitest} +``` + +#### Training + +1. Pretraining + +You can download our pretrained projector weights from our [Model Zoo](), or train your own projector weights using [`pretrain.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/pretrain.sh). + +2. Finetuning + +See [`finetune_sqa.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_sqa.sh). + +#### Evaluation + +1. Multiple-GPU inference +You may evaluate this with multiple GPUs, and concatenate the generated jsonl files. Please refer to our script for [batch evaluation](https://github.com/haotian-liu/LLaVA/blob/main/scripts/sqa_eval_batch.sh) and [results gathering](https://github.com/haotian-liu/LLaVA/blob/main/scripts/sqa_eval_gather.sh). + +2. Single-GPU inference + +(a) Generate LLaVA responses on ScienceQA dataset + +```Shell +python -m llava.eval.model_vqa_science \ + --model-path liuhaotian/llava-lcs558k-scienceqa-vicuna-13b-v1.3 \ + --question-file /path/to/ScienceQA/data/scienceqa/llava_test_QCM-LEA.json \ + --image-folder /path/to/ScienceQA/data/scienceqa/images/test \ + --answers-file vqa/results/ScienceQA/test_llava-13b.jsonl \ + --conv-mode llava_v1 +``` + +(b) Evaluate the generated responses + +```Shell +python eval_science_qa.py \ + --base-dir /path/to/ScienceQA/data/scienceqa \ + --result-file vqa/results/ScienceQA/test_llava-13b.jsonl \ + --output-file vqa/results/ScienceQA/test_llava-13b_output.json \ + --output-result vqa/results/ScienceQA/test_llava-13b_result.json \ +``` + +For reference, we attach our prediction file [`test_sqa_llava_lcs_558k_sqa_12e_vicuna_v1_3_13b.json`](https://github.com/haotian-liu/LLaVA/blob/main/llava/eval/table/results/test_sqa_llava_lcs_558k_sqa_12e_vicuna_v1_3_13b.json) and [`test_sqa_llava_13b_v0.json`](https://github.com/haotian-liu/LLaVA/blob/main/llava/eval/table/results/test_sqa_llava_13b_v0.json) for comparison when reproducing our results, as well as for further analysis in detail. diff --git a/gradio_web_server.log b/gradio_web_server.log new file mode 100644 index 0000000000000000000000000000000000000000..48447321292b7b52f61d01f1159e6b7b99bab966 --- /dev/null +++ b/gradio_web_server.log @@ -0,0 +1,2010 @@ +2024-10-09 14:33:31 | INFO | stdout | args: Namespace(host='0.0.0.0', port=None, controller_url='http://localhost:10000', concurrency_count=1, model_list_mode='reload', share=False, moderate=False, embed=False) +2024-10-09 14:33:31 | INFO | stdout | Starting the controller +2024-10-09 14:33:31 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.controller', '--host', '0.0.0.0', '--port', '10000'] +2024-10-09 14:33:31 | INFO | stdout | Starting the model worker for the model osunlp/UGround +2024-10-09 14:33:31 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.model_worker', '--host', '0.0.0.0', '--controller', 'http://localhost:10000', '--model-path', 'osunlp/UGround', '--model-name', 'llava-v1.5-UGround_v1', '--use-flash-attn', '--load-4bit'] +2024-10-09 14:33:41 | ERROR | stderr | /Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/gradio/components/dropdown.py:163: UserWarning: The value passed into gr.Dropdown() is not in the list of choices. Please update the list of choices to include: or set allow_custom_value=True. +2024-10-09 14:33:41 | ERROR | stderr | warnings.warn( +2024-10-09 14:33:41 | INFO | stdout | Running on local URL: http://0.0.0.0:7860 +2024-10-09 14:33:41 | INFO | httpx | HTTP Request: GET http://localhost:7860/startup-events "HTTP/1.1 200 OK" +2024-10-09 14:33:41 | INFO | httpx | HTTP Request: HEAD http://localhost:7860/ "HTTP/1.1 200 OK" +2024-10-09 14:33:41 | INFO | stdout | +2024-10-09 14:33:41 | INFO | stdout | To create a public link, set `share=True` in `launch()`. +2024-10-09 14:33:41 | INFO | httpx | HTTP Request: GET https://checkip.amazonaws.com/ "HTTP/1.1 200 " +2024-10-09 14:33:41 | INFO | httpx | HTTP Request: GET https://checkip.amazonaws.com/ "HTTP/1.1 200 " +2024-10-09 14:33:41 | INFO | httpx | HTTP Request: GET https://api.gradio.app/pkg-version "HTTP/1.1 200 OK" +2024-10-09 14:33:41 | INFO | stdout | IMPORTANT: You are using gradio version 4.16.0, however version 4.29.0 is available, please upgrade. +2024-10-09 14:33:41 | INFO | stdout | -------- +2024-10-09 14:33:41 | INFO | httpx | HTTP Request: POST https://api.gradio.app/gradio-initiated-analytics/ "HTTP/1.1 200 OK" +2024-10-09 14:33:41 | INFO | httpx | HTTP Request: POST https://api.gradio.app/gradio-launched-telemetry/ "HTTP/1.1 200 OK" +2024-10-09 14:33:48 | ERROR | stderr | ERROR: Exception in ASGI application +2024-10-09 14:33:48 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 270, in _init_core_attrs +2024-10-09 14:33:48 | ERROR | stderr | self._core_schema = _getattr_no_parents(self._type, '__pydantic_core_schema__') +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 112, in _getattr_no_parents +2024-10-09 14:33:48 | ERROR | stderr | raise AttributeError(attribute) +2024-10-09 14:33:48 | ERROR | stderr | AttributeError: __pydantic_core_schema__ +2024-10-09 14:33:48 | ERROR | stderr | +2024-10-09 14:33:48 | ERROR | stderr | During handling of the above exception, another exception occurred: +2024-10-09 14:33:48 | ERROR | stderr | +2024-10-09 14:33:48 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/protocols/http/h11_impl.py", line 406, in run_asgi +2024-10-09 14:33:48 | ERROR | stderr | result = await app( # type: ignore[func-returns-value] +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__ +2024-10-09 14:33:48 | ERROR | stderr | return await self.app(scope, receive, send) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/applications.py", line 1054, in __call__ +2024-10-09 14:33:48 | ERROR | stderr | await super().__call__(scope, receive, send) +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/applications.py", line 113, in __call__ +2024-10-09 14:33:48 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 187, in __call__ +2024-10-09 14:33:48 | ERROR | stderr | raise exc +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 165, in __call__ +2024-10-09 14:33:48 | ERROR | stderr | await self.app(scope, receive, _send) +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 93, in __call__ +2024-10-09 14:33:48 | ERROR | stderr | await self.simple_response(scope, receive, send, request_headers=headers) +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 144, in simple_response +2024-10-09 14:33:48 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 62, in __call__ +2024-10-09 14:33:48 | ERROR | stderr | await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:33:48 | ERROR | stderr | raise exc +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:33:48 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 715, in __call__ +2024-10-09 14:33:48 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 735, in app +2024-10-09 14:33:48 | ERROR | stderr | await route.handle(scope, receive, send) +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 288, in handle +2024-10-09 14:33:48 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 76, in app +2024-10-09 14:33:48 | ERROR | stderr | await wrap_app_handling_exceptions(app, request)(scope, receive, send) +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:33:48 | ERROR | stderr | raise exc +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:33:48 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 73, in app +2024-10-09 14:33:48 | ERROR | stderr | response = await f(request) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/routing.py", line 291, in app +2024-10-09 14:33:48 | ERROR | stderr | solved_result = await solve_dependencies( +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 656, in solve_dependencies +2024-10-09 14:33:48 | ERROR | stderr | ) = await request_body_to_args( # body_params checked above +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 881, in request_body_to_args +2024-10-09 14:33:48 | ERROR | stderr | fields_to_extract = get_cached_model_fields(first_field.type_) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 657, in get_cached_model_fields +2024-10-09 14:33:48 | ERROR | stderr | return get_model_fields(model) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 284, in get_model_fields +2024-10-09 14:33:48 | ERROR | stderr | return [ +2024-10-09 14:33:48 | ERROR | stderr | ^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 285, in +2024-10-09 14:33:48 | ERROR | stderr | ModelField(field_info=field_info, name=name) +2024-10-09 14:33:48 | ERROR | stderr | File "", line 6, in __init__ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 110, in __post_init__ +2024-10-09 14:33:48 | ERROR | stderr | self._type_adapter: TypeAdapter[Any] = TypeAdapter( +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 257, in __init__ +2024-10-09 14:33:48 | ERROR | stderr | self._init_core_attrs(rebuild_mocks=False) +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 135, in wrapped +2024-10-09 14:33:48 | ERROR | stderr | return func(self, *args, **kwargs) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 277, in _init_core_attrs +2024-10-09 14:33:48 | ERROR | stderr | self._core_schema = _get_schema(self._type, config_wrapper, parent_depth=self._parent_depth) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 95, in _get_schema +2024-10-09 14:33:48 | ERROR | stderr | schema = gen.generate_schema(type_) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:33:48 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 908, in _generate_schema_inner +2024-10-09 14:33:48 | ERROR | stderr | return self._annotated_schema(obj) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2028, in _annotated_schema +2024-10-09 14:33:48 | ERROR | stderr | schema = self._apply_annotations(source_type, annotations) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2107, in _apply_annotations +2024-10-09 14:33:48 | ERROR | stderr | schema = get_inner_schema(source_type) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:33:48 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2189, in new_handler +2024-10-09 14:33:48 | ERROR | stderr | schema = metadata_get_schema(source, get_inner_schema) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2185, in +2024-10-09 14:33:48 | ERROR | stderr | lambda source, handler: handler(source) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:33:48 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2088, in inner_handler +2024-10-09 14:33:48 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:33:48 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1029, in match_type +2024-10-09 14:33:48 | ERROR | stderr | return self._match_generic_type(obj, origin) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1058, in _match_generic_type +2024-10-09 14:33:48 | ERROR | stderr | return self._union_schema(obj) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1378, in _union_schema +2024-10-09 14:33:48 | ERROR | stderr | choices.append(self.generate_schema(arg)) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:33:48 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:33:48 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1038, in match_type +2024-10-09 14:33:48 | ERROR | stderr | return self._unknown_type_schema(obj) +2024-10-09 14:33:48 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:33:48 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 558, in _unknown_type_schema +2024-10-09 14:33:48 | ERROR | stderr | raise PydanticSchemaGenerationError( +2024-10-09 14:33:48 | ERROR | stderr | pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for . Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it. +2024-10-09 14:33:48 | ERROR | stderr | +2024-10-09 14:33:48 | ERROR | stderr | If you got this error by calling handler() within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema()` since we do not call `__get_pydantic_core_schema__` on `` otherwise to avoid infinite recursion. +2024-10-09 14:33:48 | ERROR | stderr | +2024-10-09 14:33:48 | ERROR | stderr | For further information visit https://errors.pydantic.dev/2.9/u/schema-for-unknown-type +2024-10-09 14:34:00 | ERROR | stderr | ERROR: Exception in ASGI application +2024-10-09 14:34:00 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 270, in _init_core_attrs +2024-10-09 14:34:00 | ERROR | stderr | self._core_schema = _getattr_no_parents(self._type, '__pydantic_core_schema__') +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 112, in _getattr_no_parents +2024-10-09 14:34:00 | ERROR | stderr | raise AttributeError(attribute) +2024-10-09 14:34:00 | ERROR | stderr | AttributeError: __pydantic_core_schema__ +2024-10-09 14:34:00 | ERROR | stderr | +2024-10-09 14:34:00 | ERROR | stderr | During handling of the above exception, another exception occurred: +2024-10-09 14:34:00 | ERROR | stderr | +2024-10-09 14:34:00 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/protocols/http/h11_impl.py", line 406, in run_asgi +2024-10-09 14:34:00 | ERROR | stderr | result = await app( # type: ignore[func-returns-value] +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__ +2024-10-09 14:34:00 | ERROR | stderr | return await self.app(scope, receive, send) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/applications.py", line 1054, in __call__ +2024-10-09 14:34:00 | ERROR | stderr | await super().__call__(scope, receive, send) +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/applications.py", line 113, in __call__ +2024-10-09 14:34:00 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 187, in __call__ +2024-10-09 14:34:00 | ERROR | stderr | raise exc +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 165, in __call__ +2024-10-09 14:34:00 | ERROR | stderr | await self.app(scope, receive, _send) +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 93, in __call__ +2024-10-09 14:34:00 | ERROR | stderr | await self.simple_response(scope, receive, send, request_headers=headers) +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 144, in simple_response +2024-10-09 14:34:00 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 62, in __call__ +2024-10-09 14:34:00 | ERROR | stderr | await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:34:00 | ERROR | stderr | raise exc +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:34:00 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 715, in __call__ +2024-10-09 14:34:00 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 735, in app +2024-10-09 14:34:00 | ERROR | stderr | await route.handle(scope, receive, send) +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 288, in handle +2024-10-09 14:34:00 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 76, in app +2024-10-09 14:34:00 | ERROR | stderr | await wrap_app_handling_exceptions(app, request)(scope, receive, send) +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:34:00 | ERROR | stderr | raise exc +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:34:00 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 73, in app +2024-10-09 14:34:00 | ERROR | stderr | response = await f(request) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/routing.py", line 291, in app +2024-10-09 14:34:00 | ERROR | stderr | solved_result = await solve_dependencies( +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 656, in solve_dependencies +2024-10-09 14:34:00 | ERROR | stderr | ) = await request_body_to_args( # body_params checked above +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 881, in request_body_to_args +2024-10-09 14:34:00 | ERROR | stderr | fields_to_extract = get_cached_model_fields(first_field.type_) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 657, in get_cached_model_fields +2024-10-09 14:34:00 | ERROR | stderr | return get_model_fields(model) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 284, in get_model_fields +2024-10-09 14:34:00 | ERROR | stderr | return [ +2024-10-09 14:34:00 | ERROR | stderr | ^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 285, in +2024-10-09 14:34:00 | ERROR | stderr | ModelField(field_info=field_info, name=name) +2024-10-09 14:34:00 | ERROR | stderr | File "", line 6, in __init__ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 110, in __post_init__ +2024-10-09 14:34:00 | ERROR | stderr | self._type_adapter: TypeAdapter[Any] = TypeAdapter( +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 257, in __init__ +2024-10-09 14:34:00 | ERROR | stderr | self._init_core_attrs(rebuild_mocks=False) +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 135, in wrapped +2024-10-09 14:34:00 | ERROR | stderr | return func(self, *args, **kwargs) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 277, in _init_core_attrs +2024-10-09 14:34:00 | ERROR | stderr | self._core_schema = _get_schema(self._type, config_wrapper, parent_depth=self._parent_depth) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 95, in _get_schema +2024-10-09 14:34:00 | ERROR | stderr | schema = gen.generate_schema(type_) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:34:00 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 908, in _generate_schema_inner +2024-10-09 14:34:00 | ERROR | stderr | return self._annotated_schema(obj) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2028, in _annotated_schema +2024-10-09 14:34:00 | ERROR | stderr | schema = self._apply_annotations(source_type, annotations) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2107, in _apply_annotations +2024-10-09 14:34:00 | ERROR | stderr | schema = get_inner_schema(source_type) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:34:00 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2189, in new_handler +2024-10-09 14:34:00 | ERROR | stderr | schema = metadata_get_schema(source, get_inner_schema) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2185, in +2024-10-09 14:34:00 | ERROR | stderr | lambda source, handler: handler(source) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:34:00 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2088, in inner_handler +2024-10-09 14:34:00 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:34:00 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1029, in match_type +2024-10-09 14:34:00 | ERROR | stderr | return self._match_generic_type(obj, origin) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1058, in _match_generic_type +2024-10-09 14:34:00 | ERROR | stderr | return self._union_schema(obj) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1378, in _union_schema +2024-10-09 14:34:00 | ERROR | stderr | choices.append(self.generate_schema(arg)) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:34:00 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:34:00 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1038, in match_type +2024-10-09 14:34:00 | ERROR | stderr | return self._unknown_type_schema(obj) +2024-10-09 14:34:00 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:00 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 558, in _unknown_type_schema +2024-10-09 14:34:00 | ERROR | stderr | raise PydanticSchemaGenerationError( +2024-10-09 14:34:00 | ERROR | stderr | pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for . Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it. +2024-10-09 14:34:00 | ERROR | stderr | +2024-10-09 14:34:00 | ERROR | stderr | If you got this error by calling handler() within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema()` since we do not call `__get_pydantic_core_schema__` on `` otherwise to avoid infinite recursion. +2024-10-09 14:34:00 | ERROR | stderr | +2024-10-09 14:34:00 | ERROR | stderr | For further information visit https://errors.pydantic.dev/2.9/u/schema-for-unknown-type +2024-10-09 14:34:18 | INFO | stdout | Changes detected in: /Users/geminigby/PycharmProjects/llava_demo/UGround/app.py +2024-10-09 14:34:18 | ERROR | stderr | Exception in thread Thread-5: +2024-10-09 14:34:18 | ERROR | stderr | Exception in thread Thread-5: +2024-10-09 14:34:18 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:34:18 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:34:18 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/threading.py", line 1045, in _bootstrap_inner +2024-10-09 14:34:18 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/threading.py", line 1045, in _bootstrap_inner +2024-10-09 14:34:18 | ERROR | stderr | self.run() +2024-10-09 14:34:18 | ERROR | stderr | self.run() +2024-10-09 14:34:18 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/threading.py", line 982, in run +2024-10-09 14:34:18 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/threading.py", line 982, in run +2024-10-09 14:34:18 | ERROR | stderr | self._target(*self._args, **self._kwargs) +2024-10-09 14:34:18 | ERROR | stderr | self._target(*self._args, **self._kwargs) +2024-10-09 14:34:18 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/gradio/utils.py", line 218, in watchfn +2024-10-09 14:34:18 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/gradio/utils.py", line 218, in watchfn +2024-10-09 14:34:18 | ERROR | stderr | demo = getattr(module, reloader.demo_name) +2024-10-09 14:34:18 | ERROR | stderr | demo = getattr(module, reloader.demo_name) +2024-10-09 14:34:18 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:18 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:18 | ERROR | stderr | AttributeError: module 'app' has no attribute 'demo' +2024-10-09 14:34:18 | ERROR | stderr | AttributeError: module 'app' has no attribute 'demo' +2024-10-09 14:34:27 | INFO | stdout | Keyboard interruption in main thread... closing server. +2024-10-09 14:34:27 | INFO | stdout | Keyboard interruption in main thread... closing server. +2024-10-09 14:34:35 | INFO | stdout | args: Namespace(host='0.0.0.0', port=None, controller_url='http://localhost:10000', concurrency_count=1, model_list_mode='reload', share=False, moderate=False, embed=False) +2024-10-09 14:34:35 | INFO | stdout | Starting the controller +2024-10-09 14:34:35 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.controller', '--host', '0.0.0.0', '--port', '10000'] +2024-10-09 14:34:35 | INFO | stdout | Starting the model worker for the model osunlp/UGround +2024-10-09 14:34:35 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.model_worker', '--host', '0.0.0.0', '--controller', 'http://localhost:10000', '--model-path', 'osunlp/UGround', '--model-name', 'llava-v1.5-UGround_v1', '--use-flash-attn', '--load-8bit'] +2024-10-09 14:34:45 | ERROR | stderr | /Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/gradio/components/dropdown.py:163: UserWarning: The value passed into gr.Dropdown() is not in the list of choices. Please update the list of choices to include: or set allow_custom_value=True. +2024-10-09 14:34:45 | ERROR | stderr | warnings.warn( +2024-10-09 14:34:45 | INFO | stdout | Running on local URL: http://0.0.0.0:7860 +2024-10-09 14:34:46 | INFO | httpx | HTTP Request: GET http://localhost:7860/startup-events "HTTP/1.1 200 OK" +2024-10-09 14:34:46 | INFO | httpx | HTTP Request: HEAD http://localhost:7860/ "HTTP/1.1 200 OK" +2024-10-09 14:34:46 | INFO | stdout | +2024-10-09 14:34:46 | INFO | stdout | To create a public link, set `share=True` in `launch()`. +2024-10-09 14:34:46 | INFO | httpx | HTTP Request: GET https://checkip.amazonaws.com/ "HTTP/1.1 200 " +2024-10-09 14:34:46 | INFO | httpx | HTTP Request: GET https://checkip.amazonaws.com/ "HTTP/1.1 200 " +2024-10-09 14:34:46 | INFO | httpx | HTTP Request: GET https://api.gradio.app/pkg-version "HTTP/1.1 200 OK" +2024-10-09 14:34:46 | INFO | stdout | IMPORTANT: You are using gradio version 4.16.0, however version 4.29.0 is available, please upgrade. +2024-10-09 14:34:46 | INFO | stdout | -------- +2024-10-09 14:34:46 | INFO | httpx | HTTP Request: POST https://api.gradio.app/gradio-initiated-analytics/ "HTTP/1.1 200 OK" +2024-10-09 14:34:46 | INFO | httpx | HTTP Request: POST https://api.gradio.app/gradio-launched-telemetry/ "HTTP/1.1 200 OK" +2024-10-09 14:34:49 | ERROR | stderr | ERROR: Exception in ASGI application +2024-10-09 14:34:49 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 270, in _init_core_attrs +2024-10-09 14:34:49 | ERROR | stderr | self._core_schema = _getattr_no_parents(self._type, '__pydantic_core_schema__') +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 112, in _getattr_no_parents +2024-10-09 14:34:49 | ERROR | stderr | raise AttributeError(attribute) +2024-10-09 14:34:49 | ERROR | stderr | AttributeError: __pydantic_core_schema__ +2024-10-09 14:34:49 | ERROR | stderr | +2024-10-09 14:34:49 | ERROR | stderr | During handling of the above exception, another exception occurred: +2024-10-09 14:34:49 | ERROR | stderr | +2024-10-09 14:34:49 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/protocols/http/h11_impl.py", line 406, in run_asgi +2024-10-09 14:34:49 | ERROR | stderr | result = await app( # type: ignore[func-returns-value] +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__ +2024-10-09 14:34:49 | ERROR | stderr | return await self.app(scope, receive, send) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/applications.py", line 1054, in __call__ +2024-10-09 14:34:49 | ERROR | stderr | await super().__call__(scope, receive, send) +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/applications.py", line 113, in __call__ +2024-10-09 14:34:49 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 187, in __call__ +2024-10-09 14:34:49 | ERROR | stderr | raise exc +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 165, in __call__ +2024-10-09 14:34:49 | ERROR | stderr | await self.app(scope, receive, _send) +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 93, in __call__ +2024-10-09 14:34:49 | ERROR | stderr | await self.simple_response(scope, receive, send, request_headers=headers) +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 144, in simple_response +2024-10-09 14:34:49 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 62, in __call__ +2024-10-09 14:34:49 | ERROR | stderr | await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:34:49 | ERROR | stderr | raise exc +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:34:49 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 715, in __call__ +2024-10-09 14:34:49 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 735, in app +2024-10-09 14:34:49 | ERROR | stderr | await route.handle(scope, receive, send) +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 288, in handle +2024-10-09 14:34:49 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 76, in app +2024-10-09 14:34:49 | ERROR | stderr | await wrap_app_handling_exceptions(app, request)(scope, receive, send) +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:34:49 | ERROR | stderr | raise exc +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:34:49 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 73, in app +2024-10-09 14:34:49 | ERROR | stderr | response = await f(request) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/routing.py", line 291, in app +2024-10-09 14:34:49 | ERROR | stderr | solved_result = await solve_dependencies( +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 656, in solve_dependencies +2024-10-09 14:34:49 | ERROR | stderr | ) = await request_body_to_args( # body_params checked above +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 881, in request_body_to_args +2024-10-09 14:34:49 | ERROR | stderr | fields_to_extract = get_cached_model_fields(first_field.type_) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 657, in get_cached_model_fields +2024-10-09 14:34:49 | ERROR | stderr | return get_model_fields(model) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 284, in get_model_fields +2024-10-09 14:34:49 | ERROR | stderr | return [ +2024-10-09 14:34:49 | ERROR | stderr | ^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 285, in +2024-10-09 14:34:49 | ERROR | stderr | ModelField(field_info=field_info, name=name) +2024-10-09 14:34:49 | ERROR | stderr | File "", line 6, in __init__ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 110, in __post_init__ +2024-10-09 14:34:49 | ERROR | stderr | self._type_adapter: TypeAdapter[Any] = TypeAdapter( +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 257, in __init__ +2024-10-09 14:34:49 | ERROR | stderr | self._init_core_attrs(rebuild_mocks=False) +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 135, in wrapped +2024-10-09 14:34:49 | ERROR | stderr | return func(self, *args, **kwargs) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 277, in _init_core_attrs +2024-10-09 14:34:49 | ERROR | stderr | self._core_schema = _get_schema(self._type, config_wrapper, parent_depth=self._parent_depth) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 95, in _get_schema +2024-10-09 14:34:49 | ERROR | stderr | schema = gen.generate_schema(type_) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:34:49 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 908, in _generate_schema_inner +2024-10-09 14:34:49 | ERROR | stderr | return self._annotated_schema(obj) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2028, in _annotated_schema +2024-10-09 14:34:49 | ERROR | stderr | schema = self._apply_annotations(source_type, annotations) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2107, in _apply_annotations +2024-10-09 14:34:49 | ERROR | stderr | schema = get_inner_schema(source_type) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:34:49 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2189, in new_handler +2024-10-09 14:34:49 | ERROR | stderr | schema = metadata_get_schema(source, get_inner_schema) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2185, in +2024-10-09 14:34:49 | ERROR | stderr | lambda source, handler: handler(source) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:34:49 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2088, in inner_handler +2024-10-09 14:34:49 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:34:49 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1029, in match_type +2024-10-09 14:34:49 | ERROR | stderr | return self._match_generic_type(obj, origin) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1058, in _match_generic_type +2024-10-09 14:34:49 | ERROR | stderr | return self._union_schema(obj) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1378, in _union_schema +2024-10-09 14:34:49 | ERROR | stderr | choices.append(self.generate_schema(arg)) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:34:49 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:34:49 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1038, in match_type +2024-10-09 14:34:49 | ERROR | stderr | return self._unknown_type_schema(obj) +2024-10-09 14:34:49 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:49 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 558, in _unknown_type_schema +2024-10-09 14:34:49 | ERROR | stderr | raise PydanticSchemaGenerationError( +2024-10-09 14:34:49 | ERROR | stderr | pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for . Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it. +2024-10-09 14:34:49 | ERROR | stderr | +2024-10-09 14:34:49 | ERROR | stderr | If you got this error by calling handler() within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema()` since we do not call `__get_pydantic_core_schema__` on `` otherwise to avoid infinite recursion. +2024-10-09 14:34:49 | ERROR | stderr | +2024-10-09 14:34:49 | ERROR | stderr | For further information visit https://errors.pydantic.dev/2.9/u/schema-for-unknown-type +2024-10-09 14:34:54 | ERROR | stderr | ERROR: Exception in ASGI application +2024-10-09 14:34:54 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 270, in _init_core_attrs +2024-10-09 14:34:54 | ERROR | stderr | self._core_schema = _getattr_no_parents(self._type, '__pydantic_core_schema__') +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 112, in _getattr_no_parents +2024-10-09 14:34:54 | ERROR | stderr | raise AttributeError(attribute) +2024-10-09 14:34:54 | ERROR | stderr | AttributeError: __pydantic_core_schema__ +2024-10-09 14:34:54 | ERROR | stderr | +2024-10-09 14:34:54 | ERROR | stderr | During handling of the above exception, another exception occurred: +2024-10-09 14:34:54 | ERROR | stderr | +2024-10-09 14:34:54 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/protocols/http/h11_impl.py", line 406, in run_asgi +2024-10-09 14:34:54 | ERROR | stderr | result = await app( # type: ignore[func-returns-value] +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__ +2024-10-09 14:34:54 | ERROR | stderr | return await self.app(scope, receive, send) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/applications.py", line 1054, in __call__ +2024-10-09 14:34:54 | ERROR | stderr | await super().__call__(scope, receive, send) +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/applications.py", line 113, in __call__ +2024-10-09 14:34:54 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 187, in __call__ +2024-10-09 14:34:54 | ERROR | stderr | raise exc +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 165, in __call__ +2024-10-09 14:34:54 | ERROR | stderr | await self.app(scope, receive, _send) +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 93, in __call__ +2024-10-09 14:34:54 | ERROR | stderr | await self.simple_response(scope, receive, send, request_headers=headers) +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 144, in simple_response +2024-10-09 14:34:54 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 62, in __call__ +2024-10-09 14:34:54 | ERROR | stderr | await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:34:54 | ERROR | stderr | raise exc +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:34:54 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 715, in __call__ +2024-10-09 14:34:54 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 735, in app +2024-10-09 14:34:54 | ERROR | stderr | await route.handle(scope, receive, send) +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 288, in handle +2024-10-09 14:34:54 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 76, in app +2024-10-09 14:34:54 | ERROR | stderr | await wrap_app_handling_exceptions(app, request)(scope, receive, send) +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:34:54 | ERROR | stderr | raise exc +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:34:54 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 73, in app +2024-10-09 14:34:54 | ERROR | stderr | response = await f(request) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/routing.py", line 291, in app +2024-10-09 14:34:54 | ERROR | stderr | solved_result = await solve_dependencies( +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 656, in solve_dependencies +2024-10-09 14:34:54 | ERROR | stderr | ) = await request_body_to_args( # body_params checked above +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 881, in request_body_to_args +2024-10-09 14:34:54 | ERROR | stderr | fields_to_extract = get_cached_model_fields(first_field.type_) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 657, in get_cached_model_fields +2024-10-09 14:34:54 | ERROR | stderr | return get_model_fields(model) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 284, in get_model_fields +2024-10-09 14:34:54 | ERROR | stderr | return [ +2024-10-09 14:34:54 | ERROR | stderr | ^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 285, in +2024-10-09 14:34:54 | ERROR | stderr | ModelField(field_info=field_info, name=name) +2024-10-09 14:34:54 | ERROR | stderr | File "", line 6, in __init__ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 110, in __post_init__ +2024-10-09 14:34:54 | ERROR | stderr | self._type_adapter: TypeAdapter[Any] = TypeAdapter( +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 257, in __init__ +2024-10-09 14:34:54 | ERROR | stderr | self._init_core_attrs(rebuild_mocks=False) +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 135, in wrapped +2024-10-09 14:34:54 | ERROR | stderr | return func(self, *args, **kwargs) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 277, in _init_core_attrs +2024-10-09 14:34:54 | ERROR | stderr | self._core_schema = _get_schema(self._type, config_wrapper, parent_depth=self._parent_depth) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 95, in _get_schema +2024-10-09 14:34:54 | ERROR | stderr | schema = gen.generate_schema(type_) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:34:54 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 908, in _generate_schema_inner +2024-10-09 14:34:54 | ERROR | stderr | return self._annotated_schema(obj) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2028, in _annotated_schema +2024-10-09 14:34:54 | ERROR | stderr | schema = self._apply_annotations(source_type, annotations) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2107, in _apply_annotations +2024-10-09 14:34:54 | ERROR | stderr | schema = get_inner_schema(source_type) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:34:54 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2189, in new_handler +2024-10-09 14:34:54 | ERROR | stderr | schema = metadata_get_schema(source, get_inner_schema) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2185, in +2024-10-09 14:34:54 | ERROR | stderr | lambda source, handler: handler(source) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:34:54 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2088, in inner_handler +2024-10-09 14:34:54 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:34:54 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1029, in match_type +2024-10-09 14:34:54 | ERROR | stderr | return self._match_generic_type(obj, origin) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1058, in _match_generic_type +2024-10-09 14:34:54 | ERROR | stderr | return self._union_schema(obj) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1378, in _union_schema +2024-10-09 14:34:54 | ERROR | stderr | choices.append(self.generate_schema(arg)) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:34:54 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:34:54 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1038, in match_type +2024-10-09 14:34:54 | ERROR | stderr | return self._unknown_type_schema(obj) +2024-10-09 14:34:54 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:54 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 558, in _unknown_type_schema +2024-10-09 14:34:54 | ERROR | stderr | raise PydanticSchemaGenerationError( +2024-10-09 14:34:54 | ERROR | stderr | pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for . Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it. +2024-10-09 14:34:54 | ERROR | stderr | +2024-10-09 14:34:54 | ERROR | stderr | If you got this error by calling handler() within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema()` since we do not call `__get_pydantic_core_schema__` on `` otherwise to avoid infinite recursion. +2024-10-09 14:34:54 | ERROR | stderr | +2024-10-09 14:34:54 | ERROR | stderr | For further information visit https://errors.pydantic.dev/2.9/u/schema-for-unknown-type +2024-10-09 14:34:56 | ERROR | stderr | ERROR: Exception in ASGI application +2024-10-09 14:34:56 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 270, in _init_core_attrs +2024-10-09 14:34:56 | ERROR | stderr | self._core_schema = _getattr_no_parents(self._type, '__pydantic_core_schema__') +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 112, in _getattr_no_parents +2024-10-09 14:34:56 | ERROR | stderr | raise AttributeError(attribute) +2024-10-09 14:34:56 | ERROR | stderr | AttributeError: __pydantic_core_schema__ +2024-10-09 14:34:56 | ERROR | stderr | +2024-10-09 14:34:56 | ERROR | stderr | During handling of the above exception, another exception occurred: +2024-10-09 14:34:56 | ERROR | stderr | +2024-10-09 14:34:56 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/protocols/http/h11_impl.py", line 406, in run_asgi +2024-10-09 14:34:56 | ERROR | stderr | result = await app( # type: ignore[func-returns-value] +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | return await self.app(scope, receive, send) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/applications.py", line 1054, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | await super().__call__(scope, receive, send) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/applications.py", line 113, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 187, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | raise exc +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 165, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | await self.app(scope, receive, _send) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 93, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | await self.simple_response(scope, receive, send, request_headers=headers) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 144, in simple_response +2024-10-09 14:34:56 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 62, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:34:56 | ERROR | stderr | raise exc +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:34:56 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 715, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 735, in app +2024-10-09 14:34:56 | ERROR | stderr | await route.handle(scope, receive, send) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 288, in handle +2024-10-09 14:34:56 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 76, in app +2024-10-09 14:34:56 | ERROR | stderr | await wrap_app_handling_exceptions(app, request)(scope, receive, send) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:34:56 | ERROR | stderr | raise exc +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:34:56 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 73, in app +2024-10-09 14:34:56 | ERROR | stderr | response = await f(request) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/routing.py", line 291, in app +2024-10-09 14:34:56 | ERROR | stderr | solved_result = await solve_dependencies( +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 656, in solve_dependencies +2024-10-09 14:34:56 | ERROR | stderr | ) = await request_body_to_args( # body_params checked above +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 881, in request_body_to_args +2024-10-09 14:34:56 | ERROR | stderr | fields_to_extract = get_cached_model_fields(first_field.type_) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 657, in get_cached_model_fields +2024-10-09 14:34:56 | ERROR | stderr | return get_model_fields(model) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 284, in get_model_fields +2024-10-09 14:34:56 | ERROR | stderr | return [ +2024-10-09 14:34:56 | ERROR | stderr | ^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 285, in +2024-10-09 14:34:56 | ERROR | stderr | ModelField(field_info=field_info, name=name) +2024-10-09 14:34:56 | ERROR | stderr | File "", line 6, in __init__ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 110, in __post_init__ +2024-10-09 14:34:56 | ERROR | stderr | self._type_adapter: TypeAdapter[Any] = TypeAdapter( +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 257, in __init__ +2024-10-09 14:34:56 | ERROR | stderr | self._init_core_attrs(rebuild_mocks=False) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 135, in wrapped +2024-10-09 14:34:56 | ERROR | stderr | return func(self, *args, **kwargs) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 277, in _init_core_attrs +2024-10-09 14:34:56 | ERROR | stderr | self._core_schema = _get_schema(self._type, config_wrapper, parent_depth=self._parent_depth) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 95, in _get_schema +2024-10-09 14:34:56 | ERROR | stderr | schema = gen.generate_schema(type_) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:34:56 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 908, in _generate_schema_inner +2024-10-09 14:34:56 | ERROR | stderr | return self._annotated_schema(obj) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2028, in _annotated_schema +2024-10-09 14:34:56 | ERROR | stderr | schema = self._apply_annotations(source_type, annotations) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2107, in _apply_annotations +2024-10-09 14:34:56 | ERROR | stderr | schema = get_inner_schema(source_type) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2189, in new_handler +2024-10-09 14:34:56 | ERROR | stderr | schema = metadata_get_schema(source, get_inner_schema) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2185, in +2024-10-09 14:34:56 | ERROR | stderr | lambda source, handler: handler(source) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2088, in inner_handler +2024-10-09 14:34:56 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:34:56 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1029, in match_type +2024-10-09 14:34:56 | ERROR | stderr | return self._match_generic_type(obj, origin) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1058, in _match_generic_type +2024-10-09 14:34:56 | ERROR | stderr | return self._union_schema(obj) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1378, in _union_schema +2024-10-09 14:34:56 | ERROR | stderr | choices.append(self.generate_schema(arg)) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:34:56 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:34:56 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1038, in match_type +2024-10-09 14:34:56 | ERROR | stderr | return self._unknown_type_schema(obj) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 558, in _unknown_type_schema +2024-10-09 14:34:56 | ERROR | stderr | raise PydanticSchemaGenerationError( +2024-10-09 14:34:56 | ERROR | stderr | pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for . Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it. +2024-10-09 14:34:56 | ERROR | stderr | +2024-10-09 14:34:56 | ERROR | stderr | If you got this error by calling handler() within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema()` since we do not call `__get_pydantic_core_schema__` on `` otherwise to avoid infinite recursion. +2024-10-09 14:34:56 | ERROR | stderr | +2024-10-09 14:34:56 | ERROR | stderr | For further information visit https://errors.pydantic.dev/2.9/u/schema-for-unknown-type +2024-10-09 14:34:56 | ERROR | stderr | ERROR: Exception in ASGI application +2024-10-09 14:34:56 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 270, in _init_core_attrs +2024-10-09 14:34:56 | ERROR | stderr | self._core_schema = _getattr_no_parents(self._type, '__pydantic_core_schema__') +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 112, in _getattr_no_parents +2024-10-09 14:34:56 | ERROR | stderr | raise AttributeError(attribute) +2024-10-09 14:34:56 | ERROR | stderr | AttributeError: __pydantic_core_schema__ +2024-10-09 14:34:56 | ERROR | stderr | +2024-10-09 14:34:56 | ERROR | stderr | During handling of the above exception, another exception occurred: +2024-10-09 14:34:56 | ERROR | stderr | +2024-10-09 14:34:56 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/protocols/http/h11_impl.py", line 406, in run_asgi +2024-10-09 14:34:56 | ERROR | stderr | result = await app( # type: ignore[func-returns-value] +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | return await self.app(scope, receive, send) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/applications.py", line 1054, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | await super().__call__(scope, receive, send) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/applications.py", line 113, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 187, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | raise exc +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 165, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | await self.app(scope, receive, _send) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 93, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | await self.simple_response(scope, receive, send, request_headers=headers) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 144, in simple_response +2024-10-09 14:34:56 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 62, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:34:56 | ERROR | stderr | raise exc +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:34:56 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 715, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 735, in app +2024-10-09 14:34:56 | ERROR | stderr | await route.handle(scope, receive, send) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 288, in handle +2024-10-09 14:34:56 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 76, in app +2024-10-09 14:34:56 | ERROR | stderr | await wrap_app_handling_exceptions(app, request)(scope, receive, send) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:34:56 | ERROR | stderr | raise exc +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:34:56 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 73, in app +2024-10-09 14:34:56 | ERROR | stderr | response = await f(request) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/routing.py", line 291, in app +2024-10-09 14:34:56 | ERROR | stderr | solved_result = await solve_dependencies( +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 656, in solve_dependencies +2024-10-09 14:34:56 | ERROR | stderr | ) = await request_body_to_args( # body_params checked above +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 881, in request_body_to_args +2024-10-09 14:34:56 | ERROR | stderr | fields_to_extract = get_cached_model_fields(first_field.type_) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 657, in get_cached_model_fields +2024-10-09 14:34:56 | ERROR | stderr | return get_model_fields(model) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 284, in get_model_fields +2024-10-09 14:34:56 | ERROR | stderr | return [ +2024-10-09 14:34:56 | ERROR | stderr | ^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 285, in +2024-10-09 14:34:56 | ERROR | stderr | ModelField(field_info=field_info, name=name) +2024-10-09 14:34:56 | ERROR | stderr | File "", line 6, in __init__ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 110, in __post_init__ +2024-10-09 14:34:56 | ERROR | stderr | self._type_adapter: TypeAdapter[Any] = TypeAdapter( +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 257, in __init__ +2024-10-09 14:34:56 | ERROR | stderr | self._init_core_attrs(rebuild_mocks=False) +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 135, in wrapped +2024-10-09 14:34:56 | ERROR | stderr | return func(self, *args, **kwargs) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 277, in _init_core_attrs +2024-10-09 14:34:56 | ERROR | stderr | self._core_schema = _get_schema(self._type, config_wrapper, parent_depth=self._parent_depth) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 95, in _get_schema +2024-10-09 14:34:56 | ERROR | stderr | schema = gen.generate_schema(type_) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:34:56 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 908, in _generate_schema_inner +2024-10-09 14:34:56 | ERROR | stderr | return self._annotated_schema(obj) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2028, in _annotated_schema +2024-10-09 14:34:56 | ERROR | stderr | schema = self._apply_annotations(source_type, annotations) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2107, in _apply_annotations +2024-10-09 14:34:56 | ERROR | stderr | schema = get_inner_schema(source_type) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2189, in new_handler +2024-10-09 14:34:56 | ERROR | stderr | schema = metadata_get_schema(source, get_inner_schema) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2185, in +2024-10-09 14:34:56 | ERROR | stderr | lambda source, handler: handler(source) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:34:56 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2088, in inner_handler +2024-10-09 14:34:56 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:34:56 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1029, in match_type +2024-10-09 14:34:56 | ERROR | stderr | return self._match_generic_type(obj, origin) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1058, in _match_generic_type +2024-10-09 14:34:56 | ERROR | stderr | return self._union_schema(obj) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1378, in _union_schema +2024-10-09 14:34:56 | ERROR | stderr | choices.append(self.generate_schema(arg)) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:34:56 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:34:56 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1038, in match_type +2024-10-09 14:34:56 | ERROR | stderr | return self._unknown_type_schema(obj) +2024-10-09 14:34:56 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:56 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 558, in _unknown_type_schema +2024-10-09 14:34:56 | ERROR | stderr | raise PydanticSchemaGenerationError( +2024-10-09 14:34:56 | ERROR | stderr | pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for . Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it. +2024-10-09 14:34:56 | ERROR | stderr | +2024-10-09 14:34:56 | ERROR | stderr | If you got this error by calling handler() within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema()` since we do not call `__get_pydantic_core_schema__` on `` otherwise to avoid infinite recursion. +2024-10-09 14:34:56 | ERROR | stderr | +2024-10-09 14:34:56 | ERROR | stderr | For further information visit https://errors.pydantic.dev/2.9/u/schema-for-unknown-type +2024-10-09 14:34:57 | ERROR | stderr | ERROR: Exception in ASGI application +2024-10-09 14:34:57 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 270, in _init_core_attrs +2024-10-09 14:34:57 | ERROR | stderr | self._core_schema = _getattr_no_parents(self._type, '__pydantic_core_schema__') +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 112, in _getattr_no_parents +2024-10-09 14:34:57 | ERROR | stderr | raise AttributeError(attribute) +2024-10-09 14:34:57 | ERROR | stderr | AttributeError: __pydantic_core_schema__ +2024-10-09 14:34:57 | ERROR | stderr | +2024-10-09 14:34:57 | ERROR | stderr | During handling of the above exception, another exception occurred: +2024-10-09 14:34:57 | ERROR | stderr | +2024-10-09 14:34:57 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/protocols/http/h11_impl.py", line 406, in run_asgi +2024-10-09 14:34:57 | ERROR | stderr | result = await app( # type: ignore[func-returns-value] +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | return await self.app(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/applications.py", line 1054, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | await super().__call__(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/applications.py", line 113, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 187, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | raise exc +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 165, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | await self.app(scope, receive, _send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 93, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | await self.simple_response(scope, receive, send, request_headers=headers) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 144, in simple_response +2024-10-09 14:34:57 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 62, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:34:57 | ERROR | stderr | raise exc +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:34:57 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 715, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 735, in app +2024-10-09 14:34:57 | ERROR | stderr | await route.handle(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 288, in handle +2024-10-09 14:34:57 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 76, in app +2024-10-09 14:34:57 | ERROR | stderr | await wrap_app_handling_exceptions(app, request)(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:34:57 | ERROR | stderr | raise exc +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:34:57 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 73, in app +2024-10-09 14:34:57 | ERROR | stderr | response = await f(request) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/routing.py", line 291, in app +2024-10-09 14:34:57 | ERROR | stderr | solved_result = await solve_dependencies( +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 656, in solve_dependencies +2024-10-09 14:34:57 | ERROR | stderr | ) = await request_body_to_args( # body_params checked above +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 881, in request_body_to_args +2024-10-09 14:34:57 | ERROR | stderr | fields_to_extract = get_cached_model_fields(first_field.type_) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 657, in get_cached_model_fields +2024-10-09 14:34:57 | ERROR | stderr | return get_model_fields(model) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 284, in get_model_fields +2024-10-09 14:34:57 | ERROR | stderr | return [ +2024-10-09 14:34:57 | ERROR | stderr | ^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 285, in +2024-10-09 14:34:57 | ERROR | stderr | ModelField(field_info=field_info, name=name) +2024-10-09 14:34:57 | ERROR | stderr | File "", line 6, in __init__ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 110, in __post_init__ +2024-10-09 14:34:57 | ERROR | stderr | self._type_adapter: TypeAdapter[Any] = TypeAdapter( +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 257, in __init__ +2024-10-09 14:34:57 | ERROR | stderr | self._init_core_attrs(rebuild_mocks=False) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 135, in wrapped +2024-10-09 14:34:57 | ERROR | stderr | return func(self, *args, **kwargs) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 277, in _init_core_attrs +2024-10-09 14:34:57 | ERROR | stderr | self._core_schema = _get_schema(self._type, config_wrapper, parent_depth=self._parent_depth) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 95, in _get_schema +2024-10-09 14:34:57 | ERROR | stderr | schema = gen.generate_schema(type_) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:34:57 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 908, in _generate_schema_inner +2024-10-09 14:34:57 | ERROR | stderr | return self._annotated_schema(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2028, in _annotated_schema +2024-10-09 14:34:57 | ERROR | stderr | schema = self._apply_annotations(source_type, annotations) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2107, in _apply_annotations +2024-10-09 14:34:57 | ERROR | stderr | schema = get_inner_schema(source_type) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2189, in new_handler +2024-10-09 14:34:57 | ERROR | stderr | schema = metadata_get_schema(source, get_inner_schema) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2185, in +2024-10-09 14:34:57 | ERROR | stderr | lambda source, handler: handler(source) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2088, in inner_handler +2024-10-09 14:34:57 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:34:57 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1029, in match_type +2024-10-09 14:34:57 | ERROR | stderr | return self._match_generic_type(obj, origin) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1058, in _match_generic_type +2024-10-09 14:34:57 | ERROR | stderr | return self._union_schema(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1378, in _union_schema +2024-10-09 14:34:57 | ERROR | stderr | choices.append(self.generate_schema(arg)) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:34:57 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:34:57 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1038, in match_type +2024-10-09 14:34:57 | ERROR | stderr | return self._unknown_type_schema(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 558, in _unknown_type_schema +2024-10-09 14:34:57 | ERROR | stderr | raise PydanticSchemaGenerationError( +2024-10-09 14:34:57 | ERROR | stderr | pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for . Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it. +2024-10-09 14:34:57 | ERROR | stderr | +2024-10-09 14:34:57 | ERROR | stderr | If you got this error by calling handler() within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema()` since we do not call `__get_pydantic_core_schema__` on `` otherwise to avoid infinite recursion. +2024-10-09 14:34:57 | ERROR | stderr | +2024-10-09 14:34:57 | ERROR | stderr | For further information visit https://errors.pydantic.dev/2.9/u/schema-for-unknown-type +2024-10-09 14:34:57 | ERROR | stderr | ERROR: Exception in ASGI application +2024-10-09 14:34:57 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 270, in _init_core_attrs +2024-10-09 14:34:57 | ERROR | stderr | self._core_schema = _getattr_no_parents(self._type, '__pydantic_core_schema__') +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 112, in _getattr_no_parents +2024-10-09 14:34:57 | ERROR | stderr | raise AttributeError(attribute) +2024-10-09 14:34:57 | ERROR | stderr | AttributeError: __pydantic_core_schema__ +2024-10-09 14:34:57 | ERROR | stderr | +2024-10-09 14:34:57 | ERROR | stderr | During handling of the above exception, another exception occurred: +2024-10-09 14:34:57 | ERROR | stderr | +2024-10-09 14:34:57 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/protocols/http/h11_impl.py", line 406, in run_asgi +2024-10-09 14:34:57 | ERROR | stderr | result = await app( # type: ignore[func-returns-value] +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | return await self.app(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/applications.py", line 1054, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | await super().__call__(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/applications.py", line 113, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 187, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | raise exc +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 165, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | await self.app(scope, receive, _send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 93, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | await self.simple_response(scope, receive, send, request_headers=headers) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 144, in simple_response +2024-10-09 14:34:57 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 62, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:34:57 | ERROR | stderr | raise exc +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:34:57 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 715, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 735, in app +2024-10-09 14:34:57 | ERROR | stderr | await route.handle(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 288, in handle +2024-10-09 14:34:57 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 76, in app +2024-10-09 14:34:57 | ERROR | stderr | await wrap_app_handling_exceptions(app, request)(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:34:57 | ERROR | stderr | raise exc +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:34:57 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 73, in app +2024-10-09 14:34:57 | ERROR | stderr | response = await f(request) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/routing.py", line 291, in app +2024-10-09 14:34:57 | ERROR | stderr | solved_result = await solve_dependencies( +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 656, in solve_dependencies +2024-10-09 14:34:57 | ERROR | stderr | ) = await request_body_to_args( # body_params checked above +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 881, in request_body_to_args +2024-10-09 14:34:57 | ERROR | stderr | fields_to_extract = get_cached_model_fields(first_field.type_) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 657, in get_cached_model_fields +2024-10-09 14:34:57 | ERROR | stderr | return get_model_fields(model) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 284, in get_model_fields +2024-10-09 14:34:57 | ERROR | stderr | return [ +2024-10-09 14:34:57 | ERROR | stderr | ^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 285, in +2024-10-09 14:34:57 | ERROR | stderr | ModelField(field_info=field_info, name=name) +2024-10-09 14:34:57 | ERROR | stderr | File "", line 6, in __init__ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 110, in __post_init__ +2024-10-09 14:34:57 | ERROR | stderr | self._type_adapter: TypeAdapter[Any] = TypeAdapter( +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 257, in __init__ +2024-10-09 14:34:57 | ERROR | stderr | self._init_core_attrs(rebuild_mocks=False) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 135, in wrapped +2024-10-09 14:34:57 | ERROR | stderr | return func(self, *args, **kwargs) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 277, in _init_core_attrs +2024-10-09 14:34:57 | ERROR | stderr | self._core_schema = _get_schema(self._type, config_wrapper, parent_depth=self._parent_depth) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 95, in _get_schema +2024-10-09 14:34:57 | ERROR | stderr | schema = gen.generate_schema(type_) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:34:57 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 908, in _generate_schema_inner +2024-10-09 14:34:57 | ERROR | stderr | return self._annotated_schema(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2028, in _annotated_schema +2024-10-09 14:34:57 | ERROR | stderr | schema = self._apply_annotations(source_type, annotations) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2107, in _apply_annotations +2024-10-09 14:34:57 | ERROR | stderr | schema = get_inner_schema(source_type) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2189, in new_handler +2024-10-09 14:34:57 | ERROR | stderr | schema = metadata_get_schema(source, get_inner_schema) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2185, in +2024-10-09 14:34:57 | ERROR | stderr | lambda source, handler: handler(source) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2088, in inner_handler +2024-10-09 14:34:57 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:34:57 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1029, in match_type +2024-10-09 14:34:57 | ERROR | stderr | return self._match_generic_type(obj, origin) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1058, in _match_generic_type +2024-10-09 14:34:57 | ERROR | stderr | return self._union_schema(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1378, in _union_schema +2024-10-09 14:34:57 | ERROR | stderr | choices.append(self.generate_schema(arg)) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:34:57 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:34:57 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1038, in match_type +2024-10-09 14:34:57 | ERROR | stderr | return self._unknown_type_schema(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 558, in _unknown_type_schema +2024-10-09 14:34:57 | ERROR | stderr | raise PydanticSchemaGenerationError( +2024-10-09 14:34:57 | ERROR | stderr | pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for . Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it. +2024-10-09 14:34:57 | ERROR | stderr | +2024-10-09 14:34:57 | ERROR | stderr | If you got this error by calling handler() within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema()` since we do not call `__get_pydantic_core_schema__` on `` otherwise to avoid infinite recursion. +2024-10-09 14:34:57 | ERROR | stderr | +2024-10-09 14:34:57 | ERROR | stderr | For further information visit https://errors.pydantic.dev/2.9/u/schema-for-unknown-type +2024-10-09 14:34:57 | ERROR | stderr | ERROR: Exception in ASGI application +2024-10-09 14:34:57 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 270, in _init_core_attrs +2024-10-09 14:34:57 | ERROR | stderr | self._core_schema = _getattr_no_parents(self._type, '__pydantic_core_schema__') +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 112, in _getattr_no_parents +2024-10-09 14:34:57 | ERROR | stderr | raise AttributeError(attribute) +2024-10-09 14:34:57 | ERROR | stderr | AttributeError: __pydantic_core_schema__ +2024-10-09 14:34:57 | ERROR | stderr | +2024-10-09 14:34:57 | ERROR | stderr | During handling of the above exception, another exception occurred: +2024-10-09 14:34:57 | ERROR | stderr | +2024-10-09 14:34:57 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/protocols/http/h11_impl.py", line 406, in run_asgi +2024-10-09 14:34:57 | ERROR | stderr | result = await app( # type: ignore[func-returns-value] +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | return await self.app(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/applications.py", line 1054, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | await super().__call__(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/applications.py", line 113, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 187, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | raise exc +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 165, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | await self.app(scope, receive, _send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 93, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | await self.simple_response(scope, receive, send, request_headers=headers) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 144, in simple_response +2024-10-09 14:34:57 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 62, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:34:57 | ERROR | stderr | raise exc +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:34:57 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 715, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 735, in app +2024-10-09 14:34:57 | ERROR | stderr | await route.handle(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 288, in handle +2024-10-09 14:34:57 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 76, in app +2024-10-09 14:34:57 | ERROR | stderr | await wrap_app_handling_exceptions(app, request)(scope, receive, send) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:34:57 | ERROR | stderr | raise exc +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:34:57 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 73, in app +2024-10-09 14:34:57 | ERROR | stderr | response = await f(request) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/routing.py", line 291, in app +2024-10-09 14:34:57 | ERROR | stderr | solved_result = await solve_dependencies( +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 656, in solve_dependencies +2024-10-09 14:34:57 | ERROR | stderr | ) = await request_body_to_args( # body_params checked above +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 881, in request_body_to_args +2024-10-09 14:34:57 | ERROR | stderr | fields_to_extract = get_cached_model_fields(first_field.type_) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 657, in get_cached_model_fields +2024-10-09 14:34:57 | ERROR | stderr | return get_model_fields(model) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 284, in get_model_fields +2024-10-09 14:34:57 | ERROR | stderr | return [ +2024-10-09 14:34:57 | ERROR | stderr | ^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 285, in +2024-10-09 14:34:57 | ERROR | stderr | ModelField(field_info=field_info, name=name) +2024-10-09 14:34:57 | ERROR | stderr | File "", line 6, in __init__ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 110, in __post_init__ +2024-10-09 14:34:57 | ERROR | stderr | self._type_adapter: TypeAdapter[Any] = TypeAdapter( +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 257, in __init__ +2024-10-09 14:34:57 | ERROR | stderr | self._init_core_attrs(rebuild_mocks=False) +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 135, in wrapped +2024-10-09 14:34:57 | ERROR | stderr | return func(self, *args, **kwargs) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 277, in _init_core_attrs +2024-10-09 14:34:57 | ERROR | stderr | self._core_schema = _get_schema(self._type, config_wrapper, parent_depth=self._parent_depth) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 95, in _get_schema +2024-10-09 14:34:57 | ERROR | stderr | schema = gen.generate_schema(type_) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:34:57 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 908, in _generate_schema_inner +2024-10-09 14:34:57 | ERROR | stderr | return self._annotated_schema(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2028, in _annotated_schema +2024-10-09 14:34:57 | ERROR | stderr | schema = self._apply_annotations(source_type, annotations) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2107, in _apply_annotations +2024-10-09 14:34:57 | ERROR | stderr | schema = get_inner_schema(source_type) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2189, in new_handler +2024-10-09 14:34:57 | ERROR | stderr | schema = metadata_get_schema(source, get_inner_schema) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2185, in +2024-10-09 14:34:57 | ERROR | stderr | lambda source, handler: handler(source) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:34:57 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2088, in inner_handler +2024-10-09 14:34:57 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:34:57 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1029, in match_type +2024-10-09 14:34:57 | ERROR | stderr | return self._match_generic_type(obj, origin) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1058, in _match_generic_type +2024-10-09 14:34:57 | ERROR | stderr | return self._union_schema(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1378, in _union_schema +2024-10-09 14:34:57 | ERROR | stderr | choices.append(self.generate_schema(arg)) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:34:57 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:34:57 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1038, in match_type +2024-10-09 14:34:57 | ERROR | stderr | return self._unknown_type_schema(obj) +2024-10-09 14:34:57 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:34:57 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 558, in _unknown_type_schema +2024-10-09 14:34:57 | ERROR | stderr | raise PydanticSchemaGenerationError( +2024-10-09 14:34:57 | ERROR | stderr | pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for . Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it. +2024-10-09 14:34:57 | ERROR | stderr | +2024-10-09 14:34:57 | ERROR | stderr | If you got this error by calling handler() within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema()` since we do not call `__get_pydantic_core_schema__` on `` otherwise to avoid infinite recursion. +2024-10-09 14:34:57 | ERROR | stderr | +2024-10-09 14:34:57 | ERROR | stderr | For further information visit https://errors.pydantic.dev/2.9/u/schema-for-unknown-type +2024-10-09 14:35:03 | ERROR | stderr | ERROR: Exception in ASGI application +2024-10-09 14:35:03 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 270, in _init_core_attrs +2024-10-09 14:35:03 | ERROR | stderr | self._core_schema = _getattr_no_parents(self._type, '__pydantic_core_schema__') +2024-10-09 14:35:03 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 112, in _getattr_no_parents +2024-10-09 14:35:03 | ERROR | stderr | raise AttributeError(attribute) +2024-10-09 14:35:03 | ERROR | stderr | AttributeError: __pydantic_core_schema__ +2024-10-09 14:35:03 | ERROR | stderr | +2024-10-09 14:35:03 | ERROR | stderr | During handling of the above exception, another exception occurred: +2024-10-09 14:35:03 | ERROR | stderr | +2024-10-09 14:35:03 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/protocols/http/h11_impl.py", line 406, in run_asgi +2024-10-09 14:35:03 | ERROR | stderr | result = await app( # type: ignore[func-returns-value] +2024-10-09 14:35:03 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__ +2024-10-09 14:35:03 | ERROR | stderr | return await self.app(scope, receive, send) +2024-10-09 14:35:03 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/applications.py", line 1054, in __call__ +2024-10-09 14:35:03 | ERROR | stderr | await super().__call__(scope, receive, send) +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/applications.py", line 113, in __call__ +2024-10-09 14:35:03 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 187, in __call__ +2024-10-09 14:35:03 | ERROR | stderr | raise exc +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 165, in __call__ +2024-10-09 14:35:03 | ERROR | stderr | await self.app(scope, receive, _send) +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 93, in __call__ +2024-10-09 14:35:03 | ERROR | stderr | await self.simple_response(scope, receive, send, request_headers=headers) +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 144, in simple_response +2024-10-09 14:35:03 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 62, in __call__ +2024-10-09 14:35:03 | ERROR | stderr | await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:35:03 | ERROR | stderr | raise exc +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:35:03 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 715, in __call__ +2024-10-09 14:35:03 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 735, in app +2024-10-09 14:35:03 | ERROR | stderr | await route.handle(scope, receive, send) +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 288, in handle +2024-10-09 14:35:03 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 76, in app +2024-10-09 14:35:03 | ERROR | stderr | await wrap_app_handling_exceptions(app, request)(scope, receive, send) +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:35:03 | ERROR | stderr | raise exc +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:35:03 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 73, in app +2024-10-09 14:35:03 | ERROR | stderr | response = await f(request) +2024-10-09 14:35:03 | ERROR | stderr | ^^^^^^^^^^^^^^^^ +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/routing.py", line 291, in app +2024-10-09 14:35:03 | ERROR | stderr | solved_result = await solve_dependencies( +2024-10-09 14:35:03 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 656, in solve_dependencies +2024-10-09 14:35:03 | ERROR | stderr | ) = await request_body_to_args( # body_params checked above +2024-10-09 14:35:03 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 881, in request_body_to_args +2024-10-09 14:35:03 | ERROR | stderr | fields_to_extract = get_cached_model_fields(first_field.type_) +2024-10-09 14:35:03 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 657, in get_cached_model_fields +2024-10-09 14:35:03 | ERROR | stderr | return get_model_fields(model) +2024-10-09 14:35:03 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 284, in get_model_fields +2024-10-09 14:35:03 | ERROR | stderr | return [ +2024-10-09 14:35:03 | ERROR | stderr | ^ +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 285, in +2024-10-09 14:35:03 | ERROR | stderr | ModelField(field_info=field_info, name=name) +2024-10-09 14:35:03 | ERROR | stderr | File "", line 6, in __init__ +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 110, in __post_init__ +2024-10-09 14:35:03 | ERROR | stderr | self._type_adapter: TypeAdapter[Any] = TypeAdapter( +2024-10-09 14:35:03 | ERROR | stderr | ^^^^^^^^^^^^ +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 257, in __init__ +2024-10-09 14:35:03 | ERROR | stderr | self._init_core_attrs(rebuild_mocks=False) +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 135, in wrapped +2024-10-09 14:35:03 | ERROR | stderr | return func(self, *args, **kwargs) +2024-10-09 14:35:03 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 277, in _init_core_attrs +2024-10-09 14:35:03 | ERROR | stderr | self._core_schema = _get_schema(self._type, config_wrapper, parent_depth=self._parent_depth) +2024-10-09 14:35:03 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 95, in _get_schema +2024-10-09 14:35:03 | ERROR | stderr | schema = gen.generate_schema(type_) +2024-10-09 14:35:03 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:35:03 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:35:03 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 908, in _generate_schema_inner +2024-10-09 14:35:03 | ERROR | stderr | return self._annotated_schema(obj) +2024-10-09 14:35:03 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2028, in _annotated_schema +2024-10-09 14:35:03 | ERROR | stderr | schema = self._apply_annotations(source_type, annotations) +2024-10-09 14:35:03 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2107, in _apply_annotations +2024-10-09 14:35:03 | ERROR | stderr | schema = get_inner_schema(source_type) +2024-10-09 14:35:03 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:03 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:35:04 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2189, in new_handler +2024-10-09 14:35:04 | ERROR | stderr | schema = metadata_get_schema(source, get_inner_schema) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2185, in +2024-10-09 14:35:04 | ERROR | stderr | lambda source, handler: handler(source) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:35:04 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2088, in inner_handler +2024-10-09 14:35:04 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:35:04 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1029, in match_type +2024-10-09 14:35:04 | ERROR | stderr | return self._match_generic_type(obj, origin) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1058, in _match_generic_type +2024-10-09 14:35:04 | ERROR | stderr | return self._union_schema(obj) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1378, in _union_schema +2024-10-09 14:35:04 | ERROR | stderr | choices.append(self.generate_schema(arg)) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:35:04 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:35:04 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1038, in match_type +2024-10-09 14:35:04 | ERROR | stderr | return self._unknown_type_schema(obj) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 558, in _unknown_type_schema +2024-10-09 14:35:04 | ERROR | stderr | raise PydanticSchemaGenerationError( +2024-10-09 14:35:04 | ERROR | stderr | pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for . Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it. +2024-10-09 14:35:04 | ERROR | stderr | +2024-10-09 14:35:04 | ERROR | stderr | If you got this error by calling handler() within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema()` since we do not call `__get_pydantic_core_schema__` on `` otherwise to avoid infinite recursion. +2024-10-09 14:35:04 | ERROR | stderr | +2024-10-09 14:35:04 | ERROR | stderr | For further information visit https://errors.pydantic.dev/2.9/u/schema-for-unknown-type +2024-10-09 14:35:04 | ERROR | stderr | ERROR: Exception in ASGI application +2024-10-09 14:35:04 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 270, in _init_core_attrs +2024-10-09 14:35:04 | ERROR | stderr | self._core_schema = _getattr_no_parents(self._type, '__pydantic_core_schema__') +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 112, in _getattr_no_parents +2024-10-09 14:35:04 | ERROR | stderr | raise AttributeError(attribute) +2024-10-09 14:35:04 | ERROR | stderr | AttributeError: __pydantic_core_schema__ +2024-10-09 14:35:04 | ERROR | stderr | +2024-10-09 14:35:04 | ERROR | stderr | During handling of the above exception, another exception occurred: +2024-10-09 14:35:04 | ERROR | stderr | +2024-10-09 14:35:04 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/protocols/http/h11_impl.py", line 406, in run_asgi +2024-10-09 14:35:04 | ERROR | stderr | result = await app( # type: ignore[func-returns-value] +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__ +2024-10-09 14:35:04 | ERROR | stderr | return await self.app(scope, receive, send) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/applications.py", line 1054, in __call__ +2024-10-09 14:35:04 | ERROR | stderr | await super().__call__(scope, receive, send) +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/applications.py", line 113, in __call__ +2024-10-09 14:35:04 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 187, in __call__ +2024-10-09 14:35:04 | ERROR | stderr | raise exc +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 165, in __call__ +2024-10-09 14:35:04 | ERROR | stderr | await self.app(scope, receive, _send) +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 93, in __call__ +2024-10-09 14:35:04 | ERROR | stderr | await self.simple_response(scope, receive, send, request_headers=headers) +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 144, in simple_response +2024-10-09 14:35:04 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 62, in __call__ +2024-10-09 14:35:04 | ERROR | stderr | await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:35:04 | ERROR | stderr | raise exc +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:35:04 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 715, in __call__ +2024-10-09 14:35:04 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 735, in app +2024-10-09 14:35:04 | ERROR | stderr | await route.handle(scope, receive, send) +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 288, in handle +2024-10-09 14:35:04 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 76, in app +2024-10-09 14:35:04 | ERROR | stderr | await wrap_app_handling_exceptions(app, request)(scope, receive, send) +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:35:04 | ERROR | stderr | raise exc +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:35:04 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 73, in app +2024-10-09 14:35:04 | ERROR | stderr | response = await f(request) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/routing.py", line 291, in app +2024-10-09 14:35:04 | ERROR | stderr | solved_result = await solve_dependencies( +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 656, in solve_dependencies +2024-10-09 14:35:04 | ERROR | stderr | ) = await request_body_to_args( # body_params checked above +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 881, in request_body_to_args +2024-10-09 14:35:04 | ERROR | stderr | fields_to_extract = get_cached_model_fields(first_field.type_) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 657, in get_cached_model_fields +2024-10-09 14:35:04 | ERROR | stderr | return get_model_fields(model) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 284, in get_model_fields +2024-10-09 14:35:04 | ERROR | stderr | return [ +2024-10-09 14:35:04 | ERROR | stderr | ^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 285, in +2024-10-09 14:35:04 | ERROR | stderr | ModelField(field_info=field_info, name=name) +2024-10-09 14:35:04 | ERROR | stderr | File "", line 6, in __init__ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 110, in __post_init__ +2024-10-09 14:35:04 | ERROR | stderr | self._type_adapter: TypeAdapter[Any] = TypeAdapter( +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 257, in __init__ +2024-10-09 14:35:04 | ERROR | stderr | self._init_core_attrs(rebuild_mocks=False) +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 135, in wrapped +2024-10-09 14:35:04 | ERROR | stderr | return func(self, *args, **kwargs) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 277, in _init_core_attrs +2024-10-09 14:35:04 | ERROR | stderr | self._core_schema = _get_schema(self._type, config_wrapper, parent_depth=self._parent_depth) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 95, in _get_schema +2024-10-09 14:35:04 | ERROR | stderr | schema = gen.generate_schema(type_) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:35:04 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 908, in _generate_schema_inner +2024-10-09 14:35:04 | ERROR | stderr | return self._annotated_schema(obj) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2028, in _annotated_schema +2024-10-09 14:35:04 | ERROR | stderr | schema = self._apply_annotations(source_type, annotations) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2107, in _apply_annotations +2024-10-09 14:35:04 | ERROR | stderr | schema = get_inner_schema(source_type) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:35:04 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2189, in new_handler +2024-10-09 14:35:04 | ERROR | stderr | schema = metadata_get_schema(source, get_inner_schema) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2185, in +2024-10-09 14:35:04 | ERROR | stderr | lambda source, handler: handler(source) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:35:04 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2088, in inner_handler +2024-10-09 14:35:04 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:35:04 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1029, in match_type +2024-10-09 14:35:04 | ERROR | stderr | return self._match_generic_type(obj, origin) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1058, in _match_generic_type +2024-10-09 14:35:04 | ERROR | stderr | return self._union_schema(obj) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1378, in _union_schema +2024-10-09 14:35:04 | ERROR | stderr | choices.append(self.generate_schema(arg)) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:35:04 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:35:04 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1038, in match_type +2024-10-09 14:35:04 | ERROR | stderr | return self._unknown_type_schema(obj) +2024-10-09 14:35:04 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:04 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 558, in _unknown_type_schema +2024-10-09 14:35:04 | ERROR | stderr | raise PydanticSchemaGenerationError( +2024-10-09 14:35:04 | ERROR | stderr | pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for . Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it. +2024-10-09 14:35:04 | ERROR | stderr | +2024-10-09 14:35:04 | ERROR | stderr | If you got this error by calling handler() within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema()` since we do not call `__get_pydantic_core_schema__` on `` otherwise to avoid infinite recursion. +2024-10-09 14:35:04 | ERROR | stderr | +2024-10-09 14:35:04 | ERROR | stderr | For further information visit https://errors.pydantic.dev/2.9/u/schema-for-unknown-type +2024-10-09 14:35:06 | ERROR | stderr | ERROR: Exception in ASGI application +2024-10-09 14:35:06 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 270, in _init_core_attrs +2024-10-09 14:35:06 | ERROR | stderr | self._core_schema = _getattr_no_parents(self._type, '__pydantic_core_schema__') +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 112, in _getattr_no_parents +2024-10-09 14:35:06 | ERROR | stderr | raise AttributeError(attribute) +2024-10-09 14:35:06 | ERROR | stderr | AttributeError: __pydantic_core_schema__ +2024-10-09 14:35:06 | ERROR | stderr | +2024-10-09 14:35:06 | ERROR | stderr | During handling of the above exception, another exception occurred: +2024-10-09 14:35:06 | ERROR | stderr | +2024-10-09 14:35:06 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/protocols/http/h11_impl.py", line 406, in run_asgi +2024-10-09 14:35:06 | ERROR | stderr | result = await app( # type: ignore[func-returns-value] +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__ +2024-10-09 14:35:06 | ERROR | stderr | return await self.app(scope, receive, send) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/applications.py", line 1054, in __call__ +2024-10-09 14:35:06 | ERROR | stderr | await super().__call__(scope, receive, send) +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/applications.py", line 113, in __call__ +2024-10-09 14:35:06 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 187, in __call__ +2024-10-09 14:35:06 | ERROR | stderr | raise exc +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 165, in __call__ +2024-10-09 14:35:06 | ERROR | stderr | await self.app(scope, receive, _send) +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 93, in __call__ +2024-10-09 14:35:06 | ERROR | stderr | await self.simple_response(scope, receive, send, request_headers=headers) +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 144, in simple_response +2024-10-09 14:35:06 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 62, in __call__ +2024-10-09 14:35:06 | ERROR | stderr | await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:35:06 | ERROR | stderr | raise exc +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:35:06 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 715, in __call__ +2024-10-09 14:35:06 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 735, in app +2024-10-09 14:35:06 | ERROR | stderr | await route.handle(scope, receive, send) +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 288, in handle +2024-10-09 14:35:06 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 76, in app +2024-10-09 14:35:06 | ERROR | stderr | await wrap_app_handling_exceptions(app, request)(scope, receive, send) +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:35:06 | ERROR | stderr | raise exc +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:35:06 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 73, in app +2024-10-09 14:35:06 | ERROR | stderr | response = await f(request) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/routing.py", line 291, in app +2024-10-09 14:35:06 | ERROR | stderr | solved_result = await solve_dependencies( +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 656, in solve_dependencies +2024-10-09 14:35:06 | ERROR | stderr | ) = await request_body_to_args( # body_params checked above +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 881, in request_body_to_args +2024-10-09 14:35:06 | ERROR | stderr | fields_to_extract = get_cached_model_fields(first_field.type_) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 657, in get_cached_model_fields +2024-10-09 14:35:06 | ERROR | stderr | return get_model_fields(model) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 284, in get_model_fields +2024-10-09 14:35:06 | ERROR | stderr | return [ +2024-10-09 14:35:06 | ERROR | stderr | ^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 285, in +2024-10-09 14:35:06 | ERROR | stderr | ModelField(field_info=field_info, name=name) +2024-10-09 14:35:06 | ERROR | stderr | File "", line 6, in __init__ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 110, in __post_init__ +2024-10-09 14:35:06 | ERROR | stderr | self._type_adapter: TypeAdapter[Any] = TypeAdapter( +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 257, in __init__ +2024-10-09 14:35:06 | ERROR | stderr | self._init_core_attrs(rebuild_mocks=False) +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 135, in wrapped +2024-10-09 14:35:06 | ERROR | stderr | return func(self, *args, **kwargs) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 277, in _init_core_attrs +2024-10-09 14:35:06 | ERROR | stderr | self._core_schema = _get_schema(self._type, config_wrapper, parent_depth=self._parent_depth) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 95, in _get_schema +2024-10-09 14:35:06 | ERROR | stderr | schema = gen.generate_schema(type_) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:35:06 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 908, in _generate_schema_inner +2024-10-09 14:35:06 | ERROR | stderr | return self._annotated_schema(obj) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2028, in _annotated_schema +2024-10-09 14:35:06 | ERROR | stderr | schema = self._apply_annotations(source_type, annotations) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2107, in _apply_annotations +2024-10-09 14:35:06 | ERROR | stderr | schema = get_inner_schema(source_type) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:35:06 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2189, in new_handler +2024-10-09 14:35:06 | ERROR | stderr | schema = metadata_get_schema(source, get_inner_schema) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2185, in +2024-10-09 14:35:06 | ERROR | stderr | lambda source, handler: handler(source) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:35:06 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2088, in inner_handler +2024-10-09 14:35:06 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:35:06 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1029, in match_type +2024-10-09 14:35:06 | ERROR | stderr | return self._match_generic_type(obj, origin) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1058, in _match_generic_type +2024-10-09 14:35:06 | ERROR | stderr | return self._union_schema(obj) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1378, in _union_schema +2024-10-09 14:35:06 | ERROR | stderr | choices.append(self.generate_schema(arg)) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:35:06 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:35:06 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1038, in match_type +2024-10-09 14:35:06 | ERROR | stderr | return self._unknown_type_schema(obj) +2024-10-09 14:35:06 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:35:06 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 558, in _unknown_type_schema +2024-10-09 14:35:06 | ERROR | stderr | raise PydanticSchemaGenerationError( +2024-10-09 14:35:06 | ERROR | stderr | pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for . Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it. +2024-10-09 14:35:06 | ERROR | stderr | +2024-10-09 14:35:06 | ERROR | stderr | If you got this error by calling handler() within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema()` since we do not call `__get_pydantic_core_schema__` on `` otherwise to avoid infinite recursion. +2024-10-09 14:35:06 | ERROR | stderr | +2024-10-09 14:35:06 | ERROR | stderr | For further information visit https://errors.pydantic.dev/2.9/u/schema-for-unknown-type +2024-10-09 14:38:19 | INFO | stdout | Changes detected in: /Users/geminigby/PycharmProjects/llava_demo/UGround/llava/serve/gradio_web_server.py +2024-10-09 14:38:19 | ERROR | stderr | Exception in thread Thread-5: +2024-10-09 14:38:19 | ERROR | stderr | Exception in thread Thread-5: +2024-10-09 14:38:19 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:38:19 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:38:19 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/threading.py", line 1045, in _bootstrap_inner +2024-10-09 14:38:19 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/threading.py", line 1045, in _bootstrap_inner +2024-10-09 14:38:19 | ERROR | stderr | self.run() +2024-10-09 14:38:19 | ERROR | stderr | self.run() +2024-10-09 14:38:19 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/threading.py", line 982, in run +2024-10-09 14:38:19 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/threading.py", line 982, in run +2024-10-09 14:38:19 | ERROR | stderr | self._target(*self._args, **self._kwargs) +2024-10-09 14:38:19 | ERROR | stderr | self._target(*self._args, **self._kwargs) +2024-10-09 14:38:19 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/gradio/utils.py", line 218, in watchfn +2024-10-09 14:38:19 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/gradio/utils.py", line 218, in watchfn +2024-10-09 14:38:19 | ERROR | stderr | demo = getattr(module, reloader.demo_name) +2024-10-09 14:38:19 | ERROR | stderr | demo = getattr(module, reloader.demo_name) +2024-10-09 14:38:19 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:38:19 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:38:19 | ERROR | stderr | AttributeError: module 'app' has no attribute 'demo' +2024-10-09 14:38:19 | ERROR | stderr | AttributeError: module 'app' has no attribute 'demo' +2024-10-09 14:38:20 | INFO | stdout | Keyboard interruption in main thread... closing server. +2024-10-09 14:38:20 | INFO | stdout | Keyboard interruption in main thread... closing server. +2024-10-09 14:38:28 | INFO | stdout | args: Namespace(host='0.0.0.0', port=None, controller_url='http://localhost:10000', concurrency_count=1, model_list_mode='reload', share=False, moderate=False, embed=False) +2024-10-09 14:38:28 | INFO | stdout | Starting the controller +2024-10-09 14:38:28 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.controller', '--host', '0.0.0.0', '--port', '10000'] +2024-10-09 14:38:28 | INFO | stdout | Starting the model worker for the model osunlp/UGround +2024-10-09 14:38:28 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.model_worker', '--host', '0.0.0.0', '--controller', 'http://localhost:10000', '--model-path', 'osunlp/UGround', '--model-name', 'llava-v1.5-UGround_v1', '--use-flash-attn', '--load-8bit'] +2024-10-09 14:38:38 | INFO | stdout | name 'model_selector' is not defined +2024-10-09 14:38:38 | INFO | httpx | HTTP Request: GET https://checkip.amazonaws.com/ "HTTP/1.1 200 " +2024-10-09 14:38:38 | INFO | httpx | HTTP Request: GET https://api.gradio.app/pkg-version "HTTP/1.1 200 OK" +2024-10-09 14:38:38 | INFO | stdout | IMPORTANT: You are using gradio version 4.16.0, however version 4.29.0 is available, please upgrade. +2024-10-09 14:38:38 | INFO | stdout | -------- +2024-10-09 14:38:38 | INFO | httpx | HTTP Request: POST https://api.gradio.app/gradio-initiated-analytics/ "HTTP/1.1 200 OK" +2024-10-09 14:39:51 | INFO | stdout | args: Namespace(host='0.0.0.0', port=None, controller_url='http://localhost:10000', concurrency_count=1, model_list_mode='reload', share=False, moderate=False, embed=False) +2024-10-09 14:39:51 | INFO | stdout | Starting the controller +2024-10-09 14:39:51 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.controller', '--host', '0.0.0.0', '--port', '10000'] +2024-10-09 14:39:51 | INFO | stdout | Starting the model worker for the model osunlp/UGround +2024-10-09 14:39:51 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.model_worker', '--host', '0.0.0.0', '--controller', 'http://localhost:10000', '--model-path', 'osunlp/UGround', '--model-name', 'llava-v1.5-UGround_v1', '--use-flash-attn', '--load-8bit'] +2024-10-09 14:40:02 | INFO | stdout | name 'model_selector' is not defined +2024-10-09 14:40:02 | INFO | httpx | HTTP Request: GET https://checkip.amazonaws.com/ "HTTP/1.1 200 " +2024-10-09 14:40:02 | INFO | httpx | HTTP Request: GET https://api.gradio.app/pkg-version "HTTP/1.1 200 OK" +2024-10-09 14:40:02 | INFO | stdout | IMPORTANT: You are using gradio version 4.16.0, however version 4.29.0 is available, please upgrade. +2024-10-09 14:40:02 | INFO | stdout | -------- +2024-10-09 14:40:02 | INFO | httpx | HTTP Request: POST https://api.gradio.app/gradio-initiated-analytics/ "HTTP/1.1 200 OK" +2024-10-09 14:40:32 | INFO | stdout | args: Namespace(host='0.0.0.0', port=None, controller_url='http://localhost:10000', concurrency_count=1, model_list_mode='reload', share=False, moderate=False, embed=False) +2024-10-09 14:40:32 | INFO | stdout | Starting the controller +2024-10-09 14:40:32 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.controller', '--host', '0.0.0.0', '--port', '10000'] +2024-10-09 14:40:32 | INFO | stdout | Starting the model worker for the model osunlp/UGround +2024-10-09 14:40:32 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.model_worker', '--host', '0.0.0.0', '--controller', 'http://localhost:10000', '--model-path', 'osunlp/UGround', '--model-name', 'llava-v1.5-UGround_v1', '--use-flash-attn', '--load-8bit'] +2024-10-09 14:40:42 | ERROR | stderr | /Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/gradio/components/dropdown.py:163: UserWarning: The value passed into gr.Dropdown() is not in the list of choices. Please update the list of choices to include: or set allow_custom_value=True. +2024-10-09 14:40:42 | ERROR | stderr | warnings.warn( +2024-10-09 14:40:42 | INFO | stdout | Running on local URL: http://0.0.0.0:7860 +2024-10-09 14:40:42 | INFO | httpx | HTTP Request: GET http://localhost:7860/startup-events "HTTP/1.1 200 OK" +2024-10-09 14:40:42 | INFO | httpx | HTTP Request: HEAD http://localhost:7860/ "HTTP/1.1 200 OK" +2024-10-09 14:40:42 | INFO | stdout | +2024-10-09 14:40:42 | INFO | stdout | To create a public link, set `share=True` in `launch()`. +2024-10-09 14:40:42 | INFO | httpx | HTTP Request: GET https://checkip.amazonaws.com/ "HTTP/1.1 200 " +2024-10-09 14:40:42 | INFO | httpx | HTTP Request: GET https://checkip.amazonaws.com/ "HTTP/1.1 200 " +2024-10-09 14:40:42 | INFO | httpx | HTTP Request: GET https://api.gradio.app/pkg-version "HTTP/1.1 200 OK" +2024-10-09 14:40:42 | INFO | stdout | IMPORTANT: You are using gradio version 4.16.0, however version 4.29.0 is available, please upgrade. +2024-10-09 14:40:42 | INFO | stdout | -------- +2024-10-09 14:40:42 | INFO | httpx | HTTP Request: POST https://api.gradio.app/gradio-initiated-analytics/ "HTTP/1.1 200 OK" +2024-10-09 14:40:43 | INFO | httpx | HTTP Request: POST https://api.gradio.app/gradio-launched-telemetry/ "HTTP/1.1 200 OK" +2024-10-09 14:40:50 | ERROR | stderr | ERROR: Exception in ASGI application +2024-10-09 14:40:50 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 270, in _init_core_attrs +2024-10-09 14:40:50 | ERROR | stderr | self._core_schema = _getattr_no_parents(self._type, '__pydantic_core_schema__') +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 112, in _getattr_no_parents +2024-10-09 14:40:50 | ERROR | stderr | raise AttributeError(attribute) +2024-10-09 14:40:50 | ERROR | stderr | AttributeError: __pydantic_core_schema__ +2024-10-09 14:40:50 | ERROR | stderr | +2024-10-09 14:40:50 | ERROR | stderr | During handling of the above exception, another exception occurred: +2024-10-09 14:40:50 | ERROR | stderr | +2024-10-09 14:40:50 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/protocols/http/h11_impl.py", line 406, in run_asgi +2024-10-09 14:40:50 | ERROR | stderr | result = await app( # type: ignore[func-returns-value] +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__ +2024-10-09 14:40:50 | ERROR | stderr | return await self.app(scope, receive, send) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/applications.py", line 1054, in __call__ +2024-10-09 14:40:50 | ERROR | stderr | await super().__call__(scope, receive, send) +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/applications.py", line 113, in __call__ +2024-10-09 14:40:50 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 187, in __call__ +2024-10-09 14:40:50 | ERROR | stderr | raise exc +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/errors.py", line 165, in __call__ +2024-10-09 14:40:50 | ERROR | stderr | await self.app(scope, receive, _send) +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 93, in __call__ +2024-10-09 14:40:50 | ERROR | stderr | await self.simple_response(scope, receive, send, request_headers=headers) +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/cors.py", line 144, in simple_response +2024-10-09 14:40:50 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 62, in __call__ +2024-10-09 14:40:50 | ERROR | stderr | await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:40:50 | ERROR | stderr | raise exc +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:40:50 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 715, in __call__ +2024-10-09 14:40:50 | ERROR | stderr | await self.middleware_stack(scope, receive, send) +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 735, in app +2024-10-09 14:40:50 | ERROR | stderr | await route.handle(scope, receive, send) +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 288, in handle +2024-10-09 14:40:50 | ERROR | stderr | await self.app(scope, receive, send) +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 76, in app +2024-10-09 14:40:50 | ERROR | stderr | await wrap_app_handling_exceptions(app, request)(scope, receive, send) +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app +2024-10-09 14:40:50 | ERROR | stderr | raise exc +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app +2024-10-09 14:40:50 | ERROR | stderr | await app(scope, receive, sender) +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/starlette/routing.py", line 73, in app +2024-10-09 14:40:50 | ERROR | stderr | response = await f(request) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/routing.py", line 291, in app +2024-10-09 14:40:50 | ERROR | stderr | solved_result = await solve_dependencies( +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 656, in solve_dependencies +2024-10-09 14:40:50 | ERROR | stderr | ) = await request_body_to_args( # body_params checked above +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 881, in request_body_to_args +2024-10-09 14:40:50 | ERROR | stderr | fields_to_extract = get_cached_model_fields(first_field.type_) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 657, in get_cached_model_fields +2024-10-09 14:40:50 | ERROR | stderr | return get_model_fields(model) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 284, in get_model_fields +2024-10-09 14:40:50 | ERROR | stderr | return [ +2024-10-09 14:40:50 | ERROR | stderr | ^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 285, in +2024-10-09 14:40:50 | ERROR | stderr | ModelField(field_info=field_info, name=name) +2024-10-09 14:40:50 | ERROR | stderr | File "", line 6, in __init__ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/fastapi/_compat.py", line 110, in __post_init__ +2024-10-09 14:40:50 | ERROR | stderr | self._type_adapter: TypeAdapter[Any] = TypeAdapter( +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 257, in __init__ +2024-10-09 14:40:50 | ERROR | stderr | self._init_core_attrs(rebuild_mocks=False) +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 135, in wrapped +2024-10-09 14:40:50 | ERROR | stderr | return func(self, *args, **kwargs) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 277, in _init_core_attrs +2024-10-09 14:40:50 | ERROR | stderr | self._core_schema = _get_schema(self._type, config_wrapper, parent_depth=self._parent_depth) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/type_adapter.py", line 95, in _get_schema +2024-10-09 14:40:50 | ERROR | stderr | schema = gen.generate_schema(type_) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:40:50 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 908, in _generate_schema_inner +2024-10-09 14:40:50 | ERROR | stderr | return self._annotated_schema(obj) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2028, in _annotated_schema +2024-10-09 14:40:50 | ERROR | stderr | schema = self._apply_annotations(source_type, annotations) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2107, in _apply_annotations +2024-10-09 14:40:50 | ERROR | stderr | schema = get_inner_schema(source_type) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:40:50 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2189, in new_handler +2024-10-09 14:40:50 | ERROR | stderr | schema = metadata_get_schema(source, get_inner_schema) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2185, in +2024-10-09 14:40:50 | ERROR | stderr | lambda source, handler: handler(source) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__ +2024-10-09 14:40:50 | ERROR | stderr | schema = self._handler(source_type) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 2088, in inner_handler +2024-10-09 14:40:50 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:40:50 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1029, in match_type +2024-10-09 14:40:50 | ERROR | stderr | return self._match_generic_type(obj, origin) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1058, in _match_generic_type +2024-10-09 14:40:50 | ERROR | stderr | return self._union_schema(obj) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1378, in _union_schema +2024-10-09 14:40:50 | ERROR | stderr | choices.append(self.generate_schema(arg)) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema +2024-10-09 14:40:50 | ERROR | stderr | schema = self._generate_schema_inner(obj) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 929, in _generate_schema_inner +2024-10-09 14:40:50 | ERROR | stderr | return self.match_type(obj) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 1038, in match_type +2024-10-09 14:40:50 | ERROR | stderr | return self._unknown_type_schema(obj) +2024-10-09 14:40:50 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:40:50 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py", line 558, in _unknown_type_schema +2024-10-09 14:40:50 | ERROR | stderr | raise PydanticSchemaGenerationError( +2024-10-09 14:40:50 | ERROR | stderr | pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for . Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it. +2024-10-09 14:40:50 | ERROR | stderr | +2024-10-09 14:40:50 | ERROR | stderr | If you got this error by calling handler() within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema()` since we do not call `__get_pydantic_core_schema__` on `` otherwise to avoid infinite recursion. +2024-10-09 14:40:50 | ERROR | stderr | +2024-10-09 14:40:50 | ERROR | stderr | For further information visit https://errors.pydantic.dev/2.9/u/schema-for-unknown-type +2024-10-09 14:42:19 | INFO | stdout | Changes detected in: /Users/geminigby/PycharmProjects/llava_demo/UGround/llava/serve/gradio_web_server.py +2024-10-09 14:42:19 | ERROR | stderr | Exception in thread Thread-5: +2024-10-09 14:42:19 | ERROR | stderr | Exception in thread Thread-5: +2024-10-09 14:42:19 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:42:19 | ERROR | stderr | Traceback (most recent call last): +2024-10-09 14:42:19 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/threading.py", line 1045, in _bootstrap_inner +2024-10-09 14:42:19 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/threading.py", line 1045, in _bootstrap_inner +2024-10-09 14:42:19 | ERROR | stderr | self.run() +2024-10-09 14:42:19 | ERROR | stderr | self.run() +2024-10-09 14:42:19 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/threading.py", line 982, in run +2024-10-09 14:42:19 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/threading.py", line 982, in run +2024-10-09 14:42:19 | ERROR | stderr | self._target(*self._args, **self._kwargs) +2024-10-09 14:42:19 | ERROR | stderr | self._target(*self._args, **self._kwargs) +2024-10-09 14:42:19 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/gradio/utils.py", line 218, in watchfn +2024-10-09 14:42:19 | ERROR | stderr | File "/Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/gradio/utils.py", line 218, in watchfn +2024-10-09 14:42:19 | ERROR | stderr | demo = getattr(module, reloader.demo_name) +2024-10-09 14:42:19 | ERROR | stderr | demo = getattr(module, reloader.demo_name) +2024-10-09 14:42:19 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:42:19 | ERROR | stderr | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2024-10-09 14:42:19 | ERROR | stderr | AttributeError: module 'app' has no attribute 'demo' +2024-10-09 14:42:19 | ERROR | stderr | AttributeError: module 'app' has no attribute 'demo' +2024-10-09 14:47:47 | INFO | stdout | Keyboard interruption in main thread... closing server. +2024-10-09 14:47:47 | INFO | stdout | Keyboard interruption in main thread... closing server. +2024-10-09 14:47:53 | INFO | stdout | args: Namespace(host='0.0.0.0', port=None, controller_url='http://localhost:10000', concurrency_count=1, model_list_mode='reload', share=False, moderate=False, embed=False) +2024-10-09 14:47:53 | INFO | stdout | Starting the controller +2024-10-09 14:47:53 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.controller', '--host', '0.0.0.0', '--port', '10000'] +2024-10-09 14:47:53 | INFO | stdout | Starting the model worker for the model osunlp/UGround +2024-10-09 14:47:53 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.model_worker', '--host', '0.0.0.0', '--controller', 'http://localhost:10000', '--model-path', 'osunlp/UGround', '--model-name', 'llava-v1.5-UGround_v1', '--use-flash-attn', '--load-8bit'] +2024-10-09 14:48:03 | INFO | stdout | 'str' object has no attribute '_id' +2024-10-09 14:48:03 | INFO | httpx | HTTP Request: GET https://checkip.amazonaws.com/ "HTTP/1.1 200 " +2024-10-09 14:48:04 | INFO | httpx | HTTP Request: GET https://api.gradio.app/pkg-version "HTTP/1.1 200 OK" +2024-10-09 14:48:04 | INFO | stdout | IMPORTANT: You are using gradio version 4.16.0, however version 4.29.0 is available, please upgrade. +2024-10-09 14:48:04 | INFO | stdout | -------- +2024-10-09 14:48:04 | INFO | httpx | HTTP Request: POST https://api.gradio.app/gradio-initiated-analytics/ "HTTP/1.1 200 OK" +2024-10-09 14:50:54 | INFO | stdout | args: Namespace(host='0.0.0.0', port=None, controller_url='http://localhost:10000', concurrency_count=1, model_list_mode='reload', share=False, moderate=False, embed=False) +2024-10-09 14:50:54 | INFO | stdout | Starting the controller +2024-10-09 14:50:54 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.controller', '--host', '0.0.0.0', '--port', '10000'] +2024-10-09 14:50:54 | INFO | stdout | Starting the model worker for the model osunlp/UGround +2024-10-09 14:50:54 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.model_worker', '--host', '0.0.0.0', '--controller', 'http://localhost:10000', '--model-path', 'osunlp/UGround', '--model-name', 'llava-v1.5-UGround_v1', '--use-flash-attn', '--load-8bit'] +2024-10-09 14:51:04 | ERROR | stderr | /Users/geminigby/miniconda3/envs/UGround/lib/python3.11/site-packages/gradio/components/dropdown.py:163: UserWarning: The value passed into gr.Dropdown() is not in the list of choices. Please update the list of choices to include: or set allow_custom_value=True. +2024-10-09 14:51:04 | ERROR | stderr | warnings.warn( +2024-10-09 14:51:04 | INFO | stdout | 'int' object has no attribute '_id' +2024-10-09 14:51:04 | INFO | httpx | HTTP Request: GET https://checkip.amazonaws.com/ "HTTP/1.1 200 " +2024-10-09 14:51:05 | INFO | httpx | HTTP Request: GET https://api.gradio.app/pkg-version "HTTP/1.1 200 OK" +2024-10-09 14:51:05 | INFO | stdout | IMPORTANT: You are using gradio version 4.16.0, however version 4.29.0 is available, please upgrade. +2024-10-09 14:51:05 | INFO | stdout | -------- +2024-10-09 14:51:05 | INFO | httpx | HTTP Request: POST https://api.gradio.app/gradio-initiated-analytics/ "HTTP/1.1 200 OK" +2024-10-09 14:51:42 | INFO | stdout | args: Namespace(host='0.0.0.0', port=None, controller_url='http://localhost:10000', concurrency_count=1, model_list_mode='reload', share=False, moderate=False, embed=False) +2024-10-09 14:51:42 | INFO | stdout | Starting the controller +2024-10-09 14:51:42 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.controller', '--host', '0.0.0.0', '--port', '10000'] +2024-10-09 14:51:42 | INFO | stdout | Starting the model worker for the model osunlp/UGround +2024-10-09 14:51:42 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.model_worker', '--host', '0.0.0.0', '--controller', 'http://localhost:10000', '--model-path', 'osunlp/UGround', '--model-name', 'llava-v1.5-UGround_v1', '--use-flash-attn', '--load-8bit'] +2024-10-09 14:51:52 | INFO | stdout | list index out of range +2024-10-09 14:51:52 | INFO | httpx | HTTP Request: GET https://checkip.amazonaws.com/ "HTTP/1.1 200 " +2024-10-09 14:51:52 | INFO | httpx | HTTP Request: GET https://api.gradio.app/pkg-version "HTTP/1.1 200 OK" +2024-10-09 14:51:52 | INFO | stdout | IMPORTANT: You are using gradio version 4.16.0, however version 4.29.0 is available, please upgrade. +2024-10-09 14:51:52 | INFO | stdout | -------- +2024-10-09 14:51:52 | INFO | httpx | HTTP Request: POST https://api.gradio.app/gradio-initiated-analytics/ "HTTP/1.1 200 OK" +2024-10-09 14:53:02 | INFO | stdout | args: Namespace(host='0.0.0.0', port=None, controller_url='http://localhost:10000', concurrency_count=1, model_list_mode='reload', share=False, moderate=False, embed=False) +2024-10-09 14:53:02 | INFO | stdout | Starting the controller +2024-10-09 14:53:02 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.controller', '--host', '0.0.0.0', '--port', '10000'] +2024-10-09 14:53:02 | INFO | stdout | Starting the model worker for the model osunlp/UGround +2024-10-09 14:53:02 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.model_worker', '--host', '0.0.0.0', '--controller', 'http://localhost:10000', '--model-path', 'osunlp/UGround', '--model-name', 'llava-v1.5-UGround_v1', '--use-flash-attn', '--load-8bit'] +2024-10-09 14:53:13 | INFO | stdout | list index out of range +2024-10-09 14:53:13 | INFO | httpx | HTTP Request: GET https://checkip.amazonaws.com/ "HTTP/1.1 200 " +2024-10-09 14:53:13 | INFO | httpx | HTTP Request: GET https://api.gradio.app/pkg-version "HTTP/1.1 200 OK" +2024-10-09 14:53:13 | INFO | stdout | IMPORTANT: You are using gradio version 4.16.0, however version 4.29.0 is available, please upgrade. +2024-10-09 14:53:13 | INFO | stdout | -------- +2024-10-09 14:53:13 | INFO | httpx | HTTP Request: POST https://api.gradio.app/gradio-initiated-analytics/ "HTTP/1.1 200 OK" +2024-10-09 14:53:55 | INFO | stdout | args: Namespace(host='0.0.0.0', port=None, controller_url='http://localhost:10000', concurrency_count=1, model_list_mode='reload', share=False, moderate=False, embed=False) +2024-10-09 14:53:55 | INFO | stdout | Starting the controller +2024-10-09 14:53:55 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.controller', '--host', '0.0.0.0', '--port', '10000'] +2024-10-09 14:53:55 | INFO | stdout | Starting the model worker for the model osunlp/UGround +2024-10-09 14:53:55 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.model_worker', '--host', '0.0.0.0', '--controller', 'http://localhost:10000', '--model-path', 'osunlp/UGround', '--model-name', 'llava-v1.5-UGround_v1', '--use-flash-attn', '--load-8bit'] +2024-10-09 14:54:06 | INFO | stdout | list index out of range +2024-10-09 14:54:06 | INFO | httpx | HTTP Request: GET https://checkip.amazonaws.com/ "HTTP/1.1 200 " +2024-10-09 14:54:06 | INFO | httpx | HTTP Request: GET https://api.gradio.app/pkg-version "HTTP/1.1 200 OK" +2024-10-09 14:54:06 | INFO | stdout | IMPORTANT: You are using gradio version 4.16.0, however version 4.29.0 is available, please upgrade. +2024-10-09 14:54:06 | INFO | stdout | -------- +2024-10-09 14:54:06 | INFO | httpx | HTTP Request: POST https://api.gradio.app/gradio-initiated-analytics/ "HTTP/1.1 200 OK" +2024-10-09 14:54:35 | INFO | stdout | args: Namespace(host='0.0.0.0', port=None, controller_url='http://localhost:10000', concurrency_count=1, model_list_mode='reload', share=False, moderate=False, embed=False) +2024-10-09 14:54:35 | INFO | stdout | Starting the controller +2024-10-09 14:54:35 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.controller', '--host', '0.0.0.0', '--port', '10000'] +2024-10-09 14:54:35 | INFO | stdout | Starting the model worker for the model osunlp/UGround +2024-10-09 14:54:35 | INFO | stdout | ['/Users/geminigby/miniconda3/envs/UGround/bin/python', '-m', 'llava.serve.model_worker', '--host', '0.0.0.0', '--controller', 'http://localhost:10000', '--model-path', 'osunlp/UGround', '--model-name', 'llava-v1.5-UGround_v1', '--use-flash-attn', '--load-8bit'] +2024-10-09 14:54:45 | INFO | stdout | list index out of range +2024-10-09 14:54:45 | INFO | httpx | HTTP Request: GET https://checkip.amazonaws.com/ "HTTP/1.1 200 " +2024-10-09 14:54:45 | INFO | httpx | HTTP Request: GET https://api.gradio.app/pkg-version "HTTP/1.1 200 OK" +2024-10-09 14:54:45 | INFO | stdout | IMPORTANT: You are using gradio version 4.16.0, however version 4.29.0 is available, please upgrade. +2024-10-09 14:54:45 | INFO | stdout | -------- +2024-10-09 14:54:45 | INFO | httpx | HTTP Request: POST https://api.gradio.app/gradio-initiated-analytics/ "HTTP/1.1 200 OK" diff --git a/llava/__init__.py b/llava/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..841b5bc202236baf5678513f2fa05b1d9b285ae4 --- /dev/null +++ b/llava/__init__.py @@ -0,0 +1,2 @@ +from .model import LlavaLlamaForCausalLM +# from .model.language_model.llava_llama import LlavaLlamaForCausalLM \ No newline at end of file diff --git a/llava/__pycache__/__init__.cpython-311.pyc b/llava/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67fdff39352a0026ac361db023a5c3b6ba43a463 Binary files /dev/null and b/llava/__pycache__/__init__.cpython-311.pyc differ diff --git a/llava/__pycache__/constants.cpython-311.pyc b/llava/__pycache__/constants.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21aa624277b8beae337df77eeadb7a4225d03bd1 Binary files /dev/null and b/llava/__pycache__/constants.cpython-311.pyc differ diff --git a/llava/__pycache__/conversation.cpython-311.pyc b/llava/__pycache__/conversation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62779716fdae2fdaf1976bee311244f86125389e Binary files /dev/null and b/llava/__pycache__/conversation.cpython-311.pyc differ diff --git a/llava/__pycache__/mm_utils.cpython-311.pyc b/llava/__pycache__/mm_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13ddc2b86c04210ffa67a65938ed79a5dd901cc3 Binary files /dev/null and b/llava/__pycache__/mm_utils.cpython-311.pyc differ diff --git a/llava/__pycache__/utils.cpython-311.pyc b/llava/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbf49f760a2434710b0265f594149c26445997c6 Binary files /dev/null and b/llava/__pycache__/utils.cpython-311.pyc differ diff --git a/llava/constants.py b/llava/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..374be090510b302de9882d880c755787a8eafe11 --- /dev/null +++ b/llava/constants.py @@ -0,0 +1,13 @@ +CONTROLLER_HEART_BEAT_EXPIRATION = 30 +WORKER_HEART_BEAT_INTERVAL = 15 + +LOGDIR = "." + +# Model Constants +IGNORE_INDEX = -100 +IMAGE_TOKEN_INDEX = -200 +DEFAULT_IMAGE_TOKEN = "" +DEFAULT_IMAGE_PATCH_TOKEN = "" +DEFAULT_IM_START_TOKEN = "" +DEFAULT_IM_END_TOKEN = "" +IMAGE_PLACEHOLDER = "" diff --git a/llava/conversation.py b/llava/conversation.py new file mode 100644 index 0000000000000000000000000000000000000000..42450e03210806f05d8b8438abed6d9c7e04718a --- /dev/null +++ b/llava/conversation.py @@ -0,0 +1,418 @@ +import dataclasses +from enum import auto, Enum +from typing import List, Tuple +import base64 +from io import BytesIO +from PIL import Image + + +class SeparatorStyle(Enum): + """Different separator style.""" + SINGLE = auto() + TWO = auto() + MPT = auto() + PLAIN = auto() + LLAMA_2 = auto() + + +@dataclasses.dataclass +class Conversation: + """A class that keeps all conversation history.""" + system: str + roles: List[str] + messages: List[List[str]] + offset: int + sep_style: SeparatorStyle = SeparatorStyle.SINGLE + sep: str = "###" + sep2: str = None + version: str = "Unknown" + + skip_next: bool = False + + def get_prompt(self): + messages = [self.messages[0],self.messages[-1]] + if len(messages) > 0 and type(messages[0][1]) is tuple: + messages = self.messages.copy() + init_role, init_msg = messages[0].copy() + init_msg = init_msg[0].replace("", "").strip() + if 'mmtag' in self.version: + messages[0] = (init_role, init_msg) + messages.insert(0, (self.roles[0], "")) + messages.insert(1, (self.roles[1], "Received.")) + else: + messages[0] = (init_role, "\n" + init_msg) + + if self.sep_style == SeparatorStyle.SINGLE: + ret = self.system + self.sep + for role, message in messages: + if message: + if type(message) is tuple: + message, _, _ = message + ret += role + ": " + message + self.sep + else: + ret += role + ":" + elif self.sep_style == SeparatorStyle.TWO: + seps = [self.sep, self.sep2] + ret = self.system + seps[0] + for i, (role, message) in enumerate(messages): + if message: + if type(message) is tuple: + message, _, _ = message + ret += role + ": " + message + seps[i % 2] + else: + ret += role + ":" + elif self.sep_style == SeparatorStyle.MPT: + ret = self.system + self.sep + for role, message in messages: + if message: + if type(message) is tuple: + message, _, _ = message + ret += role + message + self.sep + else: + ret += role + elif self.sep_style == SeparatorStyle.LLAMA_2: + wrap_sys = lambda msg: f"<>\n{msg}\n<>\n\n" if len(msg) > 0 else msg + wrap_inst = lambda msg: f"[INST] {msg} [/INST]" + ret = "" + + for i, (role, message) in enumerate(messages): + if i == 0: + assert message, "first message should not be none" + assert role == self.roles[0], "first message should come from user" + if message: + if type(message) is tuple: + message, _, _ = message + if i == 0: message = wrap_sys(self.system) + message + if i % 2 == 0: + message = wrap_inst(message) + ret += self.sep + message + else: + ret += " " + message + " " + self.sep2 + else: + ret += "" + ret = ret.lstrip(self.sep) + elif self.sep_style == SeparatorStyle.PLAIN: + seps = [self.sep, self.sep2] + ret = self.system + for i, (role, message) in enumerate(messages): + if message: + if type(message) is tuple: + message, _, _ = message + ret += message + seps[i % 2] + else: + ret += "" + else: + raise ValueError(f"Invalid style: {self.sep_style}") + + return ret + + def append_message(self, role, message): + self.messages.append([role, message]) + + def pop_message(self, role, message): + self.messages.pop() + + def process_image(self, image, image_process_mode, return_pil=False, image_format='PNG', max_len=1344, min_len=672): + if image_process_mode == "Pad": + def expand2square(pil_img, background_color=(122, 116, 104)): + width, height = pil_img.size + if width == height: + return pil_img + elif width > height: + result = Image.new(pil_img.mode, (width, width), background_color) + result.paste(pil_img, (0, (width - height) // 2)) + return result + else: + result = Image.new(pil_img.mode, (height, height), background_color) + result.paste(pil_img, ((height - width) // 2, 0)) + return result + image = expand2square(image) + elif image_process_mode in ["Default", "Crop"]: + pass + elif image_process_mode == "Resize": + image = image.resize((336, 336)) + else: + raise ValueError(f"Invalid image_process_mode: {image_process_mode}") + if max(image.size) > max_len: + max_hw, min_hw = max(image.size), min(image.size) + aspect_ratio = max_hw / min_hw + shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw)) + longest_edge = int(shortest_edge * aspect_ratio) + W, H = image.size + if H > W: + H, W = longest_edge, shortest_edge + else: + H, W = shortest_edge, longest_edge + image = image.resize((W, H)) + if return_pil: + return image + else: + buffered = BytesIO() + image.save(buffered, format=image_format) + img_b64_str = base64.b64encode(buffered.getvalue()).decode() + return img_b64_str + + def get_images(self, return_pil=False): + images = [] + for i, (role, msg) in enumerate(self.messages[self.offset:]): + if i % 2 == 0: + if type(msg) is tuple: + msg, image, image_process_mode = msg + image = self.process_image(image, image_process_mode, return_pil=return_pil) + images.append(image) + return images + + def to_gradio_chatbot(self,extra_image=None): + ret = [] + for i, (role, msg) in enumerate(reversed(self.messages[self.offset:])): + if role==self.roles[0]: + pass + # if type(msg) is tuple: + # msg, image, image_process_mode = msg + # img_b64_str = self.process_image( + # image, "Default", return_pil=False, + # image_format='JPEG') + # img_str = f'user upload image' + # msg = img_str + msg.replace('', '').strip() + # ret.append([msg, None]) + # else: + # ret.append([msg, None]) + elif role==self.roles[1]: + if extra_image==None: + if type(msg) is tuple: + msg, image, image_process_mode = msg + img_b64_str = self.process_image( + image, "Default", return_pil=False, + image_format='JPEG') + img_str = f'user upload image' + msg = img_str +msg + ret.append([msg, None]) + else: + ret.append([msg, None]) + else: + img_b64_str = self.process_image( + extra_image, "Default", return_pil=False, + image_format='JPEG') + img_str = f'user upload image' + msg=img_str + ret.append([msg, None]) + break + return ret + + def copy(self): + return Conversation( + system=self.system, + roles=self.roles, + messages=[[x, y] for x, y in self.messages], + offset=self.offset, + sep_style=self.sep_style, + sep=self.sep, + sep2=self.sep2, + version=self.version) + + def dict(self): + if len(self.get_images()) > 0: + return { + "system": self.system, + "roles": self.roles, + "messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages], + "offset": self.offset, + "sep": self.sep, + "sep2": self.sep2, + } + return { + "system": self.system, + "roles": self.roles, + "messages": self.messages, + "offset": self.offset, + "sep": self.sep, + "sep2": self.sep2, + } + + +conv_vicuna_v0 = Conversation( + system="A chat between a curious human and an artificial intelligence assistant. " + "The assistant gives helpful, detailed, and polite answers to the human's questions.", + roles=("Human", "Assistant"), + messages=( + ("Human", "What are the key differences between renewable and non-renewable energy sources?"), + ("Assistant", + "Renewable energy sources are those that can be replenished naturally in a relatively " + "short amount of time, such as solar, wind, hydro, geothermal, and biomass. " + "Non-renewable energy sources, on the other hand, are finite and will eventually be " + "depleted, such as coal, oil, and natural gas. Here are some key differences between " + "renewable and non-renewable energy sources:\n" + "1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable " + "energy sources are finite and will eventually run out.\n" + "2. Environmental impact: Renewable energy sources have a much lower environmental impact " + "than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, " + "and other negative effects.\n" + "3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically " + "have lower operational costs than non-renewable sources.\n" + "4. Reliability: Renewable energy sources are often more reliable and can be used in more remote " + "locations than non-renewable sources.\n" + "5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different " + "situations and needs, while non-renewable sources are more rigid and inflexible.\n" + "6. Sustainability: Renewable energy sources are more sustainable over the long term, while " + "non-renewable sources are not, and their depletion can lead to economic and social instability.\n") + ), + offset=2, + sep_style=SeparatorStyle.SINGLE, + sep="###", +) + +conv_vicuna_v1 = Conversation( + system="A chat between a curious user and an artificial intelligence assistant. " + "The assistant gives helpful, detailed, and polite answers to the user's questions.", + roles=("USER", "ASSISTANT"), + version="v1", + messages=(), + offset=0, + sep_style=SeparatorStyle.TWO, + sep=" ", + sep2="", +) + +conv_llama_2 = Conversation( + system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature. + +If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""", + roles=("USER", "ASSISTANT"), + version="llama_v2", + messages=(), + offset=0, + sep_style=SeparatorStyle.LLAMA_2, + sep="", + sep2="", +) + +conv_llava_llama_2 = Conversation( + system="You are a helpful language and vision assistant. " + "You are able to understand the visual content that the user provides, " + "and assist the user with a variety of tasks using natural language.", + roles=("USER", "ASSISTANT"), + version="llama_v2", + messages=(), + offset=0, + sep_style=SeparatorStyle.LLAMA_2, + sep="", + sep2="", +) + +conv_mpt = Conversation( + system="""<|im_start|>system +A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""", + roles=("<|im_start|>user\n", "<|im_start|>assistant\n"), + version="mpt", + messages=(), + offset=0, + sep_style=SeparatorStyle.MPT, + sep="<|im_end|>", +) + +conv_llava_plain = Conversation( + system="", + roles=("", ""), + messages=( + ), + offset=0, + sep_style=SeparatorStyle.PLAIN, + sep="\n", +) + +conv_llava_v0 = Conversation( + system="A chat between a curious human and an artificial intelligence assistant. " + "The assistant gives helpful, detailed, and polite answers to the human's questions.", + roles=("Human", "Assistant"), + messages=( + ), + offset=0, + sep_style=SeparatorStyle.SINGLE, + sep="###", +) + +conv_llava_v0_mmtag = Conversation( + system="A chat between a curious user and an artificial intelligence assistant. " + "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language." + "The visual content will be provided with the following format: visual content.", + roles=("Human", "Assistant"), + messages=( + ), + offset=0, + sep_style=SeparatorStyle.SINGLE, + sep="###", + version="v0_mmtag", +) + +conv_llava_v1 = Conversation( + system="A chat between a curious human and an artificial intelligence assistant. " + "The assistant gives helpful, detailed, and polite answers to the human's questions.", + roles=("USER", "ASSISTANT"), + version="v1", + messages=(), + offset=0, + sep_style=SeparatorStyle.TWO, + sep=" ", + sep2="", +) + +conv_llava_v1_mmtag = Conversation( + system="A chat between a curious user and an artificial intelligence assistant. " + "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language." + "The visual content will be provided with the following format: visual content.", + roles=("USER", "ASSISTANT"), + messages=(), + offset=0, + sep_style=SeparatorStyle.TWO, + sep=" ", + sep2="", + version="v1_mmtag", +) + +conv_mistral_instruct = Conversation( + system="", + roles=("USER", "ASSISTANT"), + version="llama_v2", + messages=(), + offset=0, + sep_style=SeparatorStyle.LLAMA_2, + sep="", + sep2="", +) + +conv_chatml_direct = Conversation( + system="""<|im_start|>system +Answer the questions.""", + roles=("<|im_start|>user\n", "<|im_start|>assistant\n"), + version="mpt", + messages=(), + offset=0, + sep_style=SeparatorStyle.MPT, + sep="<|im_end|>", +) + +default_conversation = conv_llava_v1 +conv_templates = { + "default": conv_vicuna_v0, + "v0": conv_vicuna_v0, + "v1": conv_vicuna_v1, + "vicuna_v1": conv_vicuna_v1, + "llama_2": conv_llama_2, + "mistral_instruct": conv_mistral_instruct, + "chatml_direct": conv_chatml_direct, + "mistral_direct": conv_chatml_direct, + + "plain": conv_llava_plain, + "v0_plain": conv_llava_plain, + "llava_v0": conv_llava_v0, + "v0_mmtag": conv_llava_v0_mmtag, + "llava_v1": conv_llava_v1, + "v1_mmtag": conv_llava_v1_mmtag, + "llava_llama_2": conv_llava_llama_2, + + "mpt": conv_mpt, +} + + +if __name__ == "__main__": + print(default_conversation.get_prompt()) diff --git a/llava/eval/Roboto-Black.ttf b/llava/eval/Roboto-Black.ttf new file mode 100644 index 0000000000000000000000000000000000000000..0112e7da626ca2f959eca850c806779ba55dbfbd Binary files /dev/null and b/llava/eval/Roboto-Black.ttf differ diff --git a/llava/eval/Roboto-BlackItalic.ttf b/llava/eval/Roboto-BlackItalic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..b2c6aca57bc0d92ab3197d595766bf9285deea00 Binary files /dev/null and b/llava/eval/Roboto-BlackItalic.ttf differ diff --git a/llava/eval/Roboto-Bold.ttf b/llava/eval/Roboto-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..43da14d84ecb949ca5f5e8ecca3a514aa7fe1c7d Binary files /dev/null and b/llava/eval/Roboto-Bold.ttf differ diff --git a/llava/eval/Roboto-BoldItalic.ttf b/llava/eval/Roboto-BoldItalic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..bcfdab4311f2201f45b341b36310e1cdb8051e34 Binary files /dev/null and b/llava/eval/Roboto-BoldItalic.ttf differ diff --git a/llava/eval/Roboto-Italic.ttf b/llava/eval/Roboto-Italic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..1b5eaa361c7306b4246c48497c79475c0e05c5e2 Binary files /dev/null and b/llava/eval/Roboto-Italic.ttf differ diff --git a/llava/eval/Roboto-Light.ttf b/llava/eval/Roboto-Light.ttf new file mode 100644 index 0000000000000000000000000000000000000000..e7307e72c5e7bced5d36c776d0986bf71b605f15 Binary files /dev/null and b/llava/eval/Roboto-Light.ttf differ diff --git a/llava/eval/Roboto-LightItalic.ttf b/llava/eval/Roboto-LightItalic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..2d277afb231f7613a49d983217c1aba871741433 Binary files /dev/null and b/llava/eval/Roboto-LightItalic.ttf differ diff --git a/llava/eval/Roboto-Medium.ttf b/llava/eval/Roboto-Medium.ttf new file mode 100644 index 0000000000000000000000000000000000000000..ac0f908b9c9c73da558b45d65cc5c6094874d3e8 Binary files /dev/null and b/llava/eval/Roboto-Medium.ttf differ diff --git a/llava/eval/Roboto-MediumItalic.ttf b/llava/eval/Roboto-MediumItalic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..fc36a4785c50c04c9b18260e4709cda077ed352d Binary files /dev/null and b/llava/eval/Roboto-MediumItalic.ttf differ diff --git a/llava/eval/Roboto-Regular.ttf b/llava/eval/Roboto-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..ddf4bfacb396e97546364ccfeeb9c31dfaea4c25 Binary files /dev/null and b/llava/eval/Roboto-Regular.ttf differ diff --git a/llava/eval/Roboto-Thin.ttf b/llava/eval/Roboto-Thin.ttf new file mode 100644 index 0000000000000000000000000000000000000000..2e0dee6a833c4b568d44ac99727f7e0c17c6eb67 Binary files /dev/null and b/llava/eval/Roboto-Thin.ttf differ diff --git a/llava/eval/Roboto-ThinItalic.ttf b/llava/eval/Roboto-ThinItalic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..084f9c0f5365952d4d860431a1c2dca147e4a9b5 Binary files /dev/null and b/llava/eval/Roboto-ThinItalic.ttf differ diff --git a/llava/eval/eval_gpt_review.py b/llava/eval/eval_gpt_review.py new file mode 100644 index 0000000000000000000000000000000000000000..8af4559c65fc2728b11fd2097a109981ee1ef686 --- /dev/null +++ b/llava/eval/eval_gpt_review.py @@ -0,0 +1,113 @@ +import argparse +import json +import os + +import openai +import tqdm +import ray +import time + +NUM_SECONDS_TO_SLEEP = 3 + +@ray.remote(num_cpus=4) +def get_eval(content: str, max_tokens: int): + while True: + try: + response = openai.ChatCompletion.create( + model='gpt-4', + messages=[{ + 'role': 'system', + 'content': 'You are a helpful and precise assistant for checking the quality of the answer.' + }, { + 'role': 'user', + 'content': content, + }], + temperature=0.2, # TODO: figure out which temperature is best for evaluation + max_tokens=max_tokens, + ) + break + except openai.error.RateLimitError: + pass + except Exception as e: + print(e) + time.sleep(NUM_SECONDS_TO_SLEEP) + + print('success!') + return response['choices'][0]['message']['content'] + + +def parse_score(review): + try: + score_pair = review.split('\n')[0] + score_pair = score_pair.replace(',', ' ') + sp = score_pair.split(' ') + if len(sp) == 2: + return [float(sp[0]), float(sp[1])] + else: + print('error', review) + return [-1, -1] + except Exception as e: + print(e) + print('error', review) + return [-1, -1] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='ChatGPT-based QA evaluation.') + parser.add_argument('-q', '--question') + # parser.add_argument('-a', '--answer') + parser.add_argument('-a', '--answer-list', nargs='+', default=[]) + parser.add_argument('-r', '--rule') + parser.add_argument('-o', '--output') + parser.add_argument('--max-tokens', type=int, default=1024, help='maximum number of tokens produced in the output') + args = parser.parse_args() + + ray.init() + + f_q = open(os.path.expanduser(args.question)) + f_ans1 = open(os.path.expanduser(args.answer_list[0])) + f_ans2 = open(os.path.expanduser(args.answer_list[1])) + rule_dict = json.load(open(os.path.expanduser(args.rule), 'r')) + + review_file = open(f'{args.output}', 'w') + + js_list = [] + handles = [] + idx = 0 + for ques_js, ans1_js, ans2_js in zip(f_q, f_ans1, f_ans2): + # if idx == 1: + # break + + ques = json.loads(ques_js) + ans1 = json.loads(ans1_js) + ans2 = json.loads(ans2_js) + + category = json.loads(ques_js)['category'] + if category in rule_dict: + rule = rule_dict[category] + else: + rule = rule_dict['default'] + prompt = rule['prompt'] + role = rule['role'] + content = (f'[Question]\n{ques["text"]}\n\n' + f'[{role} 1]\n{ans1["text"]}\n\n[End of {role} 1]\n\n' + f'[{role} 2]\n{ans2["text"]}\n\n[End of {role} 2]\n\n' + f'[System]\n{prompt}\n\n') + js_list.append({ + 'id': idx+1, + 'question_id': ques['question_id'], + 'answer1_id': ans1['answer_id'], + 'answer2_id': ans2['answer_id'], + 'category': category}) + idx += 1 + handles.append(get_eval.remote(content, args.max_tokens)) + # To avoid the rate limit set by OpenAI + time.sleep(NUM_SECONDS_TO_SLEEP) + + reviews = ray.get(handles) + for idx, review in enumerate(reviews): + scores = parse_score(review) + js_list[idx]['content'] = review + js_list[idx]['tuple'] = scores + review_file.write(json.dumps(js_list[idx]) + '\n') + review_file.close() diff --git a/llava/eval/eval_gpt_review_bench.py b/llava/eval/eval_gpt_review_bench.py new file mode 100644 index 0000000000000000000000000000000000000000..06160f2422b5368f30fb967f7cae635208a1dc69 --- /dev/null +++ b/llava/eval/eval_gpt_review_bench.py @@ -0,0 +1,121 @@ +import argparse +import json +import os + +import openai +import time + +NUM_SECONDS_TO_SLEEP = 0.5 + + +def get_eval(content: str, max_tokens: int): + while True: + try: + response = openai.ChatCompletion.create( + model='gpt-4-0314', + messages=[{ + 'role': 'system', + 'content': 'You are a helpful and precise assistant for checking the quality of the answer.' + }, { + 'role': 'user', + 'content': content, + }], + temperature=0.2, # TODO: figure out which temperature is best for evaluation + max_tokens=max_tokens, + ) + break + except openai.error.RateLimitError: + pass + except Exception as e: + print(e) + time.sleep(NUM_SECONDS_TO_SLEEP) + + return response['choices'][0]['message']['content'] + + +def parse_score(review): + try: + score_pair = review.split('\n')[0] + score_pair = score_pair.replace(',', ' ') + sp = score_pair.split(' ') + if len(sp) == 2: + return [float(sp[0]), float(sp[1])] + else: + print('error', review) + return [-1, -1] + except Exception as e: + print(e) + print('error', review) + return [-1, -1] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='ChatGPT-based QA evaluation.') + parser.add_argument('-q', '--question') + parser.add_argument('-c', '--context') + parser.add_argument('-a', '--answer-list', nargs='+', default=[]) + parser.add_argument('-r', '--rule') + parser.add_argument('-o', '--output') + parser.add_argument('--max-tokens', type=int, default=1024, help='maximum number of tokens produced in the output') + args = parser.parse_args() + + f_q = open(os.path.expanduser(args.question)) + f_ans1 = open(os.path.expanduser(args.answer_list[0])) + f_ans2 = open(os.path.expanduser(args.answer_list[1])) + rule_dict = json.load(open(os.path.expanduser(args.rule), 'r')) + + if os.path.isfile(os.path.expanduser(args.output)): + cur_reviews = [json.loads(line) for line in open(os.path.expanduser(args.output))] + else: + cur_reviews = [] + + review_file = open(f'{args.output}', 'a') + + context_list = [json.loads(line) for line in open(os.path.expanduser(args.context))] + image_to_context = {context['image']: context for context in context_list} + + handles = [] + idx = 0 + for ques_js, ans1_js, ans2_js in zip(f_q, f_ans1, f_ans2): + ques = json.loads(ques_js) + ans1 = json.loads(ans1_js) + ans2 = json.loads(ans2_js) + + inst = image_to_context[ques['image']] + + if isinstance(inst['caption'], list): + cap_str = '\n'.join(inst['caption']) + else: + cap_str = inst['caption'] + + category = 'llava_bench_' + json.loads(ques_js)['category'] + if category in rule_dict: + rule = rule_dict[category] + else: + assert False, f"Visual QA category not found in rule file: {category}." + prompt = rule['prompt'] + role = rule['role'] + content = (f'[Context]\n{cap_str}\n\n' + f'[Question]\n{ques["text"]}\n\n' + f'[{role} 1]\n{ans1["text"]}\n\n[End of {role} 1]\n\n' + f'[{role} 2]\n{ans2["text"]}\n\n[End of {role} 2]\n\n' + f'[System]\n{prompt}\n\n') + cur_js = { + 'id': idx+1, + 'question_id': ques['question_id'], + 'answer1_id': ans1.get('answer_id', ans1['question_id']), + 'answer2_id': ans2.get('answer_id', ans2['answer_id']), + 'category': category + } + if idx >= len(cur_reviews): + review = get_eval(content, args.max_tokens) + scores = parse_score(review) + cur_js['content'] = review + cur_js['tuple'] = scores + review_file.write(json.dumps(cur_js) + '\n') + review_file.flush() + else: + print(f'Skipping {idx} as we already have it.') + idx += 1 + print(idx) + review_file.close() diff --git a/llava/eval/eval_gpt_review_visual.py b/llava/eval/eval_gpt_review_visual.py new file mode 100644 index 0000000000000000000000000000000000000000..d6e407a400a67020d801e6c27a3c32a2ee38f30c --- /dev/null +++ b/llava/eval/eval_gpt_review_visual.py @@ -0,0 +1,118 @@ +import argparse +import json +import os + +import openai +import time + +NUM_SECONDS_TO_SLEEP = 0.5 + + +def get_eval(content: str, max_tokens: int): + while True: + try: + response = openai.ChatCompletion.create( + model='gpt-4-0314', + messages=[{ + 'role': 'system', + 'content': 'You are a helpful and precise assistant for checking the quality of the answer.' + }, { + 'role': 'user', + 'content': content, + }], + temperature=0.2, # TODO: figure out which temperature is best for evaluation + max_tokens=max_tokens, + ) + break + except openai.error.RateLimitError: + pass + except Exception as e: + print(e) + time.sleep(NUM_SECONDS_TO_SLEEP) + + return response['choices'][0]['message']['content'] + + +def parse_score(review): + try: + score_pair = review.split('\n')[0] + score_pair = score_pair.replace(',', ' ') + sp = score_pair.split(' ') + if len(sp) == 2: + return [float(sp[0]), float(sp[1])] + else: + print('error', review) + return [-1, -1] + except Exception as e: + print(e) + print('error', review) + return [-1, -1] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='ChatGPT-based QA evaluation.') + parser.add_argument('-q', '--question') + parser.add_argument('-c', '--context') + parser.add_argument('-a', '--answer-list', nargs='+', default=[]) + parser.add_argument('-r', '--rule') + parser.add_argument('-o', '--output') + parser.add_argument('--max-tokens', type=int, default=1024, help='maximum number of tokens produced in the output') + args = parser.parse_args() + + f_q = open(os.path.expanduser(args.question)) + f_ans1 = open(os.path.expanduser(args.answer_list[0])) + f_ans2 = open(os.path.expanduser(args.answer_list[1])) + rule_dict = json.load(open(os.path.expanduser(args.rule), 'r')) + + if os.path.isfile(os.path.expanduser(args.output)): + cur_reviews = [json.loads(line) for line in open(os.path.expanduser(args.output))] + else: + cur_reviews = [] + + review_file = open(f'{args.output}', 'a') + + context_list = [json.loads(line) for line in open(os.path.expanduser(args.context))] + image_to_context = {context['image']: context for context in context_list} + + handles = [] + idx = 0 + for ques_js, ans1_js, ans2_js in zip(f_q, f_ans1, f_ans2): + ques = json.loads(ques_js) + ans1 = json.loads(ans1_js) + ans2 = json.loads(ans2_js) + + inst = image_to_context[ques['image']] + cap_str = '\n'.join(inst['captions']) + box_str = '\n'.join([f'{instance["category"]}: {instance["bbox"]}' for instance in inst['instances']]) + + category = json.loads(ques_js)['category'] + if category in rule_dict: + rule = rule_dict[category] + else: + assert False, f"Visual QA category not found in rule file: {category}." + prompt = rule['prompt'] + role = rule['role'] + content = (f'[Context]\n{cap_str}\n\n{box_str}\n\n' + f'[Question]\n{ques["text"]}\n\n' + f'[{role} 1]\n{ans1["text"]}\n\n[End of {role} 1]\n\n' + f'[{role} 2]\n{ans2["text"]}\n\n[End of {role} 2]\n\n' + f'[System]\n{prompt}\n\n') + cur_js = { + 'id': idx+1, + 'question_id': ques['question_id'], + 'answer1_id': ans1.get('answer_id', ans1['question_id']), + 'answer2_id': ans2.get('answer_id', ans2['answer_id']), + 'category': category + } + if idx >= len(cur_reviews): + review = get_eval(content, args.max_tokens) + scores = parse_score(review) + cur_js['content'] = review + cur_js['tuple'] = scores + review_file.write(json.dumps(cur_js) + '\n') + review_file.flush() + else: + print(f'Skipping {idx} as we already have it.') + idx += 1 + print(idx) + review_file.close() diff --git a/llava/eval/eval_pope.py b/llava/eval/eval_pope.py new file mode 100644 index 0000000000000000000000000000000000000000..b115b8f2327ea9d972f9e41bcbb03c68be6b3508 --- /dev/null +++ b/llava/eval/eval_pope.py @@ -0,0 +1,81 @@ +import os +import json +import argparse + +def eval_pope(answers, label_file): + label_list = [json.loads(q)['label'] for q in open(label_file, 'r')] + + for answer in answers: + text = answer['text'] + + # Only keep the first sentence + if text.find('.') != -1: + text = text.split('.')[0] + + text = text.replace(',', '') + words = text.split(' ') + if 'No' in words or 'not' in words or 'no' in words: + answer['text'] = 'no' + else: + answer['text'] = 'yes' + + for i in range(len(label_list)): + if label_list[i] == 'no': + label_list[i] = 0 + else: + label_list[i] = 1 + + pred_list = [] + for answer in answers: + if answer['text'] == 'no': + pred_list.append(0) + else: + pred_list.append(1) + + pos = 1 + neg = 0 + yes_ratio = pred_list.count(1) / len(pred_list) + + TP, TN, FP, FN = 0, 0, 0, 0 + for pred, label in zip(pred_list, label_list): + if pred == pos and label == pos: + TP += 1 + elif pred == pos and label == neg: + FP += 1 + elif pred == neg and label == neg: + TN += 1 + elif pred == neg and label == pos: + FN += 1 + + print('TP\tFP\tTN\tFN\t') + print('{}\t{}\t{}\t{}'.format(TP, FP, TN, FN)) + + precision = float(TP) / float(TP + FP) + recall = float(TP) / float(TP + FN) + f1 = 2*precision*recall / (precision + recall) + acc = (TP + TN) / (TP + TN + FP + FN) + print('Accuracy: {}'.format(acc)) + print('Precision: {}'.format(precision)) + print('Recall: {}'.format(recall)) + print('F1 score: {}'.format(f1)) + print('Yes ratio: {}'.format(yes_ratio)) + print('%.3f, %.3f, %.3f, %.3f, %.3f' % (f1, acc, precision, recall, yes_ratio) ) + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--annotation-dir", type=str) + parser.add_argument("--question-file", type=str) + parser.add_argument("--result-file", type=str) + args = parser.parse_args() + + questions = [json.loads(line) for line in open(args.question_file)] + questions = {question['question_id']: question for question in questions} + answers = [json.loads(q) for q in open(args.result_file)] + for file in os.listdir(args.annotation_dir): + assert file.startswith('coco_pope_') + assert file.endswith('.json') + category = file[10:-5] + cur_answers = [x for x in answers if questions[x['question_id']]['category'] == category] + print('Category: {}, # samples: {}'.format(category, len(cur_answers))) + eval_pope(cur_answers, os.path.join(args.annotation_dir, file)) + print("====================================") diff --git a/llava/eval/eval_science_qa.py b/llava/eval/eval_science_qa.py new file mode 100644 index 0000000000000000000000000000000000000000..ccf206bbd7a5d6376eef82d61b3ef8bbe0f71c6c --- /dev/null +++ b/llava/eval/eval_science_qa.py @@ -0,0 +1,114 @@ +import argparse +import json +import os +import re +import random + + +def get_args(): + parser = argparse.ArgumentParser() + parser.add_argument('--base-dir', type=str) + parser.add_argument('--result-file', type=str) + parser.add_argument('--output-file', type=str) + parser.add_argument('--output-result', type=str) + parser.add_argument('--split', type=str, default='test') + parser.add_argument('--options', type=list, default=["A", "B", "C", "D", "E"]) + return parser.parse_args() + + +def convert_caps(results): + fakecaps = [] + for result in results: + image_id = result['question_id'] + caption = result['text'] + fakecaps.append({"image_id": int(image_id), "caption": caption}) + return fakecaps + + +def get_pred_idx(prediction, choices, options): + """ + Get the index (e.g. 2) from the prediction (e.g. 'C') + """ + if prediction in options[:len(choices)]: + return options.index(prediction) + else: + return -1 + return random.choice(range(len(choices))) + + +if __name__ == "__main__": + args = get_args() + + base_dir = args.base_dir + split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[args.split] + problems = json.load(open(os.path.join(base_dir, "problems.json"))) + predictions = [json.loads(line) for line in open(args.result_file)] + predictions = {pred['question_id']: pred for pred in predictions} + split_problems = {idx: problems[idx] for idx in split_indices} + + results = {'correct': [], 'incorrect': []} + sqa_results = {} + sqa_results['acc'] = None + sqa_results['correct'] = None + sqa_results['count'] = None + sqa_results['results'] = {} + sqa_results['outputs'] = {} + + for prob_id, prob in split_problems.items(): + if prob_id not in predictions: + pred = {'text': 'FAILED', 'prompt': 'Unknown'} + pred_text = 'FAILED' + else: + pred = predictions[prob_id] + pred_text = pred['text'] + + if pred_text in args.options: + answer = pred_text + elif len(pred_text) >= 3 and pred_text[0] in args.options and pred_text[1:3] == ". ": + answer = pred_text[0] + else: + pattern = re.compile(r'The answer is ([A-Z]).') + res = pattern.findall(pred_text) + if len(res) == 1: + answer = res[0] # 'A', 'B', ... + else: + answer = "FAILED" + + pred_idx = get_pred_idx(answer, prob['choices'], args.options) + + analysis = { + 'question_id': prob_id, + 'parsed_ans': answer, + 'ground_truth': args.options[prob['answer']], + 'question': pred['prompt'], + 'pred': pred_text, + 'is_multimodal': '' in pred['prompt'], + } + + sqa_results['results'][prob_id] = get_pred_idx(answer, prob['choices'], args.options) + sqa_results['outputs'][prob_id] = pred_text + + if pred_idx == prob['answer']: + results['correct'].append(analysis) + else: + results['incorrect'].append(analysis) + + correct = len(results['correct']) + total = len(results['correct']) + len(results['incorrect']) + + ###### IMG ###### + multimodal_correct = len([x for x in results['correct'] if x['is_multimodal']]) + multimodal_incorrect = len([x for x in results['incorrect'] if x['is_multimodal']]) + multimodal_total = multimodal_correct + multimodal_incorrect + ###### IMG ###### + + print(f'Total: {total}, Correct: {correct}, Accuracy: {correct / total * 100:.2f}%, IMG-Accuracy: {multimodal_correct / multimodal_total * 100:.2f}%') + + sqa_results['acc'] = correct / total * 100 + sqa_results['correct'] = correct + sqa_results['count'] = total + + with open(args.output_file, 'w') as f: + json.dump(results, f, indent=2) + with open(args.output_result, 'w') as f: + json.dump(sqa_results, f, indent=2) diff --git a/llava/eval/eval_science_qa_gpt4.py b/llava/eval/eval_science_qa_gpt4.py new file mode 100644 index 0000000000000000000000000000000000000000..c2ff17c915481fb556aba6ec816a9e08f519c515 --- /dev/null +++ b/llava/eval/eval_science_qa_gpt4.py @@ -0,0 +1,104 @@ +import argparse +import json +import os +import re +import random +from collections import defaultdict + + +def get_args(): + parser = argparse.ArgumentParser() + parser.add_argument('--base-dir', type=str) + parser.add_argument('--gpt4-result', type=str) + parser.add_argument('--our-result', type=str) + parser.add_argument('--split', type=str, default='test') + parser.add_argument('--options', type=list, default=["A", "B", "C", "D", "E"]) + return parser.parse_args() + + +def convert_caps(results): + fakecaps = [] + for result in results: + image_id = result['question_id'] + caption = result['text'] + fakecaps.append({"image_id": int(image_id), "caption": caption}) + return fakecaps + + +def get_pred_idx(prediction, choices, options): + """ + Get the index (e.g. 2) from the prediction (e.g. 'C') + """ + if prediction in options[:len(choices)]: + return options.index(prediction) + else: + return random.choice(range(len(choices))) + + +if __name__ == "__main__": + args = get_args() + + base_dir = args.base_dir + split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[args.split] + problems = json.load(open(os.path.join(base_dir, "problems.json"))) + our_predictions = [json.loads(line) for line in open(args.our_result)] + our_predictions = {pred['question_id']: pred for pred in our_predictions} + split_problems = {idx: problems[idx] for idx in split_indices} + + gpt4_predictions = json.load(open(args.gpt4_result))['outputs'] + + results = defaultdict(lambda: 0) + + for prob_id, prob in split_problems.items(): + if prob_id not in our_predictions: + continue + if prob_id not in gpt4_predictions: + continue + our_pred = our_predictions[prob_id]['text'] + gpt4_pred = gpt4_predictions[prob_id] + + pattern = re.compile(r'The answer is ([A-Z]).') + our_res = pattern.findall(our_pred) + if len(our_res) == 1: + our_answer = our_res[0] # 'A', 'B', ... + else: + our_answer = "FAILED" + gpt4_res = pattern.findall(gpt4_pred) + if len(gpt4_res) == 1: + gpt4_answer = gpt4_res[0] # 'A', 'B', ... + else: + gpt4_answer = "FAILED" + + our_pred_idx = get_pred_idx(our_answer, prob['choices'], args.options) + gpt4_pred_idx = get_pred_idx(gpt4_answer, prob['choices'], args.options) + + if gpt4_answer == 'FAILED': + results['gpt4_failed'] += 1 + # continue + gpt4_pred_idx = our_pred_idx + # if our_pred_idx != prob['answer']: + # print(our_predictions[prob_id]['prompt']) + # print('-----------------') + # print(f'LECTURE: {prob["lecture"]}') + # print(f'SOLUTION: {prob["solution"]}') + # print('=====================') + else: + # continue + pass + # gpt4_pred_idx = our_pred_idx + + if gpt4_pred_idx == prob['answer']: + results['correct'] += 1 + else: + results['incorrect'] += 1 + + + if gpt4_pred_idx == prob['answer'] or our_pred_idx == prob['answer']: + results['correct_upperbound'] += 1 + + correct = results['correct'] + total = results['correct'] + results['incorrect'] + print(f'Total: {total}, Correct: {correct}, Accuracy: {correct / total * 100:.2f}%') + print(f'Total: {total}, Correct (upper): {results["correct_upperbound"]}, Accuracy: {results["correct_upperbound"] / total * 100:.2f}%') + print(f'Total: {total}, GPT-4 NO-ANS (RANDOM): {results["gpt4_failed"]}, Percentage: {results["gpt4_failed"] / total * 100:.2f}%') + diff --git a/llava/eval/eval_science_qa_gpt4_requery.py b/llava/eval/eval_science_qa_gpt4_requery.py new file mode 100644 index 0000000000000000000000000000000000000000..698546e995d365d1ccc2c25a87e6c5cd681e6eb6 --- /dev/null +++ b/llava/eval/eval_science_qa_gpt4_requery.py @@ -0,0 +1,149 @@ +import argparse +import json +import os +import re +import random +from collections import defaultdict + + +def get_args(): + parser = argparse.ArgumentParser() + parser.add_argument('--base-dir', type=str) + parser.add_argument('--gpt4-result', type=str) + parser.add_argument('--requery-result', type=str) + parser.add_argument('--our-result', type=str) + parser.add_argument('--output-result', type=str) + parser.add_argument('--split', type=str, default='test') + parser.add_argument('--options', type=list, default=["A", "B", "C", "D", "E"]) + return parser.parse_args() + + +def convert_caps(results): + fakecaps = [] + for result in results: + image_id = result['question_id'] + caption = result['text'] + fakecaps.append({"image_id": int(image_id), "caption": caption}) + return fakecaps + + +def get_pred_idx(prediction, choices, options): + """ + Get the index (e.g. 2) from the prediction (e.g. 'C') + """ + if prediction in options[:len(choices)]: + return options.index(prediction) + else: + return random.choice(range(len(choices))) + + +if __name__ == "__main__": + args = get_args() + + base_dir = args.base_dir + split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[args.split] + problems = json.load(open(os.path.join(base_dir, "problems.json"))) + our_predictions = [json.loads(line) for line in open(args.our_result)] + our_predictions = {pred['question_id']: pred for pred in our_predictions} + split_problems = {idx: problems[idx] for idx in split_indices} + + requery_predictions = [json.loads(line) for line in open(args.requery_result)] + requery_predictions = {pred['question_id']: pred for pred in requery_predictions} + + gpt4_predictions = json.load(open(args.gpt4_result))['outputs'] + + results = defaultdict(lambda: 0) + + sqa_results = {} + sqa_results['acc'] = None + sqa_results['correct'] = None + sqa_results['count'] = None + sqa_results['results'] = {} + sqa_results['outputs'] = {} + + for prob_id, prob in split_problems.items(): + if prob_id not in our_predictions: + assert False + if prob_id not in gpt4_predictions: + assert False + our_pred = our_predictions[prob_id]['text'] + gpt4_pred = gpt4_predictions[prob_id] + if prob_id not in requery_predictions: + results['missing_requery'] += 1 + requery_pred = "MISSING" + else: + requery_pred = requery_predictions[prob_id]['text'] + + pattern = re.compile(r'The answer is ([A-Z]).') + our_res = pattern.findall(our_pred) + if len(our_res) == 1: + our_answer = our_res[0] # 'A', 'B', ... + else: + our_answer = "FAILED" + + requery_res = pattern.findall(requery_pred) + if len(requery_res) == 1: + requery_answer = requery_res[0] # 'A', 'B', ... + else: + requery_answer = "FAILED" + + gpt4_res = pattern.findall(gpt4_pred) + if len(gpt4_res) == 1: + gpt4_answer = gpt4_res[0] # 'A', 'B', ... + else: + gpt4_answer = "FAILED" + + our_pred_idx = get_pred_idx(our_answer, prob['choices'], args.options) + gpt4_pred_idx = get_pred_idx(gpt4_answer, prob['choices'], args.options) + requery_pred_idx = get_pred_idx(requery_answer, prob['choices'], args.options) + + results['total'] += 1 + + if gpt4_answer == 'FAILED': + results['gpt4_failed'] += 1 + if gpt4_pred_idx == prob['answer']: + results['gpt4_correct'] += 1 + if our_pred_idx == prob['answer']: + results['gpt4_ourvisual_correct'] += 1 + elif gpt4_pred_idx == prob['answer']: + results['gpt4_correct'] += 1 + results['gpt4_ourvisual_correct'] += 1 + + if our_pred_idx == prob['answer']: + results['our_correct'] += 1 + + if requery_answer == 'FAILED': + sqa_results['results'][prob_id] = our_pred_idx + if our_pred_idx == prob['answer']: + results['requery_correct'] += 1 + else: + sqa_results['results'][prob_id] = requery_pred_idx + if requery_pred_idx == prob['answer']: + results['requery_correct'] += 1 + else: + print(f""" +Question ({args.options[prob['answer']]}): {our_predictions[prob_id]['prompt']} +Our ({our_answer}): {our_pred} +GPT-4 ({gpt4_answer}): {gpt4_pred} +Requery ({requery_answer}): {requery_pred} +print("=====================================") +""") + + if gpt4_pred_idx == prob['answer'] or our_pred_idx == prob['answer']: + results['correct_upperbound'] += 1 + + total = results['total'] + print(f'Total: {total}, Our-Correct: {results["our_correct"]}, Accuracy: {results["our_correct"] / total * 100:.2f}%') + print(f'Total: {total}, GPT-4-Correct: {results["gpt4_correct"]}, Accuracy: {results["gpt4_correct"] / total * 100:.2f}%') + print(f'Total: {total}, GPT-4 NO-ANS (RANDOM): {results["gpt4_failed"]}, Percentage: {results["gpt4_failed"] / total * 100:.2f}%') + print(f'Total: {total}, GPT-4-OursVisual-Correct: {results["gpt4_ourvisual_correct"]}, Accuracy: {results["gpt4_ourvisual_correct"] / total * 100:.2f}%') + print(f'Total: {total}, Requery-Correct: {results["requery_correct"]}, Accuracy: {results["requery_correct"] / total * 100:.2f}%') + print(f'Total: {total}, Correct upper: {results["correct_upperbound"]}, Accuracy: {results["correct_upperbound"] / total * 100:.2f}%') + + sqa_results['acc'] = results["requery_correct"] / total * 100 + sqa_results['correct'] = results["requery_correct"] + sqa_results['count'] = total + + with open(args.output_result, 'w') as f: + json.dump(sqa_results, f, indent=2) + diff --git a/llava/eval/eval_textvqa.py b/llava/eval/eval_textvqa.py new file mode 100644 index 0000000000000000000000000000000000000000..468f4bb120448a036bd5b5c7955464fe2e13892a --- /dev/null +++ b/llava/eval/eval_textvqa.py @@ -0,0 +1,65 @@ +import os +import argparse +import json +import re + +from llava.eval.m4c_evaluator import TextVQAAccuracyEvaluator + + +def get_args(): + parser = argparse.ArgumentParser() + parser.add_argument('--annotation-file', type=str) + parser.add_argument('--result-file', type=str) + parser.add_argument('--result-dir', type=str) + return parser.parse_args() + + +def prompt_processor(prompt): + if prompt.startswith('OCR tokens: '): + pattern = r"Question: (.*?) Short answer:" + match = re.search(pattern, prompt, re.DOTALL) + question = match.group(1) + elif 'Reference OCR token: ' in prompt and len(prompt.split('\n')) == 3: + if prompt.startswith('Reference OCR token:'): + question = prompt.split('\n')[1] + else: + question = prompt.split('\n')[0] + elif len(prompt.split('\n')) == 2: + question = prompt.split('\n')[0] + else: + assert False + + return question.lower() + + +def eval_single(annotation_file, result_file): + experiment_name = os.path.splitext(os.path.basename(result_file))[0] + print(experiment_name) + annotations = json.load(open(annotation_file))['data'] + annotations = {(annotation['image_id'], annotation['question'].lower()): annotation for annotation in annotations} + results = [json.loads(line) for line in open(result_file)] + + pred_list = [] + for result in results: + annotation = annotations[(result['question_id'], prompt_processor(result['prompt']))] + pred_list.append({ + "pred_answer": result['text'], + "gt_answers": annotation['answers'], + }) + + evaluator = TextVQAAccuracyEvaluator() + print('Samples: {}\nAccuracy: {:.2f}%\n'.format(len(pred_list), 100. * evaluator.eval_pred_list(pred_list))) + + +if __name__ == "__main__": + args = get_args() + + if args.result_file is not None: + eval_single(args.annotation_file, args.result_file) + + if args.result_dir is not None: + for result_file in sorted(os.listdir(args.result_dir)): + if not result_file.endswith('.jsonl'): + print(f'Skipping {result_file}') + continue + eval_single(args.annotation_file, os.path.join(args.result_dir, result_file)) diff --git a/llava/eval/generate_webpage_data_from_table.py b/llava/eval/generate_webpage_data_from_table.py new file mode 100644 index 0000000000000000000000000000000000000000..92602258ccd953a1d7137056aaf15c8de8166e21 --- /dev/null +++ b/llava/eval/generate_webpage_data_from_table.py @@ -0,0 +1,111 @@ +"""Generate json file for webpage.""" +import json +import os +import re + +# models = ['llama', 'alpaca', 'gpt35', 'bard'] +models = ['vicuna'] + + +def read_jsonl(path: str, key: str=None): + data = [] + with open(os.path.expanduser(path)) as f: + for line in f: + if not line: + continue + data.append(json.loads(line)) + if key is not None: + data.sort(key=lambda x: x[key]) + data = {item[key]: item for item in data} + return data + + +def trim_hanging_lines(s: str, n: int) -> str: + s = s.strip() + for _ in range(n): + s = s.split('\n', 1)[1].strip() + return s + + +if __name__ == '__main__': + questions = read_jsonl('table/question.jsonl', key='question_id') + + # alpaca_answers = read_jsonl('table/answer/answer_alpaca-13b.jsonl', key='question_id') + # bard_answers = read_jsonl('table/answer/answer_bard.jsonl', key='question_id') + # gpt35_answers = read_jsonl('table/answer/answer_gpt35.jsonl', key='question_id') + # llama_answers = read_jsonl('table/answer/answer_llama-13b.jsonl', key='question_id') + vicuna_answers = read_jsonl('table/answer/answer_vicuna-13b.jsonl', key='question_id') + ours_answers = read_jsonl('table/results/llama-13b-hf-alpaca.jsonl', key='question_id') + + review_vicuna = read_jsonl('table/review/review_vicuna-13b_llama-13b-hf-alpaca.jsonl', key='question_id') + # review_alpaca = read_jsonl('table/review/review_alpaca-13b_vicuna-13b.jsonl', key='question_id') + # review_bard = read_jsonl('table/review/review_bard_vicuna-13b.jsonl', key='question_id') + # review_gpt35 = read_jsonl('table/review/review_gpt35_vicuna-13b.jsonl', key='question_id') + # review_llama = read_jsonl('table/review/review_llama-13b_vicuna-13b.jsonl', key='question_id') + + records = [] + for qid in questions.keys(): + r = { + 'id': qid, + 'category': questions[qid]['category'], + 'question': questions[qid]['text'], + 'answers': { + # 'alpaca': alpaca_answers[qid]['text'], + # 'llama': llama_answers[qid]['text'], + # 'bard': bard_answers[qid]['text'], + # 'gpt35': gpt35_answers[qid]['text'], + 'vicuna': vicuna_answers[qid]['text'], + 'ours': ours_answers[qid]['text'], + }, + 'evaluations': { + # 'alpaca': review_alpaca[qid]['text'], + # 'llama': review_llama[qid]['text'], + # 'bard': review_bard[qid]['text'], + 'vicuna': review_vicuna[qid]['content'], + # 'gpt35': review_gpt35[qid]['text'], + }, + 'scores': { + 'vicuna': review_vicuna[qid]['tuple'], + # 'alpaca': review_alpaca[qid]['score'], + # 'llama': review_llama[qid]['score'], + # 'bard': review_bard[qid]['score'], + # 'gpt35': review_gpt35[qid]['score'], + }, + } + + # cleanup data + cleaned_evals = {} + for k, v in r['evaluations'].items(): + v = v.strip() + lines = v.split('\n') + # trim the first line if it's a pair of numbers + if re.match(r'\d+[, ]+\d+', lines[0]): + lines = lines[1:] + v = '\n'.join(lines) + cleaned_evals[k] = v.replace('Assistant 1', "**Assistant 1**").replace('Assistant 2', '**Assistant 2**') + + r['evaluations'] = cleaned_evals + records.append(r) + + # Reorder the records, this is optional + for r in records: + if r['id'] <= 20: + r['id'] += 60 + else: + r['id'] -= 20 + for r in records: + if r['id'] <= 50: + r['id'] += 10 + elif 50 < r['id'] <= 60: + r['id'] -= 50 + for r in records: + if r['id'] == 7: + r['id'] = 1 + elif r['id'] < 7: + r['id'] += 1 + + records.sort(key=lambda x: x['id']) + + # Write to file + with open('webpage/data.json', 'w') as f: + json.dump({'questions': records, 'models': models}, f, indent=2) diff --git a/llava/eval/m4c_evaluator.py b/llava/eval/m4c_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..e30e958da061a4f0a0bfe34b12d2fcaeba7ff2f4 --- /dev/null +++ b/llava/eval/m4c_evaluator.py @@ -0,0 +1,334 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +import re + +from tqdm import tqdm + + +class EvalAIAnswerProcessor: + """ + Processes an answer similar to Eval AI + copied from + https://github.com/facebookresearch/mmf/blob/c46b3b3391275b4181567db80943473a89ab98ab/pythia/tasks/processors.py#L897 + """ + + CONTRACTIONS = { + "aint": "ain't", + "arent": "aren't", + "cant": "can't", + "couldve": "could've", + "couldnt": "couldn't", + "couldn'tve": "couldn't've", + "couldnt've": "couldn't've", + "didnt": "didn't", + "doesnt": "doesn't", + "dont": "don't", + "hadnt": "hadn't", + "hadnt've": "hadn't've", + "hadn'tve": "hadn't've", + "hasnt": "hasn't", + "havent": "haven't", + "hed": "he'd", + "hed've": "he'd've", + "he'dve": "he'd've", + "hes": "he's", + "howd": "how'd", + "howll": "how'll", + "hows": "how's", + "Id've": "I'd've", + "I'dve": "I'd've", + "Im": "I'm", + "Ive": "I've", + "isnt": "isn't", + "itd": "it'd", + "itd've": "it'd've", + "it'dve": "it'd've", + "itll": "it'll", + "let's": "let's", + "maam": "ma'am", + "mightnt": "mightn't", + "mightnt've": "mightn't've", + "mightn'tve": "mightn't've", + "mightve": "might've", + "mustnt": "mustn't", + "mustve": "must've", + "neednt": "needn't", + "notve": "not've", + "oclock": "o'clock", + "oughtnt": "oughtn't", + "ow's'at": "'ow's'at", + "'ows'at": "'ow's'at", + "'ow'sat": "'ow's'at", + "shant": "shan't", + "shed've": "she'd've", + "she'dve": "she'd've", + "she's": "she's", + "shouldve": "should've", + "shouldnt": "shouldn't", + "shouldnt've": "shouldn't've", + "shouldn'tve": "shouldn't've", + "somebody'd": "somebodyd", + "somebodyd've": "somebody'd've", + "somebody'dve": "somebody'd've", + "somebodyll": "somebody'll", + "somebodys": "somebody's", + "someoned": "someone'd", + "someoned've": "someone'd've", + "someone'dve": "someone'd've", + "someonell": "someone'll", + "someones": "someone's", + "somethingd": "something'd", + "somethingd've": "something'd've", + "something'dve": "something'd've", + "somethingll": "something'll", + "thats": "that's", + "thered": "there'd", + "thered've": "there'd've", + "there'dve": "there'd've", + "therere": "there're", + "theres": "there's", + "theyd": "they'd", + "theyd've": "they'd've", + "they'dve": "they'd've", + "theyll": "they'll", + "theyre": "they're", + "theyve": "they've", + "twas": "'twas", + "wasnt": "wasn't", + "wed've": "we'd've", + "we'dve": "we'd've", + "weve": "we've", + "werent": "weren't", + "whatll": "what'll", + "whatre": "what're", + "whats": "what's", + "whatve": "what've", + "whens": "when's", + "whered": "where'd", + "wheres": "where's", + "whereve": "where've", + "whod": "who'd", + "whod've": "who'd've", + "who'dve": "who'd've", + "wholl": "who'll", + "whos": "who's", + "whove": "who've", + "whyll": "why'll", + "whyre": "why're", + "whys": "why's", + "wont": "won't", + "wouldve": "would've", + "wouldnt": "wouldn't", + "wouldnt've": "wouldn't've", + "wouldn'tve": "wouldn't've", + "yall": "y'all", + "yall'll": "y'all'll", + "y'allll": "y'all'll", + "yall'd've": "y'all'd've", + "y'alld've": "y'all'd've", + "y'all'dve": "y'all'd've", + "youd": "you'd", + "youd've": "you'd've", + "you'dve": "you'd've", + "youll": "you'll", + "youre": "you're", + "youve": "you've", + } + + NUMBER_MAP = { + "none": "0", + "zero": "0", + "one": "1", + "two": "2", + "three": "3", + "four": "4", + "five": "5", + "six": "6", + "seven": "7", + "eight": "8", + "nine": "9", + "ten": "10", + } + ARTICLES = ["a", "an", "the"] + PERIOD_STRIP = re.compile(r"(?!<=\d)(\.)(?!\d)") + COMMA_STRIP = re.compile(r"(?<=\d)(\,)+(?=\d)") + PUNCTUATIONS = [ + ";", + r"/", + "[", + "]", + '"', + "{", + "}", + "(", + ")", + "=", + "+", + "\\", + "_", + "-", + ">", + "<", + "@", + "`", + ",", + "?", + "!", + ] + + def __init__(self, *args, **kwargs): + pass + + def word_tokenize(self, word): + word = word.lower() + word = word.replace(",", "").replace("?", "").replace("'s", " 's") + return word.strip() + + def process_punctuation(self, in_text): + out_text = in_text + for p in self.PUNCTUATIONS: + if (p + " " in in_text or " " + p in in_text) or ( + re.search(self.COMMA_STRIP, in_text) is not None + ): + out_text = out_text.replace(p, "") + else: + out_text = out_text.replace(p, " ") + out_text = self.PERIOD_STRIP.sub("", out_text, re.UNICODE) + return out_text + + def process_digit_article(self, in_text): + out_text = [] + temp_text = in_text.lower().split() + for word in temp_text: + word = self.NUMBER_MAP.setdefault(word, word) + if word not in self.ARTICLES: + out_text.append(word) + else: + pass + for word_id, word in enumerate(out_text): + if word in self.CONTRACTIONS: + out_text[word_id] = self.CONTRACTIONS[word] + out_text = " ".join(out_text) + return out_text + + def __call__(self, item): + item = self.word_tokenize(item) + item = item.replace("\n", " ").replace("\t", " ").strip() + item = self.process_punctuation(item) + item = self.process_digit_article(item) + return item + + +class TextVQAAccuracyEvaluator: + def __init__(self): + self.answer_processor = EvalAIAnswerProcessor() + + def _compute_answer_scores(self, raw_answers): + """ + compute the accuracy (soft score) of human answers + """ + answers = [self.answer_processor(a) for a in raw_answers] + assert len(answers) == 10 + gt_answers = list(enumerate(answers)) + unique_answers = set(answers) + unique_answer_scores = {} + + for unique_answer in unique_answers: + accs = [] + for gt_answer in gt_answers: + other_answers = [item for item in gt_answers if item != gt_answer] + matching_answers = [ + item for item in other_answers if item[1] == unique_answer + ] + acc = min(1, float(len(matching_answers)) / 3) + accs.append(acc) + unique_answer_scores[unique_answer] = sum(accs) / len(accs) + + return unique_answer_scores + + def eval_pred_list(self, pred_list): + pred_scores = [] + for entry in tqdm(pred_list): + pred_answer = self.answer_processor(entry["pred_answer"]) + unique_answer_scores = self._compute_answer_scores(entry["gt_answers"]) + score = unique_answer_scores.get(pred_answer, 0.0) + pred_scores.append(score) + + accuracy = sum(pred_scores) / len(pred_scores) + return accuracy + + +class STVQAAccuracyEvaluator: + def __init__(self): + self.answer_processor = EvalAIAnswerProcessor() + + def eval_pred_list(self, pred_list): + pred_scores = [] + for entry in pred_list: + pred_answer = self.answer_processor(entry["pred_answer"]) + gts = [self.answer_processor(a) for a in entry["gt_answers"]] + score = 1.0 if pred_answer in gts else 0.0 + pred_scores.append(score) + + accuracy = sum(pred_scores) / len(pred_scores) + return accuracy + + +class STVQAANLSEvaluator: + def __init__(self): + import editdistance # install with `pip install editdistance` + + self.get_edit_distance = editdistance.eval + + def get_anls(self, s1, s2): + s1 = s1.lower().strip() + s2 = s2.lower().strip() + iou = 1 - self.get_edit_distance(s1, s2) / max(len(s1), len(s2)) + anls = iou if iou >= 0.5 else 0.0 + return anls + + def eval_pred_list(self, pred_list): + pred_scores = [] + for entry in pred_list: + anls = max( + self.get_anls(entry["pred_answer"], gt) for gt in entry["gt_answers"] + ) + pred_scores.append(anls) + + accuracy = sum(pred_scores) / len(pred_scores) + return accuracy + + +class TextCapsBleu4Evaluator: + def __init__(self): + # The following script requires Java 1.8.0 and pycocotools installed. + # The pycocoevalcap can be installed with pip as + # pip install git+https://github.com/ronghanghu/coco-caption.git@python23 + # Original pycocoevalcap code is at https://github.com/tylin/coco-caption + # but has no python3 support yet. + try: + from pycocoevalcap.bleu.bleu import Bleu + from pycocoevalcap.tokenizer.ptbtokenizer import PTBTokenizer + except ModuleNotFoundError: + print( + "Please install pycocoevalcap module using " + "pip install git+https://github.com/ronghanghu/coco-caption.git@python23" # noqa + ) + raise + + self.tokenizer = PTBTokenizer() + self.scorer = Bleu(4) + + def eval_pred_list(self, pred_list): + # Create reference and hypotheses captions. + gts = {} + res = {} + for idx, entry in enumerate(pred_list): + gts[idx] = [{"caption": a} for a in entry["gt_answers"]] + res[idx] = [{"caption": entry["pred_answer"]}] + + gts = self.tokenizer.tokenize(gts) + res = self.tokenizer.tokenize(res) + score, _ = self.scorer.compute_score(gts, res) + + bleu4 = score[3] # score is (Bleu-1, Bleu-2, Bleu-3, Bleu-4) + return bleu4 diff --git a/llava/eval/model_qa.py b/llava/eval/model_qa.py new file mode 100644 index 0000000000000000000000000000000000000000..2e254da152ac644ff54fb5fa57e625d9e6ba31d1 --- /dev/null +++ b/llava/eval/model_qa.py @@ -0,0 +1,64 @@ +import argparse +from transformers import AutoTokenizer, AutoModelForCausalLM, StoppingCriteria +import torch +import os +import json +from tqdm import tqdm +import shortuuid + +from llava.conversation import default_conversation +from llava.utils import disable_torch_init + + +@torch.inference_mode() +def eval_model(model_name, questions_file, answers_file): + # Model + disable_torch_init() + model_name = os.path.expanduser(model_name) + tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=False) + model = AutoModelForCausalLM.from_pretrained(model_name, + torch_dtype=torch.float16).cuda() + + + ques_file = open(os.path.expanduser(questions_file), "r") + ans_file = open(os.path.expanduser(answers_file), "w") + for i, line in enumerate(tqdm(ques_file)): + idx = json.loads(line)["question_id"] + qs = json.loads(line)["text"] + cat = json.loads(line)["category"] + conv = default_conversation.copy() + conv.append_message(conv.roles[0], qs) + prompt = conv.get_prompt() + inputs = tokenizer([prompt]) + input_ids = torch.as_tensor(inputs.input_ids).cuda() + output_ids = model.generate( + input_ids, + do_sample=True, + use_cache=True, + temperature=0.7, + max_new_tokens=1024,) + outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0] + try: + index = outputs.index(conv.sep, len(prompt)) + except ValueError: + outputs += conv.sep + index = outputs.index(conv.sep, len(prompt)) + + outputs = outputs[len(prompt) + len(conv.roles[1]) + 2:index].strip() + ans_id = shortuuid.uuid() + ans_file.write(json.dumps({"question_id": idx, + "text": outputs, + "answer_id": ans_id, + "model_id": model_name, + "metadata": {}}) + "\n") + ans_file.flush() + ans_file.close() + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--model-name", type=str, default="facebook/opt-350m") + parser.add_argument("--question-file", type=str, default="tables/question.jsonl") + parser.add_argument("--answers-file", type=str, default="answer.jsonl") + args = parser.parse_args() + + eval_model(args.model_name, args.question_file, args.answers_file) diff --git a/llava/eval/model_vqa.py b/llava/eval/model_vqa.py new file mode 100644 index 0000000000000000000000000000000000000000..8715ee1ef1d4ba6f48953152a8ab5387372a0f62 --- /dev/null +++ b/llava/eval/model_vqa.py @@ -0,0 +1,112 @@ +import argparse +import torch +import os +import json +from tqdm import tqdm +import shortuuid + +from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from llava.conversation import conv_templates, SeparatorStyle +from llava.model.builder import load_pretrained_model +from llava.utils import disable_torch_init +from llava.mm_utils import tokenizer_image_token, process_images, get_model_name_from_path + +from PIL import Image +import math + +def split_list(lst, n): + """Split a list into n (roughly) equal-sized chunks""" + chunk_size = math.ceil(len(lst) / n) # integer division + return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)] + + +def get_chunk(lst, n, k): + chunks = split_list(lst, n) + return chunks[k] + + +def eval_model(args): + # Model + disable_torch_init() + model_path = os.path.expanduser(args.model_path) + model_name = get_model_name_from_path(model_path) + tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name) + + questions = [json.loads(q) for q in open(os.path.expanduser(args.question_file), "r")] + questions = get_chunk(questions, args.num_chunks, args.chunk_idx) + answers_file = os.path.expanduser(args.answers_file) + os.makedirs(os.path.dirname(answers_file), exist_ok=True) + ans_file = open(answers_file, "w") + for line in tqdm(questions): + idx = line["id"] + image_file = line["image"] + qs = line["text"] + if 'box' in line: + box=line["box"] + else: + box="" + cur_prompt = qs + if model.config.mm_use_im_start_end: + qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs + else: + qs = DEFAULT_IMAGE_TOKEN + '\n' + qs + + conv = conv_templates[args.conv_mode].copy() + conv.append_message(conv.roles[0], qs) + conv.append_message(conv.roles[1], None) + prompt = conv.get_prompt() + + input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda() + + image = Image.open(os.path.join(args.image_folder, image_file)).convert('RGB') + # print("DEBUG",model.config) + image_tensor, image_new_size = process_images([image], image_processor, model.config) + # image_tensor,image_new_size = process_images([image], image_processor, model.config)[0] + + + with torch.inference_mode(): + output_ids = model.generate( + input_ids, + # images=image_tensor.unsqueeze(0).half().cuda(), + images=image_tensor.half().cuda(), + image_sizes=[image_new_size], + do_sample=True if args.temperature > 0 else False, + temperature=args.temperature, + top_p=args.top_p, + num_beams=args.num_beams, + # no_repeat_ngram_size=3, + max_new_tokens=16384, + use_cache=True) + + outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip() + + metadata = {k: v for k, v in line.items() if k not in ["id", "image", "text"]} + + ans_id = shortuuid.uuid() + ans_file.write(json.dumps({"question_id": idx, + 'image': image_file, + "prompt": cur_prompt, + "text": outputs, + "answer_id": ans_id, + "model_id": model_name, + "box": box, + "metadata": metadata}) + "\n") + ans_file.flush() + ans_file.close() + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--model-path", type=str, default="/fs/ess/PAS1576/boyu_gou/train_vlm/ui_llava_fine_tune/checkpoints/ui-llava-ocr-text/merged-llava-v1.5-vicuna-7b-16k-pad-fusion-ocr-100k-text-1-200k-mobile-aug-1-200k") + parser.add_argument("--model-base", type=str, default=None) + parser.add_argument("--image-folder", type=str, default="/fs/ess/PAS1576/boyu_gou/Benchmark/screenspot_imgs_resized/") + parser.add_argument("--question-file", type=str, default="/fs/ess/PAS1576/boyu_gou/Benchmark/screenspot_web_text.jsonl") + parser.add_argument("--answers-file", type=str, default="/fs/ess/PAS1576/boyu_gou/Benchmark/answer_screenspot_web.jsonl") + parser.add_argument("--conv-mode", type=str, default="llava_v1") + parser.add_argument("--num-chunks", type=int, default=1) + parser.add_argument("--chunk-idx", type=int, default=0) + parser.add_argument("--temperature", type=float, default=0.2) + parser.add_argument("--top_p", type=float, default=None) + parser.add_argument("--num_beams", type=int, default=1) + args = parser.parse_args() + + eval_model(args) diff --git a/llava/eval/model_vqa_loader.py b/llava/eval/model_vqa_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..d435b7d835bdfb2934e32a93f1e8eaab39420ad9 --- /dev/null +++ b/llava/eval/model_vqa_loader.py @@ -0,0 +1,144 @@ +import argparse +import torch +import os +import json +from tqdm import tqdm +import shortuuid + +from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from llava.conversation import conv_templates, SeparatorStyle +from llava.model.builder import load_pretrained_model +from llava.utils import disable_torch_init +from llava.mm_utils import tokenizer_image_token, process_images, get_model_name_from_path +from torch.utils.data import Dataset, DataLoader + +from PIL import Image +import math + + +def split_list(lst, n): + """Split a list into n (roughly) equal-sized chunks""" + chunk_size = math.ceil(len(lst) / n) # integer division + return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)] + + +def get_chunk(lst, n, k): + chunks = split_list(lst, n) + return chunks[k] + + +# Custom dataset class +class CustomDataset(Dataset): + def __init__(self, questions, image_folder, tokenizer, image_processor, model_config): + self.questions = questions + self.image_folder = image_folder + self.tokenizer = tokenizer + self.image_processor = image_processor + self.model_config = model_config + + def __getitem__(self, index): + line = self.questions[index] + image_file = line["image"] + qs = line["text"] + if self.model_config.mm_use_im_start_end: + qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs + else: + qs = DEFAULT_IMAGE_TOKEN + '\n' + qs + + conv = conv_templates[args.conv_mode].copy() + conv.append_message(conv.roles[0], qs) + conv.append_message(conv.roles[1], None) + prompt = conv.get_prompt() + + image = Image.open(os.path.join(self.image_folder, image_file)).convert('RGB') + image_tensor = process_images([image], self.image_processor, self.model_config)[0] + + input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt') + + return input_ids, image_tensor, image.size + + def __len__(self): + return len(self.questions) + + +def collate_fn(batch): + input_ids, image_tensors, image_sizes = zip(*batch) + input_ids = torch.stack(input_ids, dim=0) + image_tensors = torch.stack(image_tensors, dim=0) + return input_ids, image_tensors, image_sizes + + +# DataLoader +def create_data_loader(questions, image_folder, tokenizer, image_processor, model_config, batch_size=1, num_workers=4): + assert batch_size == 1, "batch_size must be 1" + dataset = CustomDataset(questions, image_folder, tokenizer, image_processor, model_config) + data_loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False, collate_fn=collate_fn) + return data_loader + + +def eval_model(args): + # Model + disable_torch_init() + model_path = os.path.expanduser(args.model_path) + model_name = get_model_name_from_path(model_path) + tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name) + + questions = [json.loads(q) for q in open(os.path.expanduser(args.question_file), "r")] + questions = get_chunk(questions, args.num_chunks, args.chunk_idx) + answers_file = os.path.expanduser(args.answers_file) + os.makedirs(os.path.dirname(answers_file), exist_ok=True) + ans_file = open(answers_file, "w") + + if 'plain' in model_name and 'finetune' not in model_name.lower() and 'mmtag' not in args.conv_mode: + args.conv_mode = args.conv_mode + '_mmtag' + print(f'It seems that this is a plain model, but it is not using a mmtag prompt, auto switching to {args.conv_mode}.') + + data_loader = create_data_loader(questions, args.image_folder, tokenizer, image_processor, model.config) + + for (input_ids, image_tensor, image_sizes), line in tqdm(zip(data_loader, questions), total=len(questions)): + idx = line["question_id"] + cur_prompt = line["text"] + + input_ids = input_ids.to(device='cuda', non_blocking=True) + + with torch.inference_mode(): + output_ids = model.generate( + input_ids, + images=image_tensor.to(dtype=torch.float16, device='cuda', non_blocking=True), + image_sizes=image_sizes, + do_sample=True if args.temperature > 0 else False, + temperature=args.temperature, + top_p=args.top_p, + num_beams=args.num_beams, + max_new_tokens=args.max_new_tokens, + use_cache=True) + + outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip() + + ans_id = shortuuid.uuid() + ans_file.write(json.dumps({"question_id": idx, + "prompt": cur_prompt, + "text": outputs, + "answer_id": ans_id, + "model_id": model_name, + "metadata": {}}) + "\n") + # ans_file.flush() + ans_file.close() + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--model-path", type=str, default="facebook/opt-350m") + parser.add_argument("--model-base", type=str, default=None) + parser.add_argument("--image-folder", type=str, default="") + parser.add_argument("--question-file", type=str, default="tables/question.jsonl") + parser.add_argument("--answers-file", type=str, default="answer.jsonl") + parser.add_argument("--conv-mode", type=str, default="llava_v1") + parser.add_argument("--num-chunks", type=int, default=1) + parser.add_argument("--chunk-idx", type=int, default=0) + parser.add_argument("--temperature", type=float, default=0.2) + parser.add_argument("--top_p", type=float, default=None) + parser.add_argument("--num_beams", type=int, default=1) + parser.add_argument("--max_new_tokens", type=int, default=128) + args = parser.parse_args() + + eval_model(args) diff --git a/llava/eval/model_vqa_mmbench.py b/llava/eval/model_vqa_mmbench.py new file mode 100644 index 0000000000000000000000000000000000000000..bd7a4c8085ddb7b237b17b054e5eaa0569018178 --- /dev/null +++ b/llava/eval/model_vqa_mmbench.py @@ -0,0 +1,160 @@ +import argparse +import torch +import os +import json +import pandas as pd +from tqdm import tqdm +import shortuuid + +from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from llava.conversation import conv_templates, SeparatorStyle +from llava.model.builder import load_pretrained_model +from llava.utils import disable_torch_init +from llava.mm_utils import tokenizer_image_token, process_images, load_image_from_base64, get_model_name_from_path + +from PIL import Image +import math + + +all_options = ['A', 'B', 'C', 'D'] + + +def split_list(lst, n): + """Split a list into n (roughly) equal-sized chunks""" + chunk_size = math.ceil(len(lst) / n) # integer division + return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)] + + +def get_chunk(lst, n, k): + chunks = split_list(lst, n) + return chunks[k] + + +def is_none(value): + if value is None: + return True + if type(value) is float and math.isnan(value): + return True + if type(value) is str and value.lower() == 'nan': + return True + if type(value) is str and value.lower() == 'none': + return True + return False + +def get_options(row, options): + parsed_options = [] + for option in options: + option_value = row[option] + if is_none(option_value): + break + parsed_options.append(option_value) + return parsed_options + + +def eval_model(args): + # Model + disable_torch_init() + model_path = os.path.expanduser(args.model_path) + model_name = get_model_name_from_path(model_path) + tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name) + + questions = pd.read_table(os.path.expanduser(args.question_file)) + questions = get_chunk(questions, args.num_chunks, args.chunk_idx) + answers_file = os.path.expanduser(args.answers_file) + os.makedirs(os.path.dirname(answers_file), exist_ok=True) + ans_file = open(answers_file, "w") + + if 'plain' in model_name and 'finetune' not in model_name.lower() and 'mmtag' not in args.conv_mode: + args.conv_mode = args.conv_mode + '_mmtag' + print(f'It seems that this is a plain model, but it is not using a mmtag prompt, auto switching to {args.conv_mode}.') + + for index, row in tqdm(questions.iterrows(), total=len(questions)): + options = get_options(row, all_options) + cur_option_char = all_options[:len(options)] + + if args.all_rounds: + num_rounds = len(options) + else: + num_rounds = 1 + + for round_idx in range(num_rounds): + idx = row['index'] + question = row['question'] + hint = row['hint'] + image = load_image_from_base64(row['image']) + if not is_none(hint): + question = hint + '\n' + question + for option_char, option in zip(all_options[:len(options)], options): + question = question + '\n' + option_char + '. ' + option + qs = cur_prompt = question + if model.config.mm_use_im_start_end: + qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs + else: + qs = DEFAULT_IMAGE_TOKEN + '\n' + qs + + if args.single_pred_prompt: + if args.lang == 'cn': + qs = qs + '\n' + "请直接回答选项字母。" + else: + qs = qs + '\n' + "Answer with the option's letter from the given choices directly." + + conv = conv_templates[args.conv_mode].copy() + conv.append_message(conv.roles[0], qs) + conv.append_message(conv.roles[1], None) + prompt = conv.get_prompt() + + input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda() + + image_tensor = process_images([image], image_processor, model.config)[0] + + with torch.inference_mode(): + output_ids = model.generate( + input_ids, + images=image_tensor.unsqueeze(0).half().cuda(), + image_sizes=[image.size], + do_sample=True if args.temperature > 0 else False, + temperature=args.temperature, + top_p=args.top_p, + num_beams=args.num_beams, + # no_repeat_ngram_size=3, + max_new_tokens=1024, + use_cache=True) + + outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip() + + ans_id = shortuuid.uuid() + ans_file.write(json.dumps({"question_id": idx, + "round_id": round_idx, + "prompt": cur_prompt, + "text": outputs, + "options": options, + "option_char": cur_option_char, + "answer_id": ans_id, + "model_id": model_name, + "metadata": {}}) + "\n") + ans_file.flush() + + # rotate options + options = options[1:] + options[:1] + cur_option_char = cur_option_char[1:] + cur_option_char[:1] + ans_file.close() + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--model-path", type=str, default="facebook/opt-350m") + parser.add_argument("--model-base", type=str, default=None) + parser.add_argument("--image-folder", type=str, default="") + parser.add_argument("--question-file", type=str, default="tables/question.jsonl") + parser.add_argument("--answers-file", type=str, default="answer.jsonl") + parser.add_argument("--conv-mode", type=str, default="llava_v1") + parser.add_argument("--num-chunks", type=int, default=1) + parser.add_argument("--chunk-idx", type=int, default=0) + parser.add_argument("--temperature", type=float, default=0.2) + parser.add_argument("--top_p", type=float, default=None) + parser.add_argument("--num_beams", type=int, default=1) + parser.add_argument("--all-rounds", action="store_true") + parser.add_argument("--single-pred-prompt", action="store_true") + parser.add_argument("--lang", type=str, default="en") + args = parser.parse_args() + + eval_model(args) diff --git a/llava/eval/model_vqa_science.py b/llava/eval/model_vqa_science.py new file mode 100644 index 0000000000000000000000000000000000000000..90fc681a20ee72131862772107f6be572f010c99 --- /dev/null +++ b/llava/eval/model_vqa_science.py @@ -0,0 +1,111 @@ +import argparse +import torch +import os +import json +from tqdm import tqdm +import shortuuid + +from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from llava.conversation import conv_templates, SeparatorStyle +from llava.model.builder import load_pretrained_model +from llava.utils import disable_torch_init +from llava.mm_utils import tokenizer_image_token, process_images, get_model_name_from_path + +from PIL import Image +import math + + +def split_list(lst, n): + """Split a list into n (roughly) equal-sized chunks""" + chunk_size = math.ceil(len(lst) / n) # integer division + return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)] + + +def get_chunk(lst, n, k): + chunks = split_list(lst, n) + return chunks[k] + + +def eval_model(args): + # Model + disable_torch_init() + model_path = os.path.expanduser(args.model_path) + model_name = get_model_name_from_path(model_path) + tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name) + + questions = json.load(open(os.path.expanduser(args.question_file), "r")) + questions = get_chunk(questions, args.num_chunks, args.chunk_idx) + answers_file = os.path.expanduser(args.answers_file) + os.makedirs(os.path.dirname(answers_file), exist_ok=True) + ans_file = open(answers_file, "w") + for i, line in enumerate(tqdm(questions)): + idx = line["id"] + question = line['conversations'][0] + qs = question['value'].replace('', '').strip() + cur_prompt = qs + + if 'image' in line: + image_file = line["image"] + image = Image.open(os.path.join(args.image_folder, image_file)) + image_tensor = process_images([image], image_processor, model.config)[0] + images = image_tensor.unsqueeze(0).half().cuda() + image_sizes = [image.size] + if getattr(model.config, 'mm_use_im_start_end', False): + qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs + else: + qs = DEFAULT_IMAGE_TOKEN + '\n' + qs + cur_prompt = '' + '\n' + cur_prompt + else: + images = None + image_sizes = None + + if args.single_pred_prompt: + qs = qs + '\n' + "Answer with the option's letter from the given choices directly." + cur_prompt = cur_prompt + '\n' + "Answer with the option's letter from the given choices directly." + + conv = conv_templates[args.conv_mode].copy() + conv.append_message(conv.roles[0], qs) + conv.append_message(conv.roles[1], None) + prompt = conv.get_prompt() + + input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda() + + with torch.inference_mode(): + output_ids = model.generate( + input_ids, + images=images, + image_sizes=image_sizes, + do_sample=True if args.temperature > 0 else False, + temperature=args.temperature, + max_new_tokens=1024, + use_cache=True, + ) + + outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip() + + ans_id = shortuuid.uuid() + ans_file.write(json.dumps({"question_id": idx, + "prompt": cur_prompt, + "text": outputs, + "answer_id": ans_id, + "model_id": model_name, + "metadata": {}}) + "\n") + ans_file.flush() + ans_file.close() + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--model-path", type=str, default="facebook/opt-350m") + parser.add_argument("--model-base", type=str, default=None) + parser.add_argument("--image-folder", type=str, default="") + parser.add_argument("--question-file", type=str, default="tables/question.json") + parser.add_argument("--answers-file", type=str, default="answer.jsonl") + parser.add_argument("--conv-mode", type=str, default="llava_v0") + parser.add_argument("--num-chunks", type=int, default=1) + parser.add_argument("--chunk-idx", type=int, default=0) + parser.add_argument("--temperature", type=float, default=0.2) + parser.add_argument("--answer-prompter", action="store_true") + parser.add_argument("--single-pred-prompt", action="store_true") + args = parser.parse_args() + + eval_model(args) diff --git a/llava/eval/qa_baseline_gpt35.py b/llava/eval/qa_baseline_gpt35.py new file mode 100644 index 0000000000000000000000000000000000000000..babab6e12b4bb8cfa74a7edfa5e56cd1b3e2bf6c --- /dev/null +++ b/llava/eval/qa_baseline_gpt35.py @@ -0,0 +1,74 @@ +"""Generate answers with GPT-3.5""" +# Note: you need to be using OpenAI Python v0.27.0 for the code below to work +import argparse +import json +import os +import time +import concurrent.futures + +import openai +import tqdm +import shortuuid + +MODEL = 'gpt-3.5-turbo' +MODEL_ID = 'gpt-3.5-turbo:20230327' + +def get_answer(question_id: int, question: str, max_tokens: int): + ans = { + 'answer_id': shortuuid.uuid(), + 'question_id': question_id, + 'model_id': MODEL_ID, + } + for _ in range(3): + try: + response = openai.ChatCompletion.create( + model=MODEL, + messages=[{ + 'role': 'system', + 'content': 'You are a helpful assistant.' + }, { + 'role': 'user', + 'content': question, + }], + max_tokens=max_tokens, + ) + ans['text'] = response['choices'][0]['message']['content'] + return ans + except Exception as e: + print('[ERROR]', e) + ans['text'] = '#ERROR#' + time.sleep(1) + return ans + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='ChatGPT answer generation.') + parser.add_argument('-q', '--question') + parser.add_argument('-o', '--output') + parser.add_argument('--max-tokens', type=int, default=1024, help='maximum number of tokens produced in the output') + args = parser.parse_args() + + questions_dict = {} + with open(os.path.expanduser(args.question)) as f: + for line in f: + if not line: + continue + q = json.loads(line) + questions_dict[q['question_id']] = q['text'] + + answers = [] + + with concurrent.futures.ThreadPoolExecutor(max_workers=32) as executor: + futures = [] + for qid, question in questions_dict.items(): + future = executor.submit(get_answer, qid, question, args.max_tokens) + futures.append(future) + + for future in tqdm.tqdm(concurrent.futures.as_completed(futures), total=len(futures)): + answers.append(future.result()) + + answers.sort(key=lambda x: x['question_id']) + + with open(os.path.expanduser(args.output), 'w') as f: + table = [json.dumps(ans) for ans in answers] + f.write('\n'.join(table)) diff --git a/llava/eval/run_llava.py b/llava/eval/run_llava.py new file mode 100644 index 0000000000000000000000000000000000000000..24b0fffcc11a2045dfc7f5ac6cae4f057aaba6d6 --- /dev/null +++ b/llava/eval/run_llava.py @@ -0,0 +1,145 @@ +import argparse +import torch + +from llava.constants import ( + IMAGE_TOKEN_INDEX, + DEFAULT_IMAGE_TOKEN, + DEFAULT_IM_START_TOKEN, + DEFAULT_IM_END_TOKEN, + IMAGE_PLACEHOLDER, +) +from llava.conversation import conv_templates, SeparatorStyle +from llava.model.builder import load_pretrained_model +from llava.utils import disable_torch_init +from llava.mm_utils import ( + process_images, + tokenizer_image_token, + get_model_name_from_path, +) + +from PIL import Image + +import requests +from PIL import Image +from io import BytesIO +import re + + +def image_parser(args): + out = args.image_file.split(args.sep) + return out + + +def load_image(image_file): + if image_file.startswith("http") or image_file.startswith("https"): + response = requests.get(image_file) + image = Image.open(BytesIO(response.content)).convert("RGB") + else: + image = Image.open(image_file).convert("RGB") + return image + + +def load_images(image_files): + out = [] + for image_file in image_files: + image = load_image(image_file) + out.append(image) + return out + + +def eval_model(args): + # Model + disable_torch_init() + + model_name = get_model_name_from_path(args.model_path) + tokenizer, model, image_processor, context_len = load_pretrained_model( + args.model_path, args.model_base, model_name + ) + + qs = args.query + image_token_se = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + if IMAGE_PLACEHOLDER in qs: + if model.config.mm_use_im_start_end: + qs = re.sub(IMAGE_PLACEHOLDER, image_token_se, qs) + else: + qs = re.sub(IMAGE_PLACEHOLDER, DEFAULT_IMAGE_TOKEN, qs) + else: + if model.config.mm_use_im_start_end: + qs = image_token_se + "\n" + qs + else: + qs = DEFAULT_IMAGE_TOKEN + "\n" + qs + + if "llama-2" in model_name.lower(): + conv_mode = "llava_llama_2" + elif "mistral" in model_name.lower(): + conv_mode = "mistral_instruct" + elif "v1.6-34b" in model_name.lower(): + conv_mode = "chatml_direct" + elif "v1" in model_name.lower(): + conv_mode = "llava_v1" + elif "mpt" in model_name.lower(): + conv_mode = "mpt" + else: + conv_mode = "llava_v0" + + if args.conv_mode is not None and conv_mode != args.conv_mode: + print( + "[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}".format( + conv_mode, args.conv_mode, args.conv_mode + ) + ) + else: + args.conv_mode = conv_mode + + conv = conv_templates[args.conv_mode].copy() + conv.append_message(conv.roles[0], qs) + conv.append_message(conv.roles[1], None) + prompt = conv.get_prompt() + + image_files = image_parser(args) + images = load_images(image_files) + image_sizes = [x.size for x in images] + images_tensor = process_images( + images, + image_processor, + model.config + ).to(model.device, dtype=torch.float16) + + input_ids = ( + tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt") + .unsqueeze(0) + .cuda() + ) + + with torch.inference_mode(): + output_ids = model.generate( + input_ids, + images=images_tensor, + image_sizes=image_sizes, + do_sample=True if args.temperature > 0 else False, + temperature=args.temperature, + top_p=args.top_p, + num_beams=args.num_beams, + max_new_tokens=args.max_new_tokens, + use_cache=True, + ) + + outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip() + print(outputs) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--model-path", type=str, default="facebook/opt-350m") + parser.add_argument("--model-base", type=str, default=None) + parser.add_argument("--image-file", type=str, required=True) + parser.add_argument("--query", type=str, required=True) + parser.add_argument("--conv-mode", type=str, default=None) + parser.add_argument("--sep", type=str, default=",") + parser.add_argument("--temperature", type=float, default=0.2) + parser.add_argument("--top_p", type=float, default=None) + parser.add_argument("--num_beams", type=int, default=1) + parser.add_argument("--max_new_tokens", type=int, default=512) + args = parser.parse_args() + + eval_model(args) diff --git a/llava/eval/seeact/__init__.py b/llava/eval/seeact/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f777aa2b723674ec858f8532ca4f9a779fafa6fe --- /dev/null +++ b/llava/eval/seeact/__init__.py @@ -0,0 +1,14 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2024 OSU Natural Language Processing Group +# +# Licensed under the OpenRAIL-S License; +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.licenses.ai/ai-pubs-open-rails-vz1 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. \ No newline at end of file diff --git a/llava/eval/seeact/agent.py b/llava/eval/seeact/agent.py new file mode 100644 index 0000000000000000000000000000000000000000..4e0b30c2ff51a3ddd2d5025db1380413a4b54e38 --- /dev/null +++ b/llava/eval/seeact/agent.py @@ -0,0 +1,945 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2024 OSU Natural Language Processing Group +# +# Licensed under the OpenRAIL-S License; +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.licenses.ai/ai-pubs-open-rails-vz1 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import os +import traceback +from datetime import datetime +import json +import toml +import torch +from playwright.async_api import async_playwright,Locator + +from .data_utils.format_prompt_utils import get_index_from_option_name, generate_new_query_prompt, \ + generate_new_referring_prompt, format_options +from .demo_utils.browser_helper import normal_launch_async, normal_new_context_async, \ + get_interactive_elements_with_playwright, select_option, saveconfig, get_select_elements_with_playwright +from .demo_utils.format_prompt import format_choices, postprocess_action_lmm +from .demo_utils.inference_engine import engine_factory + + + +from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from llava.conversation import conv_templates +from llava.model.builder import load_pretrained_model +from llava.utils import disable_torch_init +from llava.mm_utils import tokenizer_image_token, process_images, get_model_name_from_path + +from PIL import Image, ImageDraw,ImageFont + +import numpy as np + +import asyncio + + +def average_color(image, bbox): + """计算指定区域的平均颜色。""" + region = image.crop(bbox) + numpy_image = np.array(region) + avg_color = np.mean(numpy_image, axis=(0, 1)) + return tuple(avg_color) + + +def color_contrast(color1, color2): + """计算两种颜色之间的对比度。""" + l1 = 0.2126 * pow(color1[0]/255, 2.2) + \ + 0.7152 * pow(color1[1]/255, 2.2) + \ + 0.0722 * pow(color1[2]/255, 2.2) + l2 = 0.2126 * pow(color2[0]/255, 2.2) + \ + 0.7152 * pow(color2[1]/255, 2.2) + \ + 0.0722 * pow(color2[2]/255, 2.2) + if l1 > l2: + return (l1 + 0.05) / (l2 + 0.05) + else: + return (l2 + 0.05) / (l1 + 0.05) + +def text_color_for_background(background_color): + """选择最佳的文本颜色基于背景颜色。""" + red = (255, 0, 0) + blue = (0, 0, 255) + contrast_red = color_contrast(background_color, red) + contrast_blue = color_contrast(background_color, blue) + if contrast_red > contrast_blue: + return red + else: + return blue + + +def draw_text(draw, text, position, font, max_width, image): + """在图像上绘制自动换行的文本,并根据背景色调整文本颜色。""" + x, y = position + words = text.split() + current_line = "" + + # 使用一个空字符串来获取单行文字的高度 + line_height = 40 + + for word in words: + test_line = f"{current_line} {word}".strip() + width, _ = 40,40 # 正确调用font对象的getsize方法 + if width <= max_width: + current_line = test_line + else: + bbox = (x, y, x + width, y + line_height) + bg_color = average_color(image, bbox) + color = text_color_for_background(bg_color) + draw.text((x, y), current_line, font=font, fill=color) + y += line_height + current_line = word + if current_line: + bbox = (x, y, x + width, y + line_height) + bg_color = average_color(image, bbox) + color = text_color_for_background(bg_color) + draw.text((x, y), current_line, font=font, fill=color) + + +class SeeActAgent: + def __init__(self, + config_path=None, + save_file_dir="seeact_agent_files", + save_task_id=None, + default_task='Search for the flight status for the flight AA 3942 leaving on Jun. 10"', + default_website="https://www.aa.com/homePage.do", + input_info=["screenshot"], + grounding_strategy="text_choice", + max_auto_op=50, + max_continuous_no_op=5, + highlight=False, + headless=False, + args=[], + browser_app="chrome", + persistant=False, + persistant_user_path="", + save_video=False, + viewport={ + "width": 1280, + "height": 960 + }, + tracing=False, + trace={ + "screenshots": True, + "snapshots": True, + "sources": True + }, + rate_limit=-1, + model="gpt-4-turbo", + temperature=0.9 + + ): + + try: + if config_path is not None: + with open(config_path, + 'r') as config: + print(f"Configuration File Loaded - {config_path}") + config = toml.load(config) + else: + config = { + "basic": { + "save_file_dir": save_file_dir, + "default_task": default_task, + "default_website": default_website + }, + "agent": { + "input_info": input_info, + "grounding_strategy": grounding_strategy, + "max_auto_op": max_auto_op, + "max_continuous_no_op": max_continuous_no_op, + "highlight": highlight + }, + "openai": { + "rate_limit": rate_limit, + "model": model, + "temperature": temperature + } + } + config.update({ + "browser": { + "headless": headless, + "args": args, + "browser_app": browser_app, + "persistant": persistant, + "persistant_user_path": persistant_user_path, + "save_video": save_video, + "viewport": viewport, + "tracing": tracing, + "trace": trace + } + }) + + except FileNotFoundError: + print(f"Error: File '{os.path.abspath(config_path)}' not found.") + except toml.TomlDecodeError: + print(f"Error: File '{os.path.abspath(config_path)}' is not a valid TOML file.") + + self.config = config + self.complete_flag = False + self.session_control = { + 'active_page': None, + 'context': None, + 'browser': None + } + self.tasks = [self.config["basic"]["default_task"]] + if save_task_id: + self.main_path = os.path.join(self.config["basic"]["save_file_dir"], + save_task_id) + + + else: + self.main_path = os.path.join(self.config["basic"]["save_file_dir"], datetime.now().strftime("%Y%m%d_%H%M%S")) + if os.path.exists(self.main_path): + self.complete_flag=True + + os.makedirs(self.main_path, exist_ok=True) + self.action_space = ["CLICK", "PRESS ENTER", "HOVER", "SCROLL UP", "SCROLL DOWN", "NEW TAB", "CLOSE TAB", + "GO BACK", "GO FORWARD", + "TERMINATE", "SELECT", "TYPE", "GOTO", "MEMORIZE"] # Define the list of actions here + + self.no_value_op = ["CLICK", "PRESS ENTER", "HOVER", "SCROLL UP", "SCROLL DOWN", "NEW TAB", "CLOSE TAB", + "PRESS HOME", "PRESS END", "PRESS PAGEUP", "PRESS PAGEDOWN" + "GO BACK", + "GO FORWARD", + "TERMINATE", "NONE"] + + self.with_value_op = ["SELECT", "TYPE", "GOTO", "MEMORIZE", "SAY"] + + self.no_element_op = ["PRESS ENTER", "SCROLL UP", "SCROLL DOWN", "NEW TAB", "CLOSE TAB", "GO BACK", "GOTO", + "PRESS HOME", "PRESS END", "PRESS PAGEUP", "PRESS PAGEDOWN", + "GO FORWARD", + "TERMINATE", "NONE", "MEMORIZE", "SAY"] + + # Initialize the primary logger and the developer logger + self.logger = self._setup_logger(redirect_to_dev_log=False) + # self.dev_logger = self._setup_dev_logger() + + # # Redirect primary logger messages to dev_logger as well + # for handler in self.logger.handlers: + # self.dev_logger.addHandler(handler) + + self.engine = engine_factory(**self.config['openai']) + self.taken_actions = [] + self.prompts = self._initialize_prompts() + self.time_step = 0 + self.valid_op = 0 + # self.error=0 + self.continuous_no_op = 0 + self.predictions=[] + + disable_torch_init() + self.pixui_model_path = os.path.expanduser( + "/fs/ess/PAS1576/boyu_gou/train_vlm/ui_llava_fine_tune/checkpoints/only-web/merged-llava-v1.5-vicuna-7b-16k-pad-no-fusion-web-80k") + self.pixui_model_name = get_model_name_from_path(self.pixui_model_path) + self.pixui_tokenizer, self.pixui_model, self.pixui_image_processor, self.pixui_context_len = load_pretrained_model(self.pixui_model_path, None, self.pixui_model_name) + + def _initialize_prompts(self): + """Initialize prompt information including dynamic action space.""" + action_format = f"" # Dynamically generate action_format based on self.action_space + + return { + "system_prompt": '''You are assisting humans doing web navigation tasks step by step. At each stage, you can see the webpage by a screenshot and know the previous actions before the current step decided by yourself that have been executed for this task through recorded history. You need to decide on the first following action to take.''', + + "action_space": ''' +Here are the descriptions of all allowed actions: + +No Value Operations: +- CLICK: Click on a webpage element using the mouse. +- PRESS ENTER: Press the Enter key, typically to submit a form or confirm an input. +- SCROLL UP: Scroll the webpage upwards by half of the window height. +- SCROLL DOWN: Scroll the webpage downwards by half of the window height. +- PRESS HOME: Scroll to the top of the webpage. +- PRESS END: Scroll to the bottom of the webpage. +- PRESS PAGEUP: Scroll up by one window height. +- PRESS PAGEDOWN: Scroll down by one window height. +- GO BACK: Navigate to the previous page in the browser history. +- GO FORWARD: Navigate to the next page in the browser history. +- TERMINATE: End the current task, typically used when the task is considered complete or requires potentially harmful actions. +- NONE: Indicates that no action is necessary at this stage. Used to skip an action or wait. + +With Value Operations: +- SELECT: Choose an option from a dropdown menu or elements), you should try directly typing the input or selecting the choice, bypassing the need for an initial click. +4. You should not attempt to create accounts, log in or do the final submission. +5. Terminate when you deem the task complete or if it requires potentially harmful actions. +6. Details of elements), you should try directly typing the input or selecting the choice, bypassing the need for an initial click. You should not attempt to create accounts, log in or do the final submission. Terminate when you deem the task complete or if it requires potentially harmful actions.''' + +seeact_online_question_description_new_exp4 = '''The screenshot below shows the webpage you see. Follow the following guidance to think step by step before outlining the next action step at the current stage: + +(Current Webpage Identification) +Firstly, think about what the current webpage is. + +(Previous Action Analysis) +Secondly, combined with the screenshot, analyze each step of the previous action history and their intention one by one. Particularly, pay more attention to the last step, which may be more related to what you should do now as the next step. Specifically, if the last action involved a TYPE, always evaluate whether it necessitates a confirmation step, because typically a single TYPE action does not make effect. (often, simply pressing 'Enter', assuming the default element involved in the last action, unless other clear elements are present for operation). + +(Screenshot Details Analysis) +Closely examine the screenshot to check the status of every part of the webpage to understand what you can operate with and what has been set or completed. You should closely examine the screenshot details to see what steps have been completed by previous actions even though you are given the textual previous actions. Because the textual history may not clearly and sufficiently record some effects of previous actions, you should closely evaluate the status of every part of the webpage to understand what you have done. + +(Next Action Based on Webpage and Analysis) +Then, based on your analysis, in conjunction with human web browsing habits and the logic of web design, decide on the following action. And clearly outline which element in the webpage users will operate with as the first next target element, its detailed location, and the corresponding operation. + +To be successful, it is important to follow the following rules: +1. You should only issue a valid action given the current observation. +2. You should only issue one action at a time +3. For handling the select dropdown elements on the webpage, it's not necessary for you to provide completely accurate options right now. The full list of options for these elements will be supplied later.''' + +seeact_online_action_format = "ACTION: Choose an action from {CLICK, SELECT, TYPE, PRESS ENTER, TERMINATE, NONE}." + +seeact_online_value_format = "VALUE: Provide additional input based on ACTION.\n\nThe VALUE means:\nIf ACTION == TYPE, specify the " \ + "text to be typed.\nIf ACTION == SELECT, indicate the option to be chosen. Revise the selection value to align with the available options within the element.\nIf ACTION == CLICK, PRESS ENTER, TERMINATE or NONE, " \ + "write \"None\"." + +seeact_choice_prompt_dict = { + "system_prompt": seeact_online_sys_prompt, + + "question_description": seeact_online_question_description_new_exp4, + + "referring_description": f"""(Reiteration) +First, reiterate your next target element, its detailed location, and the corresponding operation. + +(Multichoice Question) +Below is a multi-choice question, where the choices are elements in the webpage. All elements are arranged in the order based on their height on the webpage, from top to bottom (and from left to right). This arrangement can be used to locate them. From the screenshot, find out where and what each one is on the webpage, taking into account both their text content and HTML details. Then, determine whether one matches your target element. Please examine the choices one by one. Choose the matching one. If multiple options match your answer, choose the most likely one by re-examining the screenshot, the choices, and your further reasoning.""", + + "element_format": """(Final Answer) +Finally, conclude your answer using the format below. Ensure your answer is strictly adhering to the format provided below. Please do not leave any explanation in your answers of the final standardized format part, and this final part should be clear and certain. The element choice, action, and value should be in three separate lines. + +Format: + +ELEMENT: The uppercase letter of your choice. (No need for PRESS ENTER)""", + + "action_format": f"{seeact_online_action_format}", + + "value_format": f"{seeact_online_value_format}" +} + + +def generate_prompt(experiment_split, task=None, previous=None, choices=None): + assert experiment_split != None, "Please specify the experiment split." + assert task != None, "Please input the task." + assert previous != None, "Please input the previous actions." + + if False: + raise Exception("Please change experiment type to seeact") + elif experiment_split in ["seeact_online","online","seeact","SeeAct"]: + system_prompt_input = seeact_choice_prompt_dict["system_prompt"] + question_description_input = seeact_choice_prompt_dict["question_description"] + referring_input = seeact_choice_prompt_dict["referring_description"] + element_format_input = seeact_choice_prompt_dict["element_format"] + action_format_input = seeact_choice_prompt_dict["action_format"] + value_format_input = seeact_choice_prompt_dict["value_format"] + prompt_list = [] + + prompt_list.extend( + generate_new_query_prompt(system_prompt=system_prompt_input, task=task, previous_actions=previous, + question_description=question_description_input)) + prompt_list.append( + generate_new_referring_prompt(referring_description=referring_input, element_format=element_format_input, + action_format=action_format_input, value_format=value_format_input, + choices=choices)) + return prompt_list + diff --git a/llava/eval/seeact/demo_utils/__init__.py b/llava/eval/seeact/demo_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/llava/eval/seeact/demo_utils/browser_helper.py b/llava/eval/seeact/demo_utils/browser_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..417cf39b5b9edf885c50d139c33df332aea7846c --- /dev/null +++ b/llava/eval/seeact/demo_utils/browser_helper.py @@ -0,0 +1,457 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2024 OSU Natural Language Processing Group +# +# Licensed under the OpenRAIL-S License; +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.licenses.ai/ai-pubs-open-rails-vz1 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import re +import asyncio +from difflib import SequenceMatcher +from playwright.sync_api import Playwright, expect, sync_playwright +# from playwright.async_api import async_playwright +from pathlib import Path +import toml +import os +import traceback + +async def normal_launch_async(playwright: Playwright,headless=False,args=None): + browser = await playwright.chromium.launch( + traces_dir=None, + headless=False, + args=args, + # ignore_default_args=ignore_args, + # chromium_sandbox=False, + ) + return browser + + + +async def normal_new_context_async( + browser, + storage_state=None, + har_path=None, + video_path=None, + tracing=False, + trace_screenshots=False, + trace_snapshots=False, + trace_sources=False, + locale=None, + geolocation=None, + user_agent: str = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36", + viewport: dict = {"width": 1280, "height": 720}, +): + context = await browser.new_context( + storage_state=storage_state, + user_agent=user_agent, + viewport=viewport, + locale=locale, + record_har_path=har_path, + record_video_dir=video_path, + geolocation=geolocation, + ) + + if tracing: + await context.tracing.start(screenshots=trace_screenshots, snapshots=trace_snapshots, sources=trace_sources) + return context + +# +# def persistent_launch(playwright: Playwright, user_data_dir: str = ""): +# context = playwright.chromium.launch_persistent_context( +# user_data_dir=user_data_dir, +# headless=False, +# args=["--no-default-browser-check", +# "--no_sandbox", +# "--disable-blink-features=AutomationControlled", +# ], +# ignore_default_args=ignore_args, +# user_agent="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36", +# viewport={"width": 1280, "height": 720}, +# bypass_csp=True, +# slow_mo=1000, +# chromium_sandbox=True, +# channel="chrome-dev" +# ) +# return context + +# +# async def persistent_launch_async(playwright: Playwright, user_data_dir: str = "", record_video_dir="video"): +# context = await playwright.chromium.launch_persistent_context( +# user_data_dir=user_data_dir, +# headless=False, +# args=[ +# "--disable-blink-features=AutomationControlled", +# ], +# ignore_default_args=ignore_args, +# user_agent="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36", +# # viewport={"width": 1280, "height": 720}, +# record_video_dir=record_video_dir, +# channel="chrome-dev" +# # slow_mo=1000, +# ) +# return context + + + +def remove_extra_eol(text): + # Replace EOL symbols + text = text.replace('\n', ' ') + return re.sub(r'\s{2,}', ' ', text) + + +def get_first_line(s): + first_line = s.split('\n')[0] + tokens = first_line.split() + if len(tokens) > 8: + return ' '.join(tokens[:8]) + '...' + else: + return first_line + +async def get_element_description(element, tag_name, role_value, type_value): + ''' + Asynchronously generates a descriptive text for a web element based on its tag type. + Handles various HTML elements like 'select', 'input', and 'textarea', extracting attributes and content relevant to accessibility and interaction. + ''' + # text_content = await element.inner_text(timeout=0) + # text = (text_content or '').strip() + # + # print(text) + salient_attributes = [ + "alt", + "aria-describedby", + "aria-label", + "aria-role", + "input-checked", + # "input-value", + "label", + "name", + "option_selected", + "placeholder", + "readonly", + "text-value", + "title", + "value", + ] + + parent_value = "parent_node: " + parent_locator = element.locator('xpath=..') + num_parents = await parent_locator.count() + if num_parents > 0: + # only will be zero or one parent node + parent_text = (await parent_locator.inner_text(timeout=0) or "").strip() + if parent_text: + parent_value += parent_text + parent_value = remove_extra_eol(get_first_line(parent_value)).strip() + if parent_value == "parent_node:": + parent_value = "" + else: + parent_value += " " + + if tag_name == "select": + text1 = "Selected Options: " + text3 = " - Options: " + + text2 = await element.evaluate( + "select => select.options[select.selectedIndex].textContent", timeout=0 + ) + + if text2: + options = await element.evaluate("select => Array.from(select.options).map(option => option.text)", + timeout=0) + text4 = " | ".join(options) + + if not text4: + text4 = await element.text_content(timeout=0) + if not text4: + text4 = await element.inner_text(timeout=0) + + + return parent_value+text1 + remove_extra_eol(text2.strip()) + text3 + text4 + + input_value = "" + + none_input_type = ["submit", "reset", "checkbox", "radio", "button", "file"] + + if tag_name == "input" or tag_name == "textarea": + if role_value not in none_input_type and type_value not in none_input_type: + text1 = "input value=" + text2 = await element.input_value(timeout=0) + if text2: + input_value = text1 + "\"" + text2 + "\"" + " " + + text_content = await element.text_content(timeout=0) + text = (text_content or '').strip() + + # print(text) + if text: + text = remove_extra_eol(text) + if len(text) > 80: + text_content_in = await element.inner_text(timeout=0) + text_in = (text_content_in or '').strip() + if text_in: + return input_value + remove_extra_eol(text_in) + else: + return input_value + text + + # get salient_attributes + text1 = "" + for attr in salient_attributes: + attribute_value = await element.get_attribute(attr, timeout=0) + if attribute_value: + text1 += f"{attr}=" + "\"" + attribute_value.strip() + "\"" + " " + + text = (parent_value + text1).strip() + if text: + return input_value + remove_extra_eol(text.strip()) + + + # try to get from the first child node + first_child_locator = element.locator('xpath=./child::*[1]') + + num_childs = await first_child_locator.count() + if num_childs>0: + for attr in salient_attributes: + attribute_value = await first_child_locator.get_attribute(attr, timeout=0) + if attribute_value: + text1 += f"{attr}=" + "\"" + attribute_value.strip() + "\"" + " " + + text = (parent_value + text1).strip() + if text: + return input_value + remove_extra_eol(text.strip()) + + return None + + +async def get_element_data(element, tag_name,viewport_size,seen_elements=[],coordinates=None): + try: + tag_name_list = ['a', 'button', + 'input', + 'select', 'textarea', 'adc-tab'] + + + + + + + rect = await element.bounding_box() or {'x': -1, 'y': -1, 'width': 0, 'height': 0} + + if rect['x']<0 or rect['y']<0 or rect['width']<=4 or rect['height']<=4 or rect['y']+rect['height']>viewport_size["height"] or rect['x']+ rect['width']>viewport_size["width"]: + return None + + + + if coordinates is not None: + if coordinates[0]>=rect['x'] and coordinates[0]<=rect['x']+rect['width'] and coordinates[1]>=rect['y'] and coordinates[1]<=rect['y']+rect['height']: + print(coordinates) + print(rect) + else: + return None + + + box_model = [rect['x'], rect['y'], rect['x'] + rect['width'], rect['y'] + rect['height']] + center_point = (round((box_model[0] + box_model[2]) / 2 , 3), + round((box_model[1] + box_model[3]) / 2 , 3)) + + + + + + if await element.is_hidden(timeout=0) or await element.is_disabled(timeout=0): + return None + + if center_point in seen_elements: + return None + + # await aprint(element,tag_name) + + if tag_name in tag_name_list: + tag_head = tag_name + real_tag_name = tag_name + else: + real_tag_name = await element.evaluate("element => element.tagName.toLowerCase()", timeout=0) + if real_tag_name in tag_name_list: + # already detected + return None + else: + tag_head = real_tag_name + + text_element = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'td', "div","em","center","strong","b","i","small","mark","abbr","cite","q","blockquote","span","nobr"] + + if real_tag_name in text_element: + return None + + role_value = await element.get_attribute('role', timeout=0) + type_value = await element.get_attribute('type', timeout=0) + # await aprint("start to get element description",element,tag_name ) + description = await get_element_description(element, real_tag_name, role_value, type_value) + # print(description) + if not description: + return None + + if role_value: + tag_head += " role=" + "\"" + role_value + "\"" + if type_value: + tag_head += " type=" + "\"" + type_value + "\"" + + ''' + 0: center_point =(x,y) + 1: description + 2: tag_with_role: tag_head with role and type # TODO: Consider adding more + 3. box + 4. selector + 5. tag + ''' + selector = element + + + if coordinates is not None: + if coordinates[0]>=rect['x'] and coordinates[0]<=rect['x']+rect['width'] and coordinates[1]>=rect['y'] and coordinates[1]<=rect['y']+rect['height']: + print(tag_head) + print(description) + print(box_model) + else: + + + return None + + return {"center_point":center_point,"description":description,"tag_with_role":tag_head,"box":box_model,"selector":selector,"tag":real_tag_name} + # return [center_point, description, tag_head, box_model, selector, real_tag_name] + except Exception as e: + print(traceback.format_exc()) + print(e) + return None + + +async def get_interactive_elements_with_playwright(page,viewport_size,coordinates=None): + + print("Get Interactive elements around: ", coordinates) + interactive_elements_selectors = [ + 'a', 'button', + 'input', + 'select', 'textarea', + ] + + seen_elements = set() + tasks = [] + + + for selector in interactive_elements_selectors: + locator = page.locator(selector) + element_count = await locator.count() + for index in range(element_count): + element = locator.nth(index) + tag_name = selector + task = get_element_data(element, tag_name,viewport_size,seen_elements=[],coordinates=coordinates) + + tasks.append(task) + + results = await asyncio.gather(*tasks) + + interactive_elements = [] + for i in results: + if i: + if i["center_point"] in seen_elements: + continue + else: + seen_elements.add(i["center_point"]) + interactive_elements.append(i) + + # interactive_elements_selectors = [ + # '*' + # ] + # tasks = [] + # + # for selector in interactive_elements_selectors: + # locator = page.locator(selector) + # element_count = await locator.count() + # for index in range(element_count): + # element = locator.nth(index) + # tag_name = selector + # task = get_element_data(element, tag_name, viewport_size,seen_elements,coordinates) + # + # tasks.append(task) + # + # results = await asyncio.gather(*tasks) + # + # + # for i in results: + # if i: + # if i["center_point"] in seen_elements: + # continue + # else: + # seen_elements.add(i["center_point"]) + # interactive_elements.append(i) + + return interactive_elements + + + +async def get_select_elements_with_playwright(page,viewport_size): + + interactive_elements_selectors = [ + 'select' + ] + + seen_elements = set() + tasks = [] + + + for selector in interactive_elements_selectors: + locator = page.locator(selector) + element_count = await locator.count() + for index in range(element_count): + element = locator.nth(index) + tag_name = selector + task = get_element_data(element, tag_name,viewport_size,seen_elements=[],coordinates=None) + + tasks.append(task) + + results = await asyncio.gather(*tasks) + + interactive_elements = [] + for i in results: + if i: + if i["center_point"] in seen_elements: + continue + else: + seen_elements.add(i["center_point"]) + interactive_elements.append(i) + + return interactive_elements + + +async def select_option(selector, value): + best_option = [-1, "", -1] + for i in range(await selector.locator("option").count()): + option = await selector.locator("option").nth(i).inner_text() + similarity = SequenceMatcher(None, option, value).ratio() + if similarity > best_option[2]: + best_option = [i, option, similarity] + await selector.select_option(index=best_option[0], timeout=10000) + return remove_extra_eol(best_option[1]).strip() + + +def saveconfig(config, save_file): + """ + config is a dictionary. + save_path: saving path include file name. + """ + + + if isinstance(save_file, str): + save_file = Path(save_file) + if isinstance(config, dict): + with open(save_file, 'w') as f: + config_without_key = config + config_without_key["openai"]["api_key"] = "Your API key here" + toml.dump(config_without_key, f) + else: + os.system(" ".join(["cp", str(config), str(save_file)])) diff --git a/llava/eval/seeact/demo_utils/format_prompt.py b/llava/eval/seeact/demo_utils/format_prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..a758fbc3afbef673dfbd3093d10ce209ae687364 --- /dev/null +++ b/llava/eval/seeact/demo_utils/format_prompt.py @@ -0,0 +1,133 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2024 OSU Natural Language Processing Group +# +# Licensed under the OpenRAIL-S License; +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.licenses.ai/ai-pubs-open-rails-vz1 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import re + + +def format_choices(elements): + + converted_elements = [ + f'<{element["tag_with_role"]}>' + + ( + element["description"] + ) + + f"" + for i, element in enumerate(elements) + ] + + return converted_elements + +def postprocess_action_lmm(text): + text = text.strip() + text = text.replace( + "The uppercase letter of your choice. Choose one of the following elements if it matches the target element based on your analysis:\n\n", + "") + text = text.replace( + "The uppercase letter of your choice. Choose one of the following elements if it matches the target element based on your analysis:\n", + "") + text = text.replace( + "The uppercase letter of your choice. Choose one of the following elements if it matches the target element based on your analysis:", + "") + text = text.replace("The uppercase letter of your choice based on your analysis is:\n\n", "") + text = text.replace("The uppercase letter of your choice based on your analysis is:\n", "") + text = text.replace("The uppercase letter of your choice based on your analysis is:", "") + text = text.replace("The uppercase letter of my choice is \n\n", "") + text = text.replace("The uppercase letter of my choice is \n", "") + text = text.replace("The uppercase letter of my choice is ", "") + text = text.replace("The uppercase letter of your choice is \n\n", "") + text = text.replace("The uppercase letter of your choice is \n", "") + text = text.replace("The uppercase letter of your choice is ", "") + text = text.replace("The uppercase letter of your choice.\n\n", "") + text = text.replace("The uppercase letter of your choice.\n", "") + text = text.replace("The uppercase letter of your choice.", "") + text = text.replace("The uppercase letter of your choice based on my analysis is:\n\n", "") + text = text.replace("The uppercase letter of your choice based on my analysis is:\n", "") + text = text.replace("The uppercase letter of your choice based on my analysis is:", "") + text = text.replace("The correct choice based on the analysis would be:\n\n", "") + text = text.replace("The correct choice based on the analysis would be:\n", "") + text = text.replace("The correct choice based on the analysis would be :", "") + text = text.replace("The correct choice based on the analysis would be ", "") + text = text.replace( + "The uppercase letter of your choice. Choose one of the following elements if it matches the target element based on your analysis:\n\n", + "") + text = text.replace( + "The uppercase letter of your choice. Choose one of the following elements if it matches the target element based on your analysis:\n", + "") + text = text.replace( + "The uppercase letter of your choice. Choose one of the following elements if it matches the target element based on your analysis:", + "") + text = text.replace("The uppercase letter of your choice.\n\n", "") + text = text.replace("The uppercase letter of your choice.\n", "") + text = text.replace("The uppercase letter of your choice based on the analysis is:\n\n", "") + text = text.replace("The uppercase letter of your choice based on the analysis is:\n", "") + text = text.replace("The uppercase letter of your choice based on the analysis is:", "") + text = text.replace("The uppercase letter of your choice based on the analysis is ", "") + text = text.replace("The uppercase letter of my choice based on the analysis is:\n\n", "") + text = text.replace("The uppercase letter of my choice based on the analysis is:\n", "") + text = text.replace("The uppercase letter of my choice based on the analysis is:", "") + text = text.replace("The uppercase letter of my choice based on the analysis is ", "") + text = text.replace("The correct element to select would be:\n\n", "") + text = text.replace("The correct element to select would be:\n", "") + text = text.replace("The correct element to select would be:", "") + text = text.replace("The correct element to select would be ", "") + text = text.replace("The uppercase letter of my choice is:\n\n", "") + text = text.replace("The uppercase letter of my choice is:\n", "") + text = text.replace("The uppercase letter of my choice is:", "") + text = text.replace("The uppercase letter of my choice is ", "") + text = text.replace("Choose an action from {CLICK, TYPE, SELECT}.\n\n", "") + text = text.replace("Choose an action from {CLICK, TYPE, SELECT}.\n", "") + text = text.replace("Choose an action from {CLICK, TYPE, SELECT}.", "") + text = text.replace("Provide additional input based on ACTION.\n\n", "") + text = text.replace("Provide additional input based on ACTION.\n", "") + text = text.replace("Provide additional input based on ACTION.", "") + + def extract_element_description(text): + pattern = r'ELEMENT:\s*(.*?)\s*ACTION:' + match = re.search(pattern, text) + if match: + return match.group(1) + else: + return None + + description = extract_element_description(text) + action = re.search( + r"ACTION: (CLICK|SELECT|TYPE|HOVER|PRESS ENTER|SCROLL UP|SCROLL DOWN|PRESS HOME|PRESS END|PRESS PAGEUP|PRESS PAGEDOWN|NEW TAB|CLOSE TAB|GO BACK|GO FORWARD|TERMINATE|NONE|GOTO|SAY|MEMORIZE)", + text + ) + + + if action: + action = action.group(1) + else: + action = "None" + + value = re.search(r"VALUE: (.*)$", text, re.MULTILINE) + value = value.group(1) if value is not None else "" + return description, action.strip(), process_string(process_string(value.strip())) + +def process_string(input_string): + if input_string.startswith('"') and input_string.endswith('"'): + input_string = input_string[1:-1] + if input_string.endswith('.'): + input_string = input_string[:-1] + return input_string + + + + + + + + + diff --git a/llava/eval/seeact/demo_utils/inference_engine.py b/llava/eval/seeact/demo_utils/inference_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..42ce620b37378c3e6dbd36d9206104f4bc7a3a3e --- /dev/null +++ b/llava/eval/seeact/demo_utils/inference_engine.py @@ -0,0 +1,314 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2024 OSU Natural Language Processing Group +# +# Licensed under the OpenRAIL-S License; +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.licenses.ai/ai-pubs-open-rails-vz1 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +import time + +import backoff +import openai +from openai import ( + APIConnectionError, + APIError, + RateLimitError, +) +import requests +from dotenv import load_dotenv +import litellm +import base64 + +EMPTY_API_KEY="Your API KEY Here" + +def load_openai_api_key(): + load_dotenv() + assert ( + os.getenv("OPENAI_API_KEY") is not None and + os.getenv("OPENAI_API_KEY") != EMPTY_API_KEY + ), "must pass on the api_key or set OPENAI_API_KEY in the environment" + return os.getenv("OPENAI_API_KEY") + + +def load_gemini_api_key(): + load_dotenv() + assert ( + os.getenv("GEMINI_API_KEY") is not None and + os.getenv("GEMINI_API_KEY") != EMPTY_API_KEY + ), "must pass on the api_key or set GEMINI_API_KEY in the environment" + return os.getenv("GEMINI_API_KEY") + +def encode_image(image_path): + with open(image_path, "rb") as image_file: + return base64.b64encode(image_file.read()).decode('utf-8') + + +def engine_factory(api_key=None, model=None, **kwargs): + model = model.lower() + if model in ["gpt-4-vision-preview", "gpt-4-turbo", "gpt-4o"]: + if api_key and api_key != EMPTY_API_KEY: + os.environ["OPENAI_API_KEY"] = api_key + else: + load_openai_api_key() + return OpenAIEngine(model=model, **kwargs) + elif model in ["gemini-1.5-pro-latest", "gemini-1.5-flash"]: + if api_key and api_key != EMPTY_API_KEY: + os.environ["GEMINI_API_KEY"] = api_key + else: + load_gemini_api_key() + model=f"gemini/{model}" + return GeminiEngine(model=model, **kwargs) + elif model == "llava": + model="llava" + return OllamaEngine(model=model, **kwargs) + raise Exception(f"Unsupported model: {model}, currently supported models: \ + gpt-4-vision-preview, gpt-4-turbo, gemini-1.5-pro-latest, llava") + +class Engine: + def __init__( + self, + stop=["\n\n"], + rate_limit=-1, + model=None, + temperature=0, + **kwargs, + ) -> None: + """ + Base class to init an engine + + Args: + api_key (_type_, optional): Auth key from OpenAI. Defaults to None. + stop (list, optional): Tokens indicate stop of sequence. Defaults to ["\n"]. + rate_limit (int, optional): Max number of requests per minute. Defaults to -1. + model (_type_, optional): Model family. Defaults to None. + """ + self.time_slots = [0] + self.stop = stop + self.temperature = temperature + self.model = model + # convert rate limit to minmum request interval + self.request_interval = 0 if rate_limit == -1 else 60.0 / rate_limit + self.next_avil_time = [0] * len(self.time_slots) + self.current_key_idx = 0 + print(f"Initializing model {self.model}") + + def tokenize(self, input): + return self.tokenizer(input) + + +class OllamaEngine(Engine): + def __init__(self, **kwargs) -> None: + """ + Init an Ollama engine + To use Ollama, dowload and install Ollama from https://ollama.com/ + After Ollama start, pull llava with command: ollama pull llava + """ + super().__init__(**kwargs) + self.api_url = "http://localhost:11434/api/chat" + + + def generate(self, prompt: list = None, max_new_tokens=4096, temperature=None, model=None, image_path=None, + ouput_0=None, turn_number=0, **kwargs): + self.current_key_idx = (self.current_key_idx + 1) % len(self.time_slots) + start_time = time.time() + if ( + self.request_interval > 0 + and start_time < self.next_avil_time[self.current_key_idx] + ): + wait_time = self.next_avil_time[self.current_key_idx] - start_time + print(f"Wait {wait_time} for rate limitting") + time.sleep(wait_time) + prompt0, prompt1, prompt2 = prompt + + base64_image = encode_image(image_path) + if turn_number == 0: + # Assume one turn dialogue + prompt_input = [ + {"role": "assistant", "content": prompt0}, + {"role": "user", "content": prompt1, "images": [f"{base64_image}"]}, + ] + elif turn_number == 1: + prompt_input = [ + {"role": "assistant", "content": prompt0}, + {"role": "user", "content": prompt1, "images": [f"{base64_image}"]}, + {"role": "assistant", "content": f"\n\n{ouput_0}"}, + {"role": "user", "content": prompt2}, + ] + + options = {"temperature": self.temperature, "num_predict": max_new_tokens} + data = { + "model": self.model, + "messages": prompt_input, + "options": options, + "stream": False, + } + _request = { + "url": f"{self.api_url}", + "json": data, + } + response = requests.post(**_request) # type: ignore + if response.status_code != 200: + raise Exception(f"Ollama API Error: {response.status_code}, {response.text}") + response_json = response.json() + return response_json["message"]["content"] + + +class GeminiEngine(Engine): + def __init__(self, **kwargs) -> None: + """ + Init a Gemini engine + To use this engine, please provide the GEMINI_API_KEY in the environment + Supported Model Rate Limit + gemini-1.5-pro-latest 2 queries per minute, 1000 queries per day + """ + super().__init__(**kwargs) + + + def generate(self, prompt: list = None, max_new_tokens=4096, temperature=None, model=None, image_path=None, + ouput_0=None, turn_number=0, **kwargs): + self.current_key_idx = (self.current_key_idx + 1) % len(self.time_slots) + start_time = time.time() + if ( + self.request_interval > 0 + and start_time < self.next_avil_time[self.current_key_idx] + ): + wait_time = self.next_avil_time[self.current_key_idx] - start_time + print(f"Wait {wait_time} for rate limitting") + prompt0, prompt1, prompt2 = prompt + litellm.set_verbose=True + + base64_image = encode_image(image_path) + if turn_number == 0: + # Assume one turn dialogue + prompt_input = [ + {"role": "system", "content": prompt0}, + {"role": "user", + "content": [{"type": "text", "text": prompt1}, {"type": "image_url", "image_url": {"url": image_path, + "detail": "high"}, + }]}, + ] + elif turn_number == 1: + prompt_input = [ + {"role": "system", "content": prompt0}, + {"role": "user", + "content": [{"type": "text", "text": prompt1}, {"type": "image_url", "image_url": {"url": image_path, + "detail": "high"}, + }]}, + {"role": "assistant", "content": [{"type": "text", "text": f"\n\n{ouput_0}"}]}, + {"role": "user", "content": [{"type": "text", "text": prompt2}]}, + ] + response = litellm.completion( + model=model if model else self.model, + messages=prompt_input, + max_tokens=max_new_tokens if max_new_tokens else 4096, + temperature=temperature if temperature else self.temperature, + **kwargs, + ) + return [choice["message"]["content"] for choice in response.choices][0] + + +class OpenAIEngine(Engine): + def __init__(self, **kwargs) -> None: + """ + Init an OpenAI GPT/Codex engine + To find your OpenAI API key, visit https://platform.openai.com/api-keys + """ + super().__init__(**kwargs) + + @backoff.on_exception( + backoff.expo, + (APIError, RateLimitError, APIConnectionError), + ) + def generate(self, prompt: list = None, max_new_tokens=4096, temperature=None, model=None, image_path=None, + ouput_0=None, turn_number=0, **kwargs): + self.current_key_idx = (self.current_key_idx + 1) % len(self.time_slots) + start_time = time.time() + if ( + self.request_interval > 0 + and start_time < self.next_avil_time[self.current_key_idx] + ): + time.sleep(self.next_avil_time[self.current_key_idx] - start_time) + prompt0, prompt1, prompt2 = prompt + # litellm.set_verbose=True + + base64_image = encode_image(image_path) + if turn_number == 0: + # Assume one turn dialogue + prompt_input = [ + {"role": "system", "content": [{"type": "text", "text": prompt0}]}, + {"role": "user", + "content": [{"type": "text", "text": prompt1}, {"type": "image_url", "image_url": {"url": + f"data:image/jpeg;base64,{base64_image}", + "detail": "high"}, + }]}, + ] + elif turn_number == 1: + prompt_input = [ + {"role": "system", "content": [{"type": "text", "text": prompt0}]}, + {"role": "user", + "content": [{"type": "text", "text": prompt1}, {"type": "image_url", "image_url": {"url": + f"data:image/jpeg;base64,{base64_image}", + "detail": "high"}, }]}, + {"role": "assistant", "content": [{"type": "text", "text": f"\n\n{ouput_0}"}]}, + {"role": "user", "content": [{"type": "text", "text": prompt2}]}, + ] + response = litellm.completion( + model=model if model else self.model, + messages=prompt_input, + max_tokens=max_new_tokens if max_new_tokens else 4096, + temperature=temperature if temperature else self.temperature, + **kwargs, + ) + return [choice["message"]["content"] for choice in response.choices][0] + + +class OpenaiEngine_MindAct(Engine): + def __init__(self, **kwargs) -> None: + """Init an OpenAI GPT/Codex engine + + Args: + api_key (_type_, optional): Auth key from OpenAI. Defaults to None. + stop (list, optional): Tokens indicate stop of sequence. Defaults to ["\n"]. + rate_limit (int, optional): Max number of requests per minute. Defaults to -1. + model (_type_, optional): Model family. Defaults to None. + """ + super().__init__(**kwargs) + # + @backoff.on_exception( + backoff.expo, + (APIError, RateLimitError, APIConnectionError), + ) + def generate(self, prompt, max_new_tokens=50, temperature=0, model=None, **kwargs): + self.current_key_idx = (self.current_key_idx + 1) % len(self.time_slots) + start_time = time.time() + if ( + self.request_interval > 0 + and start_time < self.next_avil_time[self.current_key_idx] + ): + time.sleep(self.next_avil_time[self.current_key_idx] - start_time) + if isinstance(prompt, str): + # Assume one turn dialogue + prompt = [ + {"role": "user", "content": prompt}, + ] + response = litellm.completion( + model=model if model else self.model, + messages=prompt, + max_tokens=max_new_tokens, + temperature=temperature, + **kwargs, + ) + if self.request_interval > 0: + self.next_avil_time[self.current_key_idx] = ( + max(start_time, self.next_avil_time[self.current_key_idx]) + + self.request_interval + ) + return [choice["message"]["content"] for choice in response["choices"]] diff --git a/llava/eval/seeact_run.py b/llava/eval/seeact_run.py new file mode 100644 index 0000000000000000000000000000000000000000..733cf47067e8d7f6aa8653c5feec964f9dac80cf --- /dev/null +++ b/llava/eval/seeact_run.py @@ -0,0 +1,118 @@ +import asyncio +import os +import random + +from seeact.agent import SeeActAgent + +# Setup your API Key here, or pass through environment +os.environ["OPENAI_API_KEY"] = "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" +# os.environ["GEMINI_API_KEY"] = "Your API KEY Here" + + +async def run_agent(): + agent = SeeActAgent(model="gpt-4o") + await agent.start() + while not agent.complete_flag: + prediction_dict = await agent.predict() + await agent.execute(prediction_dict) + await agent.stop() + +if __name__ == "__main__": + asyncio.run(run_agent()) +# +# async def run_agent(): +# +# import json +# +# # Define the input file path +# input_file = "tasks.json" +# +# # Load the data from the input file +# with open(input_file, 'r', encoding='utf-8') as infile: +# data = json.load(infile) +# +# # Iterate through each data point and print the required fields +# +# data=[i for i in data] +# random.shuffle(data) +# for item in data: +# +# +# website = item.get("website", "N/A") +# task_id = item.get("task_id", "N/A") +# confirmed_task = item.get("confirmed_task", "N/A") +# +# agent = SeeActAgent(model="gpt-4o",default_task=confirmed_task,default_website=website,save_task_id=task_id) +# await agent.start() +# count = 0 +# try: +# while not agent.complete_flag and count < 20: +# prediction_dict = await agent.predict() +# await agent.execute(prediction_dict) +# count += 1 +# except Exception as e: +# print(e) +# try: +# await agent.stop() +# except Exception as e: +# print(e) +# +# +# +# +# if __name__ == "__main__": +# asyncio.run(run_agent()) + + + + + + + +# import asyncio +# import os +# from seeact.agent import SeeActAgent +# +# # Setup your API Key here, or pass through environment +# os.environ["OPENAI_API_KEY"] = "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" +# # os.environ["GEMINI_API_KEY"] = "Your API KEY Here" +# +# async def process_task(item): +# website = item.get("website", "N/A") +# task_id = item.get("task_id", "N/A") +# confirmed_task = item.get("confirmed_task", "N/A") +# +# agent = SeeActAgent(model="gpt-4o", default_task=confirmed_task, default_website=website, save_task_id=task_id,save_file_dir="mind2web-online90") +# await agent.start() +# count = 0 +# while not agent.complete_flag and count < 20: +# prediction_dict = await agent.predict() +# await agent.execute(prediction_dict) +# count += 1 +# await agent.stop() +# +# async def run_agent(): +# import json +# +# # Define the input file path +# input_file = "tasks.json" +# +# # Load the data from the input file +# with open(input_file, 'r', encoding='utf-8') as infile: +# data = json.load(infile) +# +# # Use a semaphore to limit the number of concurrent tasks +# semaphore = asyncio.Semaphore(1) +# +# async def sem_task(item): +# async with semaphore: +# await process_task(item) +# +# # Schedule all the tasks +# tasks = [sem_task(item) for item in data] +# await asyncio.gather(*tasks) +# +# if __name__ == "__main__": +# asyncio.run(run_agent()) + + diff --git a/llava/eval/summarize_gpt_review.py b/llava/eval/summarize_gpt_review.py new file mode 100644 index 0000000000000000000000000000000000000000..0f796a3880341739677a5fe3bfbcc90515a0f324 --- /dev/null +++ b/llava/eval/summarize_gpt_review.py @@ -0,0 +1,60 @@ +import json +import os +from collections import defaultdict + +import numpy as np + +import argparse + +def parse_args(): + parser = argparse.ArgumentParser(description='ChatGPT-based QA evaluation.') + parser.add_argument('-d', '--dir', default=None) + parser.add_argument('-v', '--version', default=None) + parser.add_argument('-s', '--select', nargs='*', default=None) + parser.add_argument('-f', '--files', nargs='*', default=[]) + parser.add_argument('-i', '--ignore', nargs='*', default=[]) + return parser.parse_args() + + +if __name__ == '__main__': + args = parse_args() + + if args.ignore is not None: + args.ignore = [int(x) for x in args.ignore] + + if len(args.files) > 0: + review_files = args.files + else: + review_files = [x for x in os.listdir(args.dir) if x.endswith('.jsonl') and (x.startswith('gpt4_text') or x.startswith('reviews_') or x.startswith('review_') or 'review' in args.dir)] + + for review_file in sorted(review_files): + config = os.path.basename(review_file).replace('gpt4_text_', '').replace('.jsonl', '') + if args.select is not None and any(x not in config for x in args.select): + continue + if '0613' in config: + version = '0613' + else: + version = '0314' + if args.version is not None and args.version != version: + continue + scores = defaultdict(list) + print(config) + with open(os.path.join(args.dir, review_file) if args.dir is not None else review_file) as f: + for review_str in f: + review = json.loads(review_str) + if review['question_id'] in args.ignore: + continue + if 'category' in review: + scores[review['category']].append(review['tuple']) + scores['all'].append(review['tuple']) + else: + if 'tuple' in review: + scores['all'].append(review['tuple']) + else: + scores['all'].append(review['score']) + for k, v in sorted(scores.items()): + stats = np.asarray(v).mean(0).tolist() + stats = [round(x, 3) for x in stats] + # print(k, stats, round(stats[1]/stats[0]*100, 1)) + print(k, round(stats[1]/stats[0]*100, 1), round(stats[0] * 10, 1), round(stats[1] * 10, 1)) + print('=================================') diff --git a/llava/eval/webpage/figures/alpaca.png b/llava/eval/webpage/figures/alpaca.png new file mode 100644 index 0000000000000000000000000000000000000000..497a702ab5efb88b8f67333eae81645eecea78cd Binary files /dev/null and b/llava/eval/webpage/figures/alpaca.png differ diff --git a/llava/eval/webpage/figures/bard.jpg b/llava/eval/webpage/figures/bard.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5b32cb501799175e3829f92b014795ad1cbee79d Binary files /dev/null and b/llava/eval/webpage/figures/bard.jpg differ diff --git a/llava/eval/webpage/figures/chatgpt.svg b/llava/eval/webpage/figures/chatgpt.svg new file mode 100644 index 0000000000000000000000000000000000000000..8147382a3152de03c24b4cd91f9870ced1a95d54 --- /dev/null +++ b/llava/eval/webpage/figures/chatgpt.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/llava/eval/webpage/figures/llama.jpg b/llava/eval/webpage/figures/llama.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7217e5dc1bb683453204a20890f01f5806ce12cf Binary files /dev/null and b/llava/eval/webpage/figures/llama.jpg differ diff --git a/llava/eval/webpage/figures/swords_FILL0_wght300_GRAD0_opsz48.svg b/llava/eval/webpage/figures/swords_FILL0_wght300_GRAD0_opsz48.svg new file mode 100644 index 0000000000000000000000000000000000000000..3bee468d34515fdcbef1a8b8803c9fc4f7dc0b34 --- /dev/null +++ b/llava/eval/webpage/figures/swords_FILL0_wght300_GRAD0_opsz48.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/llava/eval/webpage/figures/vicuna.jpeg b/llava/eval/webpage/figures/vicuna.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..e7883dc886b96d078883e01aefd16792133e204a Binary files /dev/null and b/llava/eval/webpage/figures/vicuna.jpeg differ diff --git a/llava/eval/webpage/index.html b/llava/eval/webpage/index.html new file mode 100644 index 0000000000000000000000000000000000000000..c2e3cf020ba7d8e064f2cd801788a5d2d50b97da --- /dev/null +++ b/llava/eval/webpage/index.html @@ -0,0 +1,162 @@ + + + + + + Who's GPT-4's favorite? Battles between State-of-the-Art Chatbots + + + + + + + + +
+

Who's GPT-4's favorite? Battles between State-of-the-Art Chatbots

+ + +
+
+ + +
+
+ + +
+
+
+
+ + +
+
+
+ + +
+
+ +
+
+
+ other logo +
+
+
+
+ + +
+
+
+
+ vicuna logo +
+
+
+ +
+
+ + +
+
+
+ + +
+
+
+
+
+
+ +
+
+ +
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Assistant #2 (Vicuna, our model) +
+
+
+
+
+
+
+
+
+
+ + +
+
GPT-4 Evaluation
+
+
+
+
+
+
+
+
+ +
+
+ This website is co-authored with GPT-4. +
+
+ + + + + + + + + + + + + diff --git a/llava/eval/webpage/script.js b/llava/eval/webpage/script.js new file mode 100644 index 0000000000000000000000000000000000000000..4b71e3d5618a262e4746f58e5d10947b73370dca --- /dev/null +++ b/llava/eval/webpage/script.js @@ -0,0 +1,245 @@ +// Description: Script for the evaluation webpage. + +let currentQuestionIndex = 1; + +// Store the model name mapping for later use. +modelNameMapping = { + "gpt35": "ChatGPT-3.5", + "gpt4": "GPT-4", + "alpaca": "Alpaca-13b", + "vicuna": "Vicuna-13b", + "llama": "LLaMA-13b", + "bard": "Bard", +}; + +modelFigureMapping = { + "vicuna": "figures/vicuna.jpeg", + // Image from: https://commons.wikimedia.org/wiki/File:ChatGPT_logo.svg + "gpt35": "figures/chatgpt.svg", + // Image from: https://www.reddit.com/r/logodesign/comments/1128aat/google_ai_bard_logo_design/ + "bard": "figures/bard.jpg", + // Image from: https://crfm.stanford.edu/2023/03/13/alpaca.html + "alpaca": "figures/alpaca.png", + // Image adapted from https://commons.wikimedia.org/wiki/File:Llama_on_Machu_Picchu.jpg + "llama": "figures/llama.jpg", +} + +// Store the question data in a mapping for later use. +questionMapping = {}; +// Store the question ids in a mapping for later use. +categoryMapping = {}; +// Store the number of questions for later use. +questionsCount = 0; + + +function text2Markdown(text) { + // Normalize the text for markdown rendering. + text = text.trim().replaceAll('\n\n', '\n').replaceAll('\n', '\n\n'); + return marked.parse(text); +} + +function capitalizeFirstChar(str) { + if (!str || str.length === 0) { + return str; + } + return str.charAt(0).toUpperCase() + str.slice(1); +} + +function updateQuestionSelect(question_id) { + const select = document.getElementById('question-select'); + // Clear the question select. + select.innerHTML = ''; + // Populate the question select. + category = questionMapping[question_id].category; + categoryMapping[category].forEach(question_id => { + const question = questionMapping[question_id]; + const option = document.createElement('option'); + option.value = question_id; + option.textContent = 'Q' + question_id.toString() + ': ' + question.question; + select.appendChild(option); + }); + select.value = question_id; +} + +function updateModelSelect() { + const select = document.getElementById('model-select'); + img_path = modelFigureMapping[select.value]; + document.getElementById('other-model-figure').src = img_path; +} + +function populateModels(models) { + const select = document.getElementById('model-select'); + models.forEach(model => { + const option = document.createElement('option'); + option.value = model; + option.textContent = modelNameMapping[model]; + select.appendChild(option); + }); + updateModelSelect(); +} + +function populateQuestions(questions) { + const category_select = document.getElementById('category-select'); + + questionsCount = questions.length; + questions.forEach(question => { + const option = document.createElement('option'); + // Store the question data in a mapping for later use. + questionMapping[question.id] = { + category: question.category, + question: question.question, + answers: question.answers, + evaluations: question.evaluations, + scores: question.scores, + }; + // Store the question id in the category mapping. + if (question.category in categoryMapping) { + categoryMapping[question.category].push(question.id); + } else { + categoryMapping[question.category] = [question.id]; + const category_option = document.createElement('option'); + category_option.value = question.category; + category_option.textContent = capitalizeFirstChar(question.category); + category_select.appendChild(category_option); + } + }); + // Set the default category. + updateQuestionSelect(currentQuestionIndex); +} + +function displayQuestion(index) { + const question = questionMapping[index].question; + document.getElementById('selected-question').innerHTML = text2Markdown('**Question:** ' + question); + displayAnswers(index); +} + +function displayAnswers(index) { + const question = questionMapping[index]; + const otherModel = document.getElementById('model-select').value; + // render the answers with markdown + document.getElementById('other-model-answer').innerHTML = text2Markdown(question.answers[otherModel]); + document.getElementById('our-model-answer').innerHTML = text2Markdown(question.answers.vicuna); + + // Display evaluation + score = question.scores[otherModel]; + score_text = modelNameMapping[otherModel] + " " + score[0] + "/10, Vicuna-13b " + score[1] + "/10"; + document.getElementById('evaluation-header').textContent = "GPT-4 Evaluation" + " (Score: " + score_text + ")"; + document.getElementById('evaluation-result').innerHTML = text2Markdown(question.evaluations[otherModel]); + + // Update model names + let assistant1_title = "Assistant #1"; // (" + modelNameMapping[otherModel] + ")"; + let assistant2_title = "Assistant #2 (Vicuna-13b, our model)"; + // Update scores/labels. + let assistant1_score_label = score[0].toString() + '/10'; + let assistant2_score_label = score[1].toString() + '/10'; + + const colorRed ='#fa9'; // '#eb978d'; + // const colorGreen = '#c9f2c9'; + const colorBlue = '#8ef'; // '#71dbf9'; + const colorYellow = '#fe7'; // '#fada57'; + let otherModelHeaderColor = ''; + let ourModelHeaderColor = ''; + // Update the winner. + if (score[0] == score[1]) { + assistant1_title = '🏆 ' + assistant1_title; + assistant1_score_label = '🏆 ' + assistant1_score_label; + assistant2_title = '🏆 ' + assistant2_title; + assistant2_score_label = '🏆 ' + assistant2_score_label; + otherModelHeaderColor = colorYellow; + ourModelHeaderColor = colorYellow; + } else if (score[0] > score[1]) { + assistant1_title = '🏆 ' + assistant1_title; + assistant1_score_label = '🏆 ' + assistant1_score_label; + otherModelHeaderColor = colorBlue; + ourModelHeaderColor = colorRed; + } else if (score[0] < score[1]) { + assistant2_title = '🏆 ' + assistant2_title; + assistant2_score_label = '🏆 ' + assistant2_score_label; + otherModelHeaderColor = colorRed; + ourModelHeaderColor = colorBlue; + } + + document.getElementById('other-model-header-bg').style.backgroundColor = otherModelHeaderColor; + document.getElementById('our-model-header').style.backgroundColor = ourModelHeaderColor; + + document.getElementById('other-model-header').textContent = assistant1_title; + document.getElementById('our-model-header').textContent = assistant2_title; + + document.getElementById('other-score-label').textContent = assistant1_score_label; + document.getElementById('our-score-label').textContent = assistant2_score_label; + + // Update expand buttons visibility for both cards after displaying answers + // Reset the expanded state and update expand buttons visibility for both cards after displaying answers + document.querySelectorAll('.expandable-card').forEach(card => { + card.classList.remove('expanded'); + updateExpandButtonVisibility(card); + const expandBtn = card.querySelector('.expand-btn'); + expandBtn.innerHTML = 'keyboard_arrow_down Show more'; // .textContent = 'Show more'; + }); +} + +document.getElementById('question-select').addEventListener('change', e => { + currentQuestionIndex = parseInt(e.target.value); + displayQuestion(currentQuestionIndex); +}); + +document.getElementById('category-select').addEventListener('change', e => { + let currentCategory = e.target.value; + const questionIds = categoryMapping[currentCategory]; + currentQuestionIndex = questionIds[0]; + updateQuestionSelect(currentQuestionIndex); + displayQuestion(currentQuestionIndex); +}); + +// Update expand buttons whenever the model is changed +document.getElementById('model-select').addEventListener('change', () => { + displayAnswers(currentQuestionIndex); + document.querySelectorAll('.expandable-card').forEach(card => { + updateExpandButtonVisibility(card); + }); + updateModelSelect(); +}); + +function switchQuestionAndCategory() { + document.getElementById('question-select').value = currentQuestionIndex; + old_category = document.getElementById('category-select').value; + new_category = questionMapping[currentQuestionIndex].category; + if (old_category != new_category) { + document.getElementById('category-select').value = new_category; + updateQuestionSelect(currentQuestionIndex); + } + displayQuestion(currentQuestionIndex); +} + +document.getElementById('prev-question').addEventListener('click', () => { + // Question index starts from 1. + currentQuestionIndex = Math.max(1, currentQuestionIndex - 1); + switchQuestionAndCategory(); +}); + +document.getElementById('next-question').addEventListener('click', () => { + // Question index starts from 1. + currentQuestionIndex = Math.min(questionsCount, currentQuestionIndex + 1); + switchQuestionAndCategory(); +}); + +function updateExpandButtonVisibility(card) { + const cardTextContainer = card.querySelector('.card-text-container'); + const expandBtn = card.querySelector('.expand-btn'); + if (cardTextContainer.scrollHeight > cardTextContainer.offsetHeight) { + expandBtn.style.display = 'flex'; + } else { + expandBtn.style.display = 'none'; + card.classList.add('expanded'); + } +} + +document.querySelectorAll('.expand-btn').forEach(btn => { + btn.addEventListener('click', e => { + const card = e.target.closest('.expandable-card'); + card.classList.toggle('expanded'); + const more = 'keyboard_arrow_down Show more'; + const less = 'keyboard_arrow_up Show less'; + e.target.innerHTML = card.classList.contains('expanded') ? less : more; + }); +}); diff --git a/llava/eval/webpage/styles.css b/llava/eval/webpage/styles.css new file mode 100644 index 0000000000000000000000000000000000000000..7b6d6fc69b336c0a5d103be9fb13a0e0897c76a3 --- /dev/null +++ b/llava/eval/webpage/styles.css @@ -0,0 +1,105 @@ +body { + font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; + background-color: #f8f9fa; +} + +.navbar-dark .navbar-nav .nav-link { + color: #f1cf68; + font-size: 1.1rem; + padding: 0.5rem 0.6rem; +} + +.card-header { + font-weight: bold; +} + +.card { + box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); + transition: 0.3s; +} + +.card:hover { + box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2); +} + +button { + transition: background-color 0.3s; +} + +button:hover { + background-color: #007bff; +} + +@media (max-width: 767px) { + .form-row .form-group { + margin-bottom: 10px; + } +} + +/* Extra styles */ + +.expandable-card .card-text-container { + max-height: 200px; + overflow-y: hidden; + position: relative; +} + +.expandable-card.expanded .card-text-container { + max-height: none; +} + +.expand-btn { + position: relative; + display: none; + background-color: rgba(255, 255, 255, 0.8); + color: #510c75; + border-color: transparent; +} + +.expand-btn:hover { + background-color: rgba(200, 200, 200, 0.8); + text-decoration: none; + border-color: transparent; + color: #510c75; +} + +.expand-btn:focus { + outline: none; + text-decoration: none; +} + +.expandable-card:not(.expanded) .card-text-container:after { + content: ""; + position: absolute; + bottom: 0; + left: 0; + width: 100%; + height: 90px; + background: linear-gradient(rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 1)); +} + +.expandable-card:not(.expanded) .expand-btn { + margin-top: -40px; +} + +.card-body { + padding-bottom: 5px; +} + +.vertical-flex-layout { + justify-content: center; + align-items: center; + height: 100%; + display: flex; + flex-direction: column; + gap: 5px; +} + +.figure-img { + max-width: 100%; + height: auto; +} + +.adjustable-font-size { + font-size: calc(0.5rem + 2vw); +} diff --git a/llava/mm_utils.py b/llava/mm_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8c00c53b96704116593538058e14f590dd26f625 --- /dev/null +++ b/llava/mm_utils.py @@ -0,0 +1,517 @@ +from PIL import Image +from io import BytesIO +import base64 +import torch +import math +import ast + +from transformers import StoppingCriteria +from llava.constants import IMAGE_TOKEN_INDEX + + +def select_best_resolution(original_size, possible_resolutions): + """ + Selects the best resolution from a list of possible resolutions based on the original size. + + Args: + original_size (tuple): The original size of the image in the format (width, height). + possible_resolutions (list): A list of possible resolutions in the format [(width1, height1), (width2, height2), ...]. + + Returns: + tuple: The best fit resolution in the format (width, height). + """ + original_width, original_height = original_size + best_fit = None + max_effective_resolution = 0 + min_wasted_resolution = float('inf') + + for width, height in possible_resolutions: + scale = min(width / original_width, height / original_height) + downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale) + effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height) + wasted_resolution = (width * height) - effective_resolution + + if effective_resolution > max_effective_resolution or (effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution): + max_effective_resolution = effective_resolution + min_wasted_resolution = wasted_resolution + best_fit = (width, height) + + return best_fit + + + +def get_resized_ui_resolution(original_size): + """ + Selects the best resolution from a list of possible resolutions based on the original size. + + Args: + original_size (tuple): The original size of the image in the format (width, height). + possible_resolutions (list): A list of possible resolutions in the format [(width1, height1), (width2, height2), ...]. + + Returns: + tuple: The best fit resolution in the format (width, height). + """ + original_width, original_height = original_size + # best_fit = None + + new_width = nearest_multiple_of_224_at_least_224(original_width,upperbound=26880) + + scale_factor = new_width / original_width + new_height_unpadded = int(original_height * scale_factor) + new_height_padded = nearest_multiple_of_224_at_least_224(new_height_unpadded,ceiling=True) + best_fit=(new_width,new_height_padded) + + return best_fit + + + + + + +def resize_and_pad_image(image, target_resolution): + """ + Resize and pad an image to a target resolution while maintaining aspect ratio. + + Args: + image (PIL.Image.Image): The input image. + target_resolution (tuple): The target resolution (width, height) of the image. + + Returns: + PIL.Image.Image: The resized and padded image. + """ + original_width, original_height = image.size + target_width, target_height = target_resolution + + scale_w = target_width / original_width + scale_h = target_height / original_height + + if scale_w < scale_h: + new_width = target_width + new_height = min(math.ceil(original_height * scale_w), target_height) + else: + new_height = target_height + new_width = min(math.ceil(original_width * scale_h), target_width) + + # Resize the image + resized_image = image.resize((new_width, new_height)) + + new_image = Image.new('RGB', (target_width, target_height), (0, 0, 0)) + paste_x = (target_width - new_width) // 2 + paste_y = (target_height - new_height) // 2 + new_image.paste(resized_image, (paste_x, paste_y)) + + return new_image + + + + +def resize_and_pad_ui_image(img): + """ + Resize and pad an image to a target resolution while maintaining aspect ratio. + + Args: + img (PIL.Image.Image): The input image. + Returns: + PIL.Image.Image: The resized and padded image. + """ + + #TODO: [USE THIS ->->] True training + + orig_width, orig_height = img.size + + # print("DEBUG--- (orig_width, orig_height)", (orig_width, orig_height)) + + # target_width, target_height = target_resolution + + # scale_w = target_width / original_width + # scale_h = target_height / original_height + + new_width = nearest_multiple_of_224_at_least_224(orig_width, upperbound=26880) + + # print("new_width",new_width) + + scale_factor = new_width / orig_width + + new_height_unpadded = min(int(orig_height * scale_factor),26880) + # print("new_height_unpadded", new_height_unpadded) + + img_resized = img.resize((new_width, new_height_unpadded)) + + new_height_padded = nearest_multiple_of_224_at_least_224(new_height_unpadded,ceiling=True,upperbound=268800) + # print("new_height_padded", new_height_padded) + + img_padded = Image.new('RGB', (new_width, new_height_padded), (0, 0, 0)) + img_padded.paste(img_resized, (0, 0)) + + new_size=(new_width,new_height_padded) + + + #TODO [DO NOT USE THIS!!!!] TEST FOR UPPERBOUND square + + # orig_width, orig_height = img.size + # + # # target_width, target_height = target_resolution + # + # # scale_w = target_width / original_width + # # scale_h = target_height / original_height + # + # new_width = 1344 + # + # # print("new_width",new_width) + # + # scale_factor = new_width / orig_width + # + # new_height_unpadded = 1344 + # # print("new_height_unpadded", new_height_unpadded) + # + # img_resized = img.resize((new_width, new_height_unpadded)) + # + # new_height_padded = nearest_multiple_of_224_at_least_224(new_height_unpadded, ceiling=True, upperbound=1344) + # # print("new_height_padded", new_height_padded) + # + # img_padded = Image.new('RGB', (new_width, new_height_padded), (0, 0, 0)) + # img_padded.paste(img_resized, (0, 0)) + # + # new_size = (new_width, new_height_padded) + + # TODO [DO NOT USE THIS!!!!] TEST FOR UPPERBOUND square + + + # + # if scale_w < scale_h: + # new_width = target_width + # new_height = min(math.ceil(original_height * scale_w), target_height) + # else: + # new_height = target_height + # new_width = min(math.ceil(original_width * scale_h), target_width) + + # Resize the image + # resized_image = image.resize((new_width, new_height)) + + # new_image = Image.new('RGB', (target_width, target_height), (0, 0, 0)) + # paste_x = (target_width - new_width) // 2 + # paste_y = (target_height - new_height) // 2 + # new_image.paste(resized_image, (paste_x, paste_y)) + + return img_padded,new_size + + +def resize_and_pad_image_to_top_left(image, target_resolution): + """ + Resize and pad an image to a target resolution while maintaining aspect ratio, + and align the image to the top-left corner of the new image. + + Args: + image (PIL.Image.Image): The input image. + target_resolution (tuple): The target resolution (width, height) of the image. + + Returns: + PIL.Image.Image: The resized and padded image aligned to the top-left corner. + """ + original_width, original_height = image.size + target_width, target_height = target_resolution + + scale_w = target_width / original_width + scale_h = target_height / original_height + + if scale_w < scale_h: + new_width = target_width + new_height = min(math.ceil(original_height * scale_w), target_height) + else: + new_height = target_height + new_width = min(math.ceil(original_width * scale_h), target_width) + + # Resize the image + resized_image = image.resize((new_width, new_height)) + + # Create a new image with a black background + new_image = Image.new('RGB', (target_width, target_height), (0, 0, 0)) + + # Paste the resized image into the new image, aligned to the top-left corner + paste_x = 0 # Align to the left + paste_y = 0 # Align to the top + new_image.paste(resized_image, (paste_x, paste_y)) + + return new_image + + +def divide_to_patches(image, patch_size): + """ + Divides an image into patches of a specified size. + + Args: + image (PIL.Image.Image): The input image. + patch_size (int): The size of each patch. + + Returns: + list: A list of PIL.Image.Image objects representing the patches. + """ + patches = [] + width, height = image.size + for i in range(0, height, patch_size): + for j in range(0, width, patch_size): + box = (j, i, j + patch_size, i + patch_size) + patch = image.crop(box) + patches.append(patch) + + return patches + + +def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size): + """ + Calculate the shape of the image patch grid after the preprocessing for images of any resolution. + + Args: + image_size (tuple): The size of the input image in the format (width, height). + grid_pinpoints (str): A string representation of a list of possible resolutions. + patch_size (int): The size of each image patch. + + Returns: + tuple: The shape of the image patch grid in the format (width, height). + """ + if type(grid_pinpoints) is list: + possible_resolutions = grid_pinpoints + else: + possible_resolutions = ast.literal_eval(grid_pinpoints) + width, height = select_best_resolution(image_size, possible_resolutions) + return width // patch_size, height // patch_size + + + +def get_anyres_image_grid_shape_ui(image_size, patch_size): + """ + Calculate the shape of the image patch grid after the preprocessing for images of any resolution. + + Args: + image_size (tuple): The size of the input image in the format (width, height). + grid_pinpoints (str): A string representation of a list of possible resolutions. + patch_size (int): The size of each image patch. + + Returns: + tuple: The shape of the image patch grid in the format (width, height). + """ + # if type(grid_pinpoints) is list: + # possible_resolutions = grid_pinpoints + # else: + # possible_resolutions = ast.literal_eval(grid_pinpoints) + + width, height = image_size + + + # width, height = get_resized_ui_resolution(image_size) + return width // patch_size, height // patch_size + + +def process_anyres_image(image, processor, grid_pinpoints): + """ + Process an image with variable resolutions. + + Args: + image (PIL.Image.Image): The input image to be processed. + processor: The image processor object. + grid_pinpoints (str): A string representation of a list of possible resolutions. + + Returns: + torch.Tensor: A tensor containing the processed image patches. + """ + if type(grid_pinpoints) is list: + possible_resolutions = grid_pinpoints + else: + possible_resolutions = ast.literal_eval(grid_pinpoints) + best_resolution = select_best_resolution(image.size, possible_resolutions) + image_padded = resize_and_pad_image(image, best_resolution) + + patches = divide_to_patches(image_padded, processor.crop_size['height']) + + image_original_resize = image.resize((processor.size['shortest_edge'], processor.size['shortest_edge'])) + + image_patches = [image_original_resize] + patches + image_patches = [processor.preprocess(image_patch, return_tensors='pt')['pixel_values'][0] + for image_patch in image_patches] + return torch.stack(image_patches, dim=0) + + + + +def nearest_multiple_of_224_at_least_224(num,ceiling=False,upperbound=26880): + if num <= 224: + return 224 + division, remainder = divmod(num, 224) + if ceiling and remainder>0: + return (division + 1) * 224 + + if remainder < 112: + return min(division * 224,upperbound) + else: + return min((division + 1) * 224,upperbound) + + + +def process_anyres_ui_image(image, processor,fusion=False): + """ + Process an image with variable resolutions. + + Args: + image (PIL.Image.Image): The input image to be processed. + processor: The image processor object. + grid_pinpoints (str): A string representation of a list of possible resolutions. + + Returns: + torch.Tensor: A tensor containing the processed image patches. + """ + # if type(grid_pinpoints) is list: + # possible_resolutions = grid_pinpoints + # else: + # # possible_resolutions = ast.literal_eval(grid_pinpoints) + # best_resolution = select_best_resolution(image.size, possible_resolutions) + + + image_padded,new_size = resize_and_pad_ui_image(image) + patches = divide_to_patches(image_padded, 224) + if fusion: + image_original_resize = image.resize((224, 224)) + image_patches = [image_original_resize] + patches + else: + image_patches = patches + # if len(image_patches)==2: + # print(f"\n len image_patches: {len(image_patches)}") + image_patches = [processor.preprocess(image_patch, return_tensors='pt')['pixel_values'][0] + for image_patch in image_patches] + return torch.stack(image_patches, dim=0),new_size + + + +def load_image_from_base64(image): + return Image.open(BytesIO(base64.b64decode(image))) + + +def expand2square(pil_img, background_color): + width, height = pil_img.size + if width == height: + return pil_img + elif width > height: + result = Image.new(pil_img.mode, (width, width), background_color) + result.paste(pil_img, (0, (width - height) // 2)) + return result + else: + result = Image.new(pil_img.mode, (height, height), background_color) + result.paste(pil_img, ((height - width) // 2, 0)) + return result + + +def process_images(images, image_processor, model_cfg): + image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None) + new_images = [] + image_new_size=None + #TODO: FIX THE BUG OF NEW SIZE BATCH + # print("DEBUG image_aspect_ratio: ",image_aspect_ratio) + if image_aspect_ratio == 'pad': + for image in images: + image = expand2square(image, tuple(int(x*255) for x in image_processor.image_mean)) + image = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0] + new_images.append(image) + elif image_aspect_ratio == "anyres": + for image in images: + image,image_new_size = process_anyres_image(image, image_processor, model_cfg.image_grid_pinpoints) + new_images.append(image) + elif image_aspect_ratio == "anyres_ui": + # print("DEBUG---: Process As UI") + for image in images: + image,image_new_size = process_anyres_ui_image(image, image_processor,fusion=False) + new_images.append(image) + elif image_aspect_ratio == "anyres_ui_fusion": + for image in images: + # print("DEBUG---: Process As anyres_ui_fusion") + image,image_new_size = process_anyres_ui_image(image, image_processor,fusion=True) + # if image_new_size is not None: + # print("NEW SIZE", image_new_size) + # else: + # print("NEW SIZE IS NONE!!!!") + new_images.append(image) + else: + print(image_aspect_ratio) + raise NotImplementedError + # return image_processor(images, return_tensors='pt')['pixel_values'] + # print("LEN new_images",len(new_images)) + # if image_new_size is not None: + # print("AFTER: NEW SIZE",image_new_size) + # else: + # print("AFTER: NEW SIZE IS NONE!!!!") + # + # print("TYPE new_images[0]",type(new_images[0])) + # print("len new_images[0]", len(new_images[0])) + # print("new_images[0]", new_images[0]) + if all(x.shape == new_images[0].shape for x in new_images): + new_images = torch.stack(new_images, dim=0) + + if image_new_size is not None: + # print("RETURN WITH NEW SIZE") + return new_images, image_new_size + else: + # print("RETURN ONLY IMAGE") + return new_images + + +def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None): + prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split('')] + + def insert_separator(X, sep): + return [ele for sublist in zip(X, [sep]*len(X)) for ele in sublist][:-1] + + input_ids = [] + offset = 0 + if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id: + offset = 1 + input_ids.append(prompt_chunks[0][0]) + + for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)): + input_ids.extend(x[offset:]) + + if return_tensors is not None: + if return_tensors == 'pt': + return torch.tensor(input_ids, dtype=torch.long) + raise ValueError(f'Unsupported tensor type: {return_tensors}') + return input_ids + + +def get_model_name_from_path(model_path): + model_path = model_path.strip("/") + model_paths = model_path.split("/") + if model_paths[-1].startswith('checkpoint-'): + return model_paths[-2] + "_" + model_paths[-1] + else: + return model_paths[-1] + +class KeywordsStoppingCriteria(StoppingCriteria): + def __init__(self, keywords, tokenizer, input_ids): + self.keywords = keywords + self.keyword_ids = [] + self.max_keyword_len = 0 + for keyword in keywords: + cur_keyword_ids = tokenizer(keyword).input_ids + if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id: + cur_keyword_ids = cur_keyword_ids[1:] + if len(cur_keyword_ids) > self.max_keyword_len: + self.max_keyword_len = len(cur_keyword_ids) + self.keyword_ids.append(torch.tensor(cur_keyword_ids)) + self.tokenizer = tokenizer + self.start_len = input_ids.shape[1] + + def call_for_batch(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: + offset = min(output_ids.shape[1] - self.start_len, self.max_keyword_len) + self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids] + for keyword_id in self.keyword_ids: + truncated_output_ids = output_ids[0, -keyword_id.shape[0]:] + if torch.equal(truncated_output_ids, keyword_id): + return True + outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0] + for keyword in self.keywords: + if keyword in outputs: + return True + return False + + def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: + outputs = [] + for i in range(output_ids.shape[0]): + outputs.append(self.call_for_batch(output_ids[i].unsqueeze(0), scores)) + return all(outputs) diff --git a/llava/model/__init__.py b/llava/model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dbd91789f0cde61dd13a7f9a5f7a69488ad07279 --- /dev/null +++ b/llava/model/__init__.py @@ -0,0 +1,6 @@ +try: + from .language_model.llava_llama import LlavaLlamaForCausalLM, LlavaConfig + from .language_model.llava_mpt import LlavaMptForCausalLM, LlavaMptConfig + from .language_model.llava_mistral import LlavaMistralForCausalLM, LlavaMistralConfig +except: + pass diff --git a/llava/model/__pycache__/__init__.cpython-311.pyc b/llava/model/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39297ecaad27b27f9ac19319c633569a75772d2b Binary files /dev/null and b/llava/model/__pycache__/__init__.cpython-311.pyc differ diff --git a/llava/model/__pycache__/builder.cpython-311.pyc b/llava/model/__pycache__/builder.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d7c5de3d4a3117600c988fd0486aac7b03efcee Binary files /dev/null and b/llava/model/__pycache__/builder.cpython-311.pyc differ diff --git a/llava/model/__pycache__/llava_arch.cpython-311.pyc b/llava/model/__pycache__/llava_arch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df7222e92381300c39ffebc9eebfc1fafa3a93a0 Binary files /dev/null and b/llava/model/__pycache__/llava_arch.cpython-311.pyc differ diff --git a/llava/model/apply_delta.py b/llava/model/apply_delta.py new file mode 100644 index 0000000000000000000000000000000000000000..666dd9691bde7d54ddf2871e311d6f621e29f099 --- /dev/null +++ b/llava/model/apply_delta.py @@ -0,0 +1,48 @@ +""" +Usage: +python3 -m fastchat.model.apply_delta --base ~/model_weights/llama-7b --target ~/model_weights/vicuna-7b --delta lmsys/vicuna-7b-delta +""" +import argparse + +import torch +from tqdm import tqdm +from transformers import AutoTokenizer, AutoModelForCausalLM +from llava import LlavaLlamaForCausalLM + + +def apply_delta(base_model_path, target_model_path, delta_path): + print("Loading base model") + base = AutoModelForCausalLM.from_pretrained( + base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True) + + print("Loading delta") + delta = LlavaLlamaForCausalLM.from_pretrained(delta_path, torch_dtype=torch.float16, low_cpu_mem_usage=True) + delta_tokenizer = AutoTokenizer.from_pretrained(delta_path) + + print("Applying delta") + for name, param in tqdm(delta.state_dict().items(), desc="Applying delta"): + if name not in base.state_dict(): + assert name in ['model.mm_projector.weight', 'model.mm_projector.bias'], f'{name} not in base model' + continue + if param.data.shape == base.state_dict()[name].shape: + param.data += base.state_dict()[name] + else: + assert name in ['model.embed_tokens.weight', 'lm_head.weight'], \ + f'{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}' + bparam = base.state_dict()[name] + param.data[:bparam.shape[0], :bparam.shape[1]] += bparam + + print("Saving target model") + delta.save_pretrained(target_model_path) + delta_tokenizer.save_pretrained(target_model_path) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--base-model-path", type=str, required=True) + parser.add_argument("--target-model-path", type=str, required=True) + parser.add_argument("--delta-path", type=str, required=True) + + args = parser.parse_args() + + apply_delta(args.base_model_path, args.target_model_path, args.delta_path) diff --git a/llava/model/builder.py b/llava/model/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..26fb5932421e35b0f52f56cb6ffd051c951abc37 --- /dev/null +++ b/llava/model/builder.py @@ -0,0 +1,176 @@ +# Copyright 2023 Haotian Liu +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import os +import warnings +import shutil + +from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig +import torch +from llava.model import * +from llava.constants import DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN + + +def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, load_4bit=False, device_map="auto", device="cuda", use_flash_attn=False, **kwargs): + kwargs = {"device_map": device_map, **kwargs} + + if device != "cuda": + kwargs['device_map'] = {"": device} + + if load_8bit: + kwargs['load_in_8bit'] = True + elif load_4bit: + kwargs['load_in_4bit'] = True + kwargs['quantization_config'] = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_compute_dtype=torch.float16, + bnb_4bit_use_double_quant=True, + bnb_4bit_quant_type='nf4' + ) + else: + kwargs['torch_dtype'] = torch.float16 + + if use_flash_attn: + kwargs['attn_implementation'] = 'flash_attention_2' + + # if 'llava' in model_name.lower(): + if True: + # Load LLaVA model + if 'lora' in model_name.lower() and model_base is None: + warnings.warn('There is `lora` in model name but no `model_base` is provided. If you are loading a LoRA model, please provide the `model_base` argument. Detailed instruction: https://github.com/haotian-liu/LLaVA#launch-a-model-worker-lora-weights-unmerged.') + if 'lora' in model_name.lower() and model_base is not None: + from llava.model.language_model.llava_llama import LlavaConfig + lora_cfg_pretrained = LlavaConfig.from_pretrained(model_path) + tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False) + # print('Loading LLaVA from base model...') + model = LlavaLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, **kwargs) + token_num, tokem_dim = model.lm_head.out_features, model.lm_head.in_features + if model.lm_head.weight.shape[0] != token_num: + model.lm_head.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype)) + model.model.embed_tokens.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype)) + + # print('Loading additional LLaVA weights...') + if os.path.exists(os.path.join(model_path, 'non_lora_trainables.bin')): + # print("DEBUG------FOUND non_lora_trainables.bin !!!!!!") + non_lora_trainables = torch.load(os.path.join(model_path, 'non_lora_trainables.bin'), map_location='cpu') + else: + # this is probably from HF Hub + from huggingface_hub import hf_hub_download + def load_from_hf(repo_id, filename, subfolder=None): + cache_file = hf_hub_download( + repo_id=repo_id, + filename=filename, + subfolder=subfolder) + return torch.load(cache_file, map_location='cpu') + non_lora_trainables = load_from_hf(model_path, 'non_lora_trainables.bin') + + names=[k for k,v in non_lora_trainables.items()] + # print("DEBUG----NONE-TRAINABLE: ",names) + non_lora_trainables = {(k[11:] if k.startswith('base_model.') else k): v for k, v in non_lora_trainables.items()} + # print("DEBUG----NONE-TRAINABLE2 non_lora_trainables: ", names) + if any(k.startswith('model.model.') for k in non_lora_trainables): + non_lora_trainables = {(k[6:] if k.startswith('model.') else k): v for k, v in non_lora_trainables.items()} + + # print("DEBUG---- non_lora_trainables ----: ",non_lora_trainables) + model.load_state_dict(non_lora_trainables, strict=False) + + from peft import PeftModel + # print('Loading LoRA weights...') + model = PeftModel.from_pretrained(model, model_path) + # print('Merging LoRA weights...') + model = model.merge_and_unload() + # print('Model is loaded...') + elif model_base is not None: + # this may be mm projector only + # print('Loading LLaVA from base model...') + if 'mpt' in model_name.lower(): + if not os.path.isfile(os.path.join(model_path, 'configuration_mpt.py')): + shutil.copyfile(os.path.join(model_base, 'configuration_mpt.py'), os.path.join(model_path, 'configuration_mpt.py')) + tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=True) + cfg_pretrained = AutoConfig.from_pretrained(model_path, trust_remote_code=True) + model = LlavaMptForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs) + else: + tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False) + cfg_pretrained = AutoConfig.from_pretrained(model_path) + model = LlavaLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs) + + mm_projector_weights = torch.load(os.path.join(model_path, 'mm_projector.bin'), map_location='cpu') + mm_projector_weights = {k: v.to(torch.float16) for k, v in mm_projector_weights.items()} + model.load_state_dict(mm_projector_weights, strict=False) + else: + if 'mpt' in model_name.lower(): + tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True) + model = LlavaMptForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs) + elif 'mistral' in model_name.lower(): + tokenizer = AutoTokenizer.from_pretrained(model_path) + model = LlavaMistralForCausalLM.from_pretrained( + model_path, + low_cpu_mem_usage=True, + **kwargs + ) + else: + tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False) + model = LlavaLlamaForCausalLM.from_pretrained( + model_path, + low_cpu_mem_usage=True, + **kwargs + ) + else: + # Load language model + if model_base is not None: + # PEFT model + from peft import PeftModel + tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False) + model = AutoModelForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, **kwargs) + # print(f"Loading LoRA weights from {model_path}") + model = PeftModel.from_pretrained(model, model_path) + # print(f"Merging weights") + model = model.merge_and_unload() + # print('Convert to FP16...') + model.to(torch.float16) + else: + use_fast = False + if 'mpt' in model_name.lower(): + tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True) + model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, trust_remote_code=True, **kwargs) + else: + tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False) + model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs) + + image_processor = None + + # if 'llava' in model_name.lower(): + if True: + mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False) + mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True) + if mm_use_im_patch_token: + tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True) + if mm_use_im_start_end: + tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True) + model.resize_token_embeddings(len(tokenizer)) + + vision_tower = model.get_vision_tower() + if not vision_tower.is_loaded: + vision_tower.load_model(device_map=device_map) + if device_map != 'auto': + vision_tower.to(device=device_map, dtype=torch.float16) + image_processor = vision_tower.image_processor + + if hasattr(model.config, "max_sequence_length"): + context_len = model.config.max_sequence_length + else: + context_len = 2048 + + return tokenizer, model, image_processor, context_len diff --git a/llava/model/consolidate.py b/llava/model/consolidate.py new file mode 100644 index 0000000000000000000000000000000000000000..1e324210e229eeba23b75791bba82df7c6e639eb --- /dev/null +++ b/llava/model/consolidate.py @@ -0,0 +1,29 @@ +""" +Usage: +python3 -m llava.model.consolidate --src ~/model_weights/llava-7b --dst ~/model_weights/llava-7b_consolidate +""" +import argparse + +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM +from llava.model import * +from llava.model.utils import auto_upgrade + + +def consolidate_ckpt(src_path, dst_path): + print("Loading model") + auto_upgrade(src_path) + src_model = AutoModelForCausalLM.from_pretrained(src_path, torch_dtype=torch.float16, low_cpu_mem_usage=True) + src_tokenizer = AutoTokenizer.from_pretrained(src_path, use_fast=False) + src_model.save_pretrained(dst_path) + src_tokenizer.save_pretrained(dst_path) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--src", type=str, required=True) + parser.add_argument("--dst", type=str, required=True) + + args = parser.parse_args() + + consolidate_ckpt(args.src, args.dst) diff --git a/llava/model/language_model/__pycache__/llava_llama.cpython-311.pyc b/llava/model/language_model/__pycache__/llava_llama.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fac5d5b1980aa55b0a89077ff34b8e3f7dce0950 Binary files /dev/null and b/llava/model/language_model/__pycache__/llava_llama.cpython-311.pyc differ diff --git a/llava/model/language_model/__pycache__/llava_mistral.cpython-311.pyc b/llava/model/language_model/__pycache__/llava_mistral.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60986762102c337c7070f2d447bddc470bce42be Binary files /dev/null and b/llava/model/language_model/__pycache__/llava_mistral.cpython-311.pyc differ diff --git a/llava/model/language_model/__pycache__/llava_mpt.cpython-311.pyc b/llava/model/language_model/__pycache__/llava_mpt.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..960241b24db847054bf78a46f12996e7bac6f5b9 Binary files /dev/null and b/llava/model/language_model/__pycache__/llava_mpt.cpython-311.pyc differ diff --git a/llava/model/language_model/llava_llama.py b/llava/model/language_model/llava_llama.py new file mode 100644 index 0000000000000000000000000000000000000000..069d0d1c10da42f5d278598e8534f166d1f9f5ff --- /dev/null +++ b/llava/model/language_model/llava_llama.py @@ -0,0 +1,158 @@ +# Copyright 2023 Haotian Liu +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from typing import List, Optional, Tuple, Union + +import torch +import torch.nn as nn + +from transformers import AutoConfig, AutoModelForCausalLM, \ + LlamaConfig, LlamaModel, LlamaForCausalLM + +from transformers.modeling_outputs import CausalLMOutputWithPast +from transformers.generation.utils import GenerateOutput + +from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM + + +class LlavaConfig(LlamaConfig): + model_type = "llava_llama" + + +class LlavaLlamaModel(LlavaMetaModel, LlamaModel): + config_class = LlavaConfig + + def __init__(self, config: LlamaConfig): + super(LlavaLlamaModel, self).__init__(config) + + +class LlavaLlamaForCausalLM(LlamaForCausalLM, LlavaMetaForCausalLM): + config_class = LlavaConfig + + def __init__(self, config): + super(LlamaForCausalLM, self).__init__(config) + self.model = LlavaLlamaModel(config) + self.pretraining_tp = config.pretraining_tp + self.vocab_size = config.vocab_size + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_model(self): + return self.model + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + images: Optional[torch.FloatTensor] = None, + image_sizes: Optional[List[List[int]]] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + + if inputs_embeds is None: + ( + input_ids, + position_ids, + attention_mask, + past_key_values, + inputs_embeds, + labels + ) = self.prepare_inputs_labels_for_multimodal( + input_ids, + position_ids, + attention_mask, + past_key_values, + labels, + images, + image_sizes + ) + + return super().forward( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + labels=labels, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict + ) + + @torch.no_grad() + def generate( + self, + inputs: Optional[torch.Tensor] = None, + images: Optional[torch.Tensor] = None, + image_sizes: Optional[torch.Tensor] = None, + **kwargs, + ) -> Union[GenerateOutput, torch.LongTensor]: + position_ids = kwargs.pop("position_ids", None) + attention_mask = kwargs.pop("attention_mask", None) + if "inputs_embeds" in kwargs: + raise NotImplementedError("`inputs_embeds` is not supported") + + if images is not None: + ( + inputs, + position_ids, + attention_mask, + _, + inputs_embeds, + _ + ) = self.prepare_inputs_labels_for_multimodal( + inputs, + position_ids, + attention_mask, + None, + None, + images, + image_sizes=image_sizes + ) + else: + inputs_embeds = self.get_model().embed_tokens(inputs) + + return super().generate( + position_ids=position_ids, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + **kwargs + ) + + def prepare_inputs_for_generation(self, input_ids, past_key_values=None, + inputs_embeds=None, **kwargs): + images = kwargs.pop("images", None) + image_sizes = kwargs.pop("image_sizes", None) + inputs = super().prepare_inputs_for_generation( + input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs + ) + if images is not None: + inputs['images'] = images + if image_sizes is not None: + inputs['image_sizes'] = image_sizes + return inputs + +AutoConfig.register("llava_llama", LlavaConfig) +AutoModelForCausalLM.register(LlavaConfig, LlavaLlamaForCausalLM) diff --git a/llava/model/language_model/llava_mistral.py b/llava/model/language_model/llava_mistral.py new file mode 100644 index 0000000000000000000000000000000000000000..0def682ea3c497e36aa85f1c53eb2cfab6e2fb87 --- /dev/null +++ b/llava/model/language_model/llava_mistral.py @@ -0,0 +1,158 @@ +# Copyright 2023 Haotian Liu +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from typing import List, Optional, Tuple, Union + +import torch +import torch.nn as nn +from torch.nn import CrossEntropyLoss + +from transformers import AutoConfig, AutoModelForCausalLM, \ + MistralConfig, MistralModel, MistralForCausalLM + +from transformers.modeling_outputs import CausalLMOutputWithPast +from transformers.generation.utils import GenerateOutput + +from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM + + +class LlavaMistralConfig(MistralConfig): + model_type = "llava_mistral" + + +class LlavaMistralModel(LlavaMetaModel, MistralModel): + config_class = LlavaMistralConfig + + def __init__(self, config: MistralConfig): + super(LlavaMistralModel, self).__init__(config) + + +class LlavaMistralForCausalLM(MistralForCausalLM, LlavaMetaForCausalLM): + config_class = LlavaMistralConfig + + def __init__(self, config): + super(MistralForCausalLM, self).__init__(config) + self.model = LlavaMistralModel(config) + + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_model(self): + return self.model + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + images: Optional[torch.FloatTensor] = None, + image_sizes: Optional[List[List[int]]] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + + if inputs_embeds is None: + ( + input_ids, + position_ids, + attention_mask, + past_key_values, + inputs_embeds, + labels + ) = self.prepare_inputs_labels_for_multimodal( + input_ids, + position_ids, + attention_mask, + past_key_values, + labels, + images, + image_sizes + ) + + return super().forward( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + labels=labels, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict + ) + + @torch.no_grad() + def generate( + self, + inputs: Optional[torch.Tensor] = None, + images: Optional[torch.Tensor] = None, + image_sizes: Optional[torch.Tensor] = None, + **kwargs, + ) -> Union[GenerateOutput, torch.LongTensor]: + position_ids = kwargs.pop("position_ids", None) + attention_mask = kwargs.pop("attention_mask", None) + if "inputs_embeds" in kwargs: + raise NotImplementedError("`inputs_embeds` is not supported") + + if images is not None: + ( + inputs, + position_ids, + attention_mask, + _, + inputs_embeds, + _ + ) = self.prepare_inputs_labels_for_multimodal( + inputs, + position_ids, + attention_mask, + None, + None, + images, + image_sizes=image_sizes + ) + else: + inputs_embeds = self.get_model().embed_tokens(inputs) + + return super().generate( + position_ids=position_ids, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + **kwargs + ) + + def prepare_inputs_for_generation(self, input_ids, past_key_values=None, + inputs_embeds=None, **kwargs): + images = kwargs.pop("images", None) + image_sizes = kwargs.pop("image_sizes", None) + inputs = super().prepare_inputs_for_generation( + input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs + ) + if images is not None: + inputs['images'] = images + if image_sizes is not None: + inputs['image_sizes'] = image_sizes + return inputs + +AutoConfig.register("llava_mistral", LlavaMistralConfig) +AutoModelForCausalLM.register(LlavaMistralConfig, LlavaMistralForCausalLM) diff --git a/llava/model/language_model/llava_mpt.py b/llava/model/language_model/llava_mpt.py new file mode 100644 index 0000000000000000000000000000000000000000..02e5237ece031af23fcd76b5b4e0d9b0bc5f55cc --- /dev/null +++ b/llava/model/language_model/llava_mpt.py @@ -0,0 +1,97 @@ +# Copyright 2023 Haotian Liu +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from typing import Optional, Tuple + +import torch + +from transformers import AutoConfig, AutoModelForCausalLM, \ + MptConfig, MptForCausalLM, MptModel +from llava.model.llava_arch import LlavaMetaModel, LlavaMetaForCausalLM + + +class LlavaMptConfig(MptConfig): + model_type = "llava_mpt" + + +class LlavaMptModel(LlavaMetaModel, MptModel): + config_class = LlavaMptConfig + + def __init__(self, config: MptConfig): + config.hidden_size = config.d_model + super(LlavaMptModel, self).__init__(config) + + def embed_tokens(self, x): + return self.wte(x) + + +class LlavaMptForCausalLM(MptForCausalLM, LlavaMetaForCausalLM): + config_class = LlavaMptConfig + supports_gradient_checkpointing = True + + def __init__(self, config): + super(MptForCausalLM, self).__init__(config) + + self.transformer = LlavaMptModel(config) + self.lm_head = torch.nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_model(self): + return self.transformer + + def _set_gradient_checkpointing(self, module, value=False): + if isinstance(module, LlavaMptModel): + module.gradient_checkpointing = value + + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None, + attention_mask: Optional[torch.Tensor] = None, + inputs_embeds: Optional[torch.Tensor] = None, + labels: Optional[torch.Tensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + images=None): + + input_ids, attention_mask, past_key_values, inputs_embeds, labels = self.prepare_inputs_labels_for_multimodal(input_ids, attention_mask, past_key_values, labels, images) + + return super().forward( + input_ids, + past_key_values=past_key_values, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + labels=labels, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs): + images = kwargs.pop("images", None) + _inputs = super().prepare_inputs_for_generation( + input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs + ) + _inputs['images'] = images + return _inputs + + +AutoConfig.register("llava_mpt", LlavaMptConfig) +AutoModelForCausalLM.register(LlavaMptConfig, LlavaMptForCausalLM) diff --git a/llava/model/llava_arch.py b/llava/model/llava_arch.py new file mode 100644 index 0000000000000000000000000000000000000000..ca8e956be93821a65ffcb29914af0b8d47445d1f --- /dev/null +++ b/llava/model/llava_arch.py @@ -0,0 +1,413 @@ +# Copyright 2023 Haotian Liu +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from abc import ABC, abstractmethod + +import torch +import torch.nn as nn + +from .multimodal_encoder.builder import build_vision_tower +from .multimodal_projector.builder import build_vision_projector + +from llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN + +from llava.mm_utils import get_anyres_image_grid_shape,get_anyres_image_grid_shape_ui + + +class LlavaMetaModel: + + def __init__(self, config): + super(LlavaMetaModel, self).__init__(config) + + # print("DEBUGGGGG_______patch_merge_type:",getattr(config, 'mm_patch_merge_type', 'spatial')) + # print("DEBUGGGGG_______mm_vision_tower:", getattr(config, 'mm_vision_tower', '')) + + if hasattr(config, "mm_vision_tower"): + self.vision_tower = build_vision_tower(config, delay_load=True) + self.mm_projector = build_vision_projector(config) + + # print("DEBUGGGGG---- mm_patch_merge_type:",getattr(config, 'mm_patch_merge_type', '')) + + if 'unpad' in getattr(config, 'mm_patch_merge_type', 'spatial') or 'spatial' in getattr(config, 'mm_patch_merge_type', 'spatial'): + self.image_newline = nn.Parameter( + torch.empty(config.hidden_size, dtype=self.dtype) + ) + + + def get_vision_tower(self): + vision_tower = getattr(self, 'vision_tower', None) + if type(vision_tower) is list: + vision_tower = vision_tower[0] + return vision_tower + + def initialize_vision_modules(self, model_args, fsdp=None): + vision_tower = model_args.vision_tower + mm_vision_select_layer = model_args.mm_vision_select_layer + mm_vision_select_feature = model_args.mm_vision_select_feature + pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter + mm_patch_merge_type = model_args.mm_patch_merge_type + + self.config.mm_vision_tower = vision_tower + + if self.get_vision_tower() is None: + vision_tower = build_vision_tower(model_args) + + if fsdp is not None and len(fsdp) > 0: + self.vision_tower = [vision_tower] + else: + self.vision_tower = vision_tower + else: + if fsdp is not None and len(fsdp) > 0: + vision_tower = self.vision_tower[0] + else: + vision_tower = self.vision_tower + vision_tower.load_model() + + self.config.use_mm_proj = True + self.config.mm_projector_type = getattr(model_args, 'mm_projector_type', 'linear') + self.config.mm_hidden_size = vision_tower.hidden_size + self.config.mm_vision_select_layer = mm_vision_select_layer + self.config.mm_vision_select_feature = mm_vision_select_feature + self.config.mm_patch_merge_type = mm_patch_merge_type + + if getattr(self, 'mm_projector', None) is None: + self.mm_projector = build_vision_projector(self.config) + + # if 'unpad' in mm_patch_merge_type: + # embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype)) + # self.image_newline = nn.Parameter( + # torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std + # ) + + if 'spatial' in mm_patch_merge_type: + embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype)) + self.image_newline = nn.Parameter( + torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std + ) + else: + # In case it is frozen by LoRA + for p in self.mm_projector.parameters(): + p.requires_grad = True + + if pretrain_mm_mlp_adapter is not None: + mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu') + def get_w(weights, keyword): + return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k} + + self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector')) + + +def unpad_image(tensor, original_size): + """ + Unpads a PyTorch tensor of a padded and resized image. + + Args: + tensor (torch.Tensor): The image tensor, assumed to be in CxHxW format. + original_size (tuple): The original size of the image (height, width). + + Returns: + torch.Tensor: The unpadded image tensor. + """ + original_width, original_height = original_size + current_height, current_width = tensor.shape[1:] + + original_aspect_ratio = original_width / original_height + current_aspect_ratio = current_width / current_height + + if original_aspect_ratio > current_aspect_ratio: + scale_factor = current_width / original_width + new_height = int(original_height * scale_factor) + padding = (current_height - new_height) // 2 + unpadded_tensor = tensor[:, padding:current_height - padding, :] + else: + scale_factor = current_height / original_height + new_width = int(original_width * scale_factor) + padding = (current_width - new_width) // 2 + unpadded_tensor = tensor[:, :, padding:current_width - padding] + + return unpadded_tensor + + +class LlavaMetaForCausalLM(ABC): + + @abstractmethod + def get_model(self): + pass + + def get_vision_tower(self): + return self.get_model().get_vision_tower() + + def encode_images(self, images): + image_features = self.get_model().get_vision_tower()(images) + image_features = self.get_model().mm_projector(image_features) + return image_features + + def prepare_inputs_labels_for_multimodal( + self, input_ids, position_ids, attention_mask, past_key_values, labels, + images, image_sizes=None + ): + vision_tower = self.get_vision_tower() + if vision_tower is None or images is None or input_ids.shape[1] == 1: + return input_ids, position_ids, attention_mask, past_key_values, None, labels + + if type(images) is list or images.ndim == 5: + if type(images) is list: + images = [x.unsqueeze(0) if x.ndim == 3 else x for x in images] + concat_images = torch.cat([image for image in images], dim=0) + image_features = self.encode_images(concat_images) + split_sizes = [image.shape[0] for image in images] + # print(f"DEBUG Split Size: {split_sizes}") + image_features = torch.split(image_features, split_sizes, dim=0) + mm_patch_merge_type = getattr(self.config, 'mm_patch_merge_type', 'spatial') + image_aspect_ratio = getattr(self.config, 'image_aspect_ratio', 'square') + # print(f"DEBUG image_aspect_ratio: {image_aspect_ratio}") + if mm_patch_merge_type == 'flat': + image_features = [x.flatten(0, 1) for x in image_features] + elif mm_patch_merge_type.startswith('spatial'): + new_image_features = [] + for image_idx, image_feature in enumerate(image_features): + # print("\nimage_feature.shape[0]: ", image_feature.shape[0]) + if image_feature.shape[0] > 1 and 'anyres_ui' in image_aspect_ratio: #not only one large patch, i.e. have base and other stuff + if "fusion" in image_aspect_ratio: + # print("DEBUG--FUSION") + base_image_feature = image_feature[0] + image_feature = image_feature[1:] + else: + # print("DEBUG--NO-----FUSION") + base_image_feature=None + # image_feature = image_feature[0:] + + # print("DEBUG______image_feature",image_feature.shape) + height = width = self.get_vision_tower().num_patches_per_side + # assert height * width == base_image_feature[1].shape[0] + if 'anyres_ui' in image_aspect_ratio: + # print("processed size: ", image_sizes[image_idx]) + # print("image_feature.shape[0]: ",image_feature.shape[0]) + # print("image_idx: ",image_idx) + # print("image_feature shape", image_feature.shape) + num_patch_width, num_patch_height = get_anyres_image_grid_shape_ui(image_sizes[image_idx], self.get_vision_tower().config.image_size) + # print("num_patch_width, num_patch_height: ",num_patch_width, num_patch_height) + image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1) + else: + pass + # raise NotImplementedError + # print("DEBUG______image_feature_after_view", image_feature.shape) + if 'unpad' in mm_patch_merge_type: + image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous() + image_feature = image_feature.flatten(1, 2).flatten(2, 3) + image_feature = unpad_image(image_feature, image_sizes[image_idx]) + image_feature = torch.cat(( + image_feature, + self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device) + ), dim=-1) + image_feature = image_feature.flatten(1, 2).transpose(0, 1) + else: + # image_feature = image_feature.permute(0, 2, 1, 3, 4).contiguous() + # image_feature = image_feature.flatten(0, 3) + + image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous() + # print("DEBUG______image_feature_permuted", image_feature.shape) + image_feature = image_feature.flatten(1, 2).flatten(2, 3) + # print("DEBUG______double_flattened", image_feature.shape) + # image_feature = unpad_image(image_feature, image_sizes[image_idx]) + image_feature = torch.cat(( + image_feature, + self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to( + image_feature.device) + ), dim=-1) + image_feature = image_feature.flatten(1, 2).transpose(0, 1) + if base_image_feature is not None: + image_feature = torch.cat((base_image_feature, image_feature), dim=0) + # else: + else: #only one image patch + # print("GOT INTO ONE BLOCK-----DEBUG") + image_feature = image_feature[0] + if 'unpad' in mm_patch_merge_type: + image_feature = torch.cat(( + image_feature, + self.model.image_newline[None].to(image_feature.device) + ), dim=0) + new_image_features.append(image_feature) + image_features = new_image_features + else: + raise ValueError(f"Unexpected mm_patch_merge_type: {self.config.mm_patch_merge_type}") + else: + image_features = self.encode_images(images) + + # TODO: image start / end is not implemented here to support pretraining. + if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False): + raise NotImplementedError + + # Let's just add dummy tensors if they do not exist, + # it is a headache to deal with None all the time. + # But it is not ideal, and if you have a better idea, + # please open an issue / submit a PR, thanks. + _labels = labels + _position_ids = position_ids + _attention_mask = attention_mask + if attention_mask is None: + attention_mask = torch.ones_like(input_ids, dtype=torch.bool) + else: + attention_mask = attention_mask.bool() + if position_ids is None: + position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device) + if labels is None: + labels = torch.full_like(input_ids, IGNORE_INDEX) + + # remove the padding using attention_mask -- FIXME + _input_ids = input_ids + input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)] + labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)] + + new_input_embeds = [] + new_labels = [] + cur_image_idx = 0 + for batch_idx, cur_input_ids in enumerate(input_ids): + num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum() + if num_images == 0: + cur_image_features = image_features[cur_image_idx] + cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids) + cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0) + new_input_embeds.append(cur_input_embeds) + new_labels.append(labels[batch_idx]) + cur_image_idx += 1 + continue + + image_token_indices = [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]] + cur_input_ids_noim = [] + cur_labels = labels[batch_idx] + cur_labels_noim = [] + for i in range(len(image_token_indices) - 1): + cur_input_ids_noim.append(cur_input_ids[image_token_indices[i]+1:image_token_indices[i+1]]) + cur_labels_noim.append(cur_labels[image_token_indices[i]+1:image_token_indices[i+1]]) + split_sizes = [x.shape[0] for x in cur_labels_noim] + cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim)) + cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0) + cur_new_input_embeds = [] + cur_new_labels = [] + + for i in range(num_images + 1): + cur_new_input_embeds.append(cur_input_embeds_no_im[i]) + cur_new_labels.append(cur_labels_noim[i]) + if i < num_images: + cur_image_features = image_features[cur_image_idx] + cur_image_idx += 1 + cur_new_input_embeds.append(cur_image_features) + cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype)) + + cur_new_input_embeds = [x.to(self.device) for x in cur_new_input_embeds] + + cur_new_input_embeds = torch.cat(cur_new_input_embeds) + cur_new_labels = torch.cat(cur_new_labels) + + new_input_embeds.append(cur_new_input_embeds) + new_labels.append(cur_new_labels) + + # Truncate sequences to max length as image embeddings can make the sequence longer + tokenizer_model_max_length = getattr(self.config, 'tokenizer_model_max_length', None) + if tokenizer_model_max_length is not None: + new_input_embeds = [x[:tokenizer_model_max_length] for x in new_input_embeds] + new_labels = [x[:tokenizer_model_max_length] for x in new_labels] + + # Combine them + max_len = max(x.shape[0] for x in new_input_embeds) + batch_size = len(new_input_embeds) + + new_input_embeds_padded = [] + new_labels_padded = torch.full((batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device) + attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device) + position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device) + + for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)): + cur_len = cur_new_embed.shape[0] + if getattr(self.config, 'tokenizer_padding_side', 'right') == "left": + new_input_embeds_padded.append(torch.cat(( + torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device), + cur_new_embed + ), dim=0)) + if cur_len > 0: + new_labels_padded[i, -cur_len:] = cur_new_labels + attention_mask[i, -cur_len:] = True + position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device) + else: + new_input_embeds_padded.append(torch.cat(( + cur_new_embed, + torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device) + ), dim=0)) + if cur_len > 0: + new_labels_padded[i, :cur_len] = cur_new_labels + attention_mask[i, :cur_len] = True + position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device) + + new_input_embeds = torch.stack(new_input_embeds_padded, dim=0) + + if _labels is None: + new_labels = None + else: + new_labels = new_labels_padded + + if _attention_mask is None: + attention_mask = None + else: + attention_mask = attention_mask.to(dtype=_attention_mask.dtype) + + if _position_ids is None: + position_ids = None + + return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels + + def initialize_vision_tokenizer(self, model_args, tokenizer): + if model_args.mm_use_im_patch_token: + tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True) + self.resize_token_embeddings(len(tokenizer)) + + if model_args.mm_use_im_start_end: + num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True) + self.resize_token_embeddings(len(tokenizer)) + + if num_new_tokens > 0: + input_embeddings = self.get_input_embeddings().weight.data + output_embeddings = self.get_output_embeddings().weight.data + + input_embeddings_avg = input_embeddings[:-num_new_tokens].mean( + dim=0, keepdim=True) + output_embeddings_avg = output_embeddings[:-num_new_tokens].mean( + dim=0, keepdim=True) + + input_embeddings[-num_new_tokens:] = input_embeddings_avg + output_embeddings[-num_new_tokens:] = output_embeddings_avg + + if model_args.tune_mm_mlp_adapter: + for p in self.get_input_embeddings().parameters(): + p.requires_grad = True + for p in self.get_output_embeddings().parameters(): + p.requires_grad = False + + if model_args.pretrain_mm_mlp_adapter: + mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location='cpu') + embed_tokens_weight = mm_projector_weights['model.embed_tokens.weight'] + assert num_new_tokens == 2 + if input_embeddings.shape == embed_tokens_weight.shape: + input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:] + elif embed_tokens_weight.shape[0] == num_new_tokens: + input_embeddings[-num_new_tokens:] = embed_tokens_weight + else: + raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.") + elif model_args.mm_use_im_patch_token: + if model_args.tune_mm_mlp_adapter: + for p in self.get_input_embeddings().parameters(): + p.requires_grad = False + for p in self.get_output_embeddings().parameters(): + p.requires_grad = False diff --git a/llava/model/make_delta.py b/llava/model/make_delta.py new file mode 100644 index 0000000000000000000000000000000000000000..4ae55d59c2c8bab80299272314a41bbeb959d8ed --- /dev/null +++ b/llava/model/make_delta.py @@ -0,0 +1,52 @@ +""" +Usage: +python3 -m llava.model.make_delta --base ~/model_weights/llama-7b --target ~/model_weights/llava-7b --delta ~/model_weights/llava-7b-delta --hub-repo-id liuhaotian/llava-7b-delta +""" +import argparse + +import torch +from tqdm import tqdm +from transformers import AutoTokenizer, AutoModelForCausalLM +from llava.model.utils import auto_upgrade + + +def make_delta(base_model_path, target_model_path, delta_path, hub_repo_id): + print("Loading base model") + base = AutoModelForCausalLM.from_pretrained( + base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True) + + print("Loading target model") + auto_upgrade(target_model_path) + target = AutoModelForCausalLM.from_pretrained(target_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True) + + print("Calculating delta") + for name, param in tqdm(target.state_dict().items(), desc="Calculating delta"): + if name not in base.state_dict(): + assert name in ['model.mm_projector.weight', 'model.mm_projector.bias'], f'{name} not in base model' + continue + if param.data.shape == base.state_dict()[name].shape: + param.data -= base.state_dict()[name] + else: + assert name in ['model.embed_tokens.weight', 'lm_head.weight'], f'{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}' + bparam = base.state_dict()[name] + param.data[:bparam.shape[0], :bparam.shape[1]] -= bparam + + print("Saving delta") + if hub_repo_id: + kwargs = {"push_to_hub": True, "repo_id": hub_repo_id} + else: + kwargs = {} + target.save_pretrained(delta_path, **kwargs) + target_tokenizer = AutoTokenizer.from_pretrained(target_model_path) + target_tokenizer.save_pretrained(delta_path, **kwargs) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--base-model-path", type=str, required=True) + parser.add_argument("--target-model-path", type=str, required=True) + parser.add_argument("--delta-path", type=str, required=True) + parser.add_argument("--hub-repo-id", type=str, default=None) + args = parser.parse_args() + + make_delta(args.base_model_path, args.target_model_path, args.delta_path, args.hub_repo_id) diff --git a/llava/model/multimodal_encoder/__pycache__/builder.cpython-311.pyc b/llava/model/multimodal_encoder/__pycache__/builder.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..034a8266a2b79ae69ccbf5770a8c950485c9b1d6 Binary files /dev/null and b/llava/model/multimodal_encoder/__pycache__/builder.cpython-311.pyc differ diff --git a/llava/model/multimodal_encoder/__pycache__/clip_encoder.cpython-311.pyc b/llava/model/multimodal_encoder/__pycache__/clip_encoder.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fe7162ba0524d5d6e6d459dd1ec7a451dbf3478 Binary files /dev/null and b/llava/model/multimodal_encoder/__pycache__/clip_encoder.cpython-311.pyc differ diff --git a/llava/model/multimodal_encoder/builder.py b/llava/model/multimodal_encoder/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..e89507c49df413945453959d48b51a71b9031ef7 --- /dev/null +++ b/llava/model/multimodal_encoder/builder.py @@ -0,0 +1,11 @@ +import os +from .clip_encoder import CLIPVisionTower + + +def build_vision_tower(vision_tower_cfg, **kwargs): + vision_tower = getattr(vision_tower_cfg, 'mm_vision_tower', getattr(vision_tower_cfg, 'vision_tower', None)) + is_absolute_path_exists = os.path.exists(vision_tower) + if is_absolute_path_exists or vision_tower.startswith("openai") or vision_tower.startswith("laion") or "ShareGPT4V" in vision_tower: + return CLIPVisionTower(vision_tower, args=vision_tower_cfg, **kwargs) + + raise ValueError(f'Unknown vision tower: {vision_tower}') diff --git a/llava/model/multimodal_encoder/clip_encoder.py b/llava/model/multimodal_encoder/clip_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..97dbea3dee79b06ed163f9d85f174753a1237572 --- /dev/null +++ b/llava/model/multimodal_encoder/clip_encoder.py @@ -0,0 +1,88 @@ +import torch +import torch.nn as nn + +from transformers import CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig + + +class CLIPVisionTower(nn.Module): + def __init__(self, vision_tower, args, delay_load=False): + super().__init__() + + self.is_loaded = False + + self.vision_tower_name = vision_tower + self.select_layer = args.mm_vision_select_layer + self.select_feature = getattr(args, 'mm_vision_select_feature', 'patch') + + if not delay_load: + self.load_model() + elif getattr(args, 'unfreeze_mm_vision_tower', False): + self.load_model() + else: + self.cfg_only = CLIPVisionConfig.from_pretrained(self.vision_tower_name) + + def load_model(self, device_map=None): + if self.is_loaded: + print('{} is already loaded, `load_model` called again, skipping.'.format(self.vision_tower_name)) + return + + self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name) + self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name, device_map=device_map) + self.vision_tower.requires_grad_(False) + + self.is_loaded = True + + def feature_select(self, image_forward_outs): + image_features = image_forward_outs.hidden_states[self.select_layer] + if self.select_feature == 'patch': + image_features = image_features[:, 1:] + elif self.select_feature == 'cls_patch': + image_features = image_features + else: + raise ValueError(f'Unexpected select feature: {self.select_feature}') + return image_features + + @torch.no_grad() + def forward(self, images): + if type(images) is list: + image_features = [] + for image in images: + image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True) + image_feature = self.feature_select(image_forward_out).to(image.dtype) + image_features.append(image_feature) + else: + image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True) + image_features = self.feature_select(image_forward_outs).to(images.dtype) + + return image_features + + @property + def dummy_feature(self): + return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype) + + @property + def dtype(self): + return self.vision_tower.dtype + + @property + def device(self): + return self.vision_tower.device + + @property + def config(self): + if self.is_loaded: + return self.vision_tower.config + else: + return self.cfg_only + + @property + def hidden_size(self): + return self.config.hidden_size + + @property + def num_patches_per_side(self): + return self.config.image_size // self.config.patch_size + + @property + def num_patches(self): + return (self.config.image_size // self.config.patch_size) ** 2 diff --git a/llava/model/multimodal_projector/__pycache__/builder.cpython-311.pyc b/llava/model/multimodal_projector/__pycache__/builder.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa05fed9866daaa036b2540a87a4f29d13024fcc Binary files /dev/null and b/llava/model/multimodal_projector/__pycache__/builder.cpython-311.pyc differ diff --git a/llava/model/multimodal_projector/builder.py b/llava/model/multimodal_projector/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..31cd4f48e6055cd6d00a162af30b1c8139e26b57 --- /dev/null +++ b/llava/model/multimodal_projector/builder.py @@ -0,0 +1,51 @@ +import torch +import torch.nn as nn +import re + + +class IdentityMap(nn.Module): + def __init__(self): + super().__init__() + + def forward(self, x, *args, **kwargs): + return x + + @property + def config(self): + return {"mm_projector_type": 'identity'} + + +class SimpleResBlock(nn.Module): + def __init__(self, channels): + super().__init__() + self.pre_norm = nn.LayerNorm(channels) + + self.proj = nn.Sequential( + nn.Linear(channels, channels), + nn.GELU(), + nn.Linear(channels, channels) + ) + def forward(self, x): + x = self.pre_norm(x) + return x + self.proj(x) + + +def build_vision_projector(config, delay_load=False, **kwargs): + projector_type = getattr(config, 'mm_projector_type', 'linear') + + if projector_type == 'linear': + return nn.Linear(config.mm_hidden_size, config.hidden_size) + + mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu$', projector_type) + if mlp_gelu_match: + mlp_depth = int(mlp_gelu_match.group(1)) + modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)] + for _ in range(1, mlp_depth): + modules.append(nn.GELU()) + modules.append(nn.Linear(config.hidden_size, config.hidden_size)) + return nn.Sequential(*modules) + + if projector_type == 'identity': + return IdentityMap() + + raise ValueError(f'Unknown projector type: {projector_type}') diff --git a/llava/model/utils.py b/llava/model/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6fc27c4fde7b707bf2ecb53680e981fef8ba1d1c --- /dev/null +++ b/llava/model/utils.py @@ -0,0 +1,20 @@ +from transformers import AutoConfig + + +def auto_upgrade(config): + cfg = AutoConfig.from_pretrained(config) + if True and 'llava' not in cfg.model_type: + assert cfg.model_type == 'llama' + print("You are using newer LLaVA code base, while the checkpoint of v0 is from older code base.") + print("You must upgrade the checkpoint to the new code base (this can be done automatically).") + confirm = input("Please confirm that you want to upgrade the checkpoint. [Y/N]") + if confirm.lower() in ["y", "yes"]: + print("Upgrading checkpoint...") + assert len(cfg.architectures) == 1 + setattr(cfg.__class__, "model_type", "llava") + cfg.architectures[0] = 'LlavaLlamaForCausalLM' + cfg.save_pretrained(config) + print("Checkpoint upgraded.") + else: + print("Checkpoint upgrade aborted.") + exit(1) diff --git a/llava/serve/__init__.py b/llava/serve/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/llava/serve/__pycache__/__init__.cpython-311.pyc b/llava/serve/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d74008a1417c1ff949f4b60d744f80f9040caf4d Binary files /dev/null and b/llava/serve/__pycache__/__init__.cpython-311.pyc differ diff --git a/llava/serve/__pycache__/controller.cpython-311.pyc b/llava/serve/__pycache__/controller.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ee257222065537f6c0e9037794920b9bba057da Binary files /dev/null and b/llava/serve/__pycache__/controller.cpython-311.pyc differ diff --git a/llava/serve/__pycache__/gradio_web_server.cpython-311.pyc b/llava/serve/__pycache__/gradio_web_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cea21d3c1a06136173d3362b32abe8b869962b58 Binary files /dev/null and b/llava/serve/__pycache__/gradio_web_server.cpython-311.pyc differ diff --git a/llava/serve/__pycache__/model_worker.cpython-311.pyc b/llava/serve/__pycache__/model_worker.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fef7b0f7a671852ed58e17b7ef98e159d29384fc Binary files /dev/null and b/llava/serve/__pycache__/model_worker.cpython-311.pyc differ diff --git a/llava/serve/cli.py b/llava/serve/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..4cfcd7e39551291da90c2b924ba78fc64e57b594 --- /dev/null +++ b/llava/serve/cli.py @@ -0,0 +1,131 @@ +import argparse +import torch + +from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from llava.conversation import conv_templates, SeparatorStyle +from llava.model.builder import load_pretrained_model +from llava.utils import disable_torch_init +from llava.mm_utils import process_images, tokenizer_image_token, get_model_name_from_path + +from PIL import Image + +import requests +from PIL import Image +from io import BytesIO +from transformers import TextStreamer + + +def load_image(image_file): + if image_file.startswith('http://') or image_file.startswith('https://'): + response = requests.get(image_file) + image = Image.open(BytesIO(response.content)).convert('RGB') + else: + image = Image.open(image_file).convert('RGB') + return image + + +def main(args): + # Model + disable_torch_init() + + model_name = get_model_name_from_path(args.model_path) + tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit, device=args.device) + + if "llama-2" in model_name.lower(): + conv_mode = "llava_llama_2" + elif "mistral" in model_name.lower(): + conv_mode = "mistral_instruct" + elif "v1.6-34b" in model_name.lower(): + conv_mode = "chatml_direct" + elif "v1" in model_name.lower(): + conv_mode = "llava_v1" + elif "mpt" in model_name.lower(): + conv_mode = "mpt" + else: + conv_mode = "llava_v0" + + if args.conv_mode is not None and conv_mode != args.conv_mode: + print('[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}'.format(conv_mode, args.conv_mode, args.conv_mode)) + else: + args.conv_mode = conv_mode + + conv = conv_templates[args.conv_mode].copy() + if "mpt" in model_name.lower(): + roles = ('user', 'assistant') + else: + roles = conv.roles + + image = load_image(args.image_file) + + + # Similar operation in model_worker.py + print(model.config) + image_tensor,image_size = process_images([image], image_processor, model.config) + # image_size = image.size + if type(image_tensor) is list: + image_tensor = [image.to(model.device, dtype=torch.float16) for image in image_tensor] + else: + image_tensor = image_tensor.to(model.device, dtype=torch.float16) + + while True: + try: + inp = input(f"{roles[0]}: ") + except EOFError: + inp = "" + if not inp: + print("exit...") + break + + print(f"{roles[1]}: ", end="") + + if image is not None: + # first message + if model.config.mm_use_im_start_end: + inp = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + inp + else: + inp = DEFAULT_IMAGE_TOKEN + '\n' + inp + conv.append_message(conv.roles[0], inp) + image = None + else: + # later messages + conv.append_message(conv.roles[0], inp) + conv.append_message(conv.roles[1], None) + prompt = conv.get_prompt() + + input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(model.device) + stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2 + keywords = [stop_str] + streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True) + + with torch.inference_mode(): + output_ids = model.generate( + input_ids, + images=image_tensor, + image_sizes=[image_size], + do_sample=True if args.temperature > 0 else False, + temperature=args.temperature, + max_new_tokens=args.max_new_tokens, + streamer=streamer, + use_cache=True) + + outputs = tokenizer.decode(output_ids[0]).strip() + conv.messages[-1][-1] = outputs + + if args.debug: + print("\n", {"prompt": prompt, "outputs": outputs}, "\n") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--model-path", type=str, default="facebook/opt-350m") + parser.add_argument("--model-base", type=str, default=None) + parser.add_argument("--image-file", type=str, required=True) + parser.add_argument("--device", type=str, default="cuda") + parser.add_argument("--conv-mode", type=str, default=None) + parser.add_argument("--temperature", type=float, default=0.2) + parser.add_argument("--max-new-tokens", type=int, default=512) + parser.add_argument("--load-8bit", action="store_true") + parser.add_argument("--load-4bit", action="store_true") + parser.add_argument("--debug", action="store_true") + args = parser.parse_args() + main(args) diff --git a/llava/serve/controller.py b/llava/serve/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..d4bf1b4c47ccdb1401b18f8397868ec016d1c43a --- /dev/null +++ b/llava/serve/controller.py @@ -0,0 +1,298 @@ +""" +A controller manages distributed workers. +It sends worker addresses to clients. +""" +import argparse +import asyncio +import dataclasses +from enum import Enum, auto +import json +import logging +import time +from typing import List, Union +import threading + +from fastapi import FastAPI, Request +from fastapi.responses import StreamingResponse +import numpy as np +import requests +import uvicorn + +from llava.constants import CONTROLLER_HEART_BEAT_EXPIRATION +from llava.utils import build_logger, server_error_msg + + +logger = build_logger("controller", "controller.log") + + +class DispatchMethod(Enum): + LOTTERY = auto() + SHORTEST_QUEUE = auto() + + @classmethod + def from_str(cls, name): + if name == "lottery": + return cls.LOTTERY + elif name == "shortest_queue": + return cls.SHORTEST_QUEUE + else: + raise ValueError(f"Invalid dispatch method") + + +@dataclasses.dataclass +class WorkerInfo: + model_names: List[str] + speed: int + queue_length: int + check_heart_beat: bool + last_heart_beat: str + + +def heart_beat_controller(controller): + while True: + time.sleep(CONTROLLER_HEART_BEAT_EXPIRATION) + controller.remove_stable_workers_by_expiration() + + +class Controller: + def __init__(self, dispatch_method: str): + # Dict[str -> WorkerInfo] + self.worker_info = {} + self.dispatch_method = DispatchMethod.from_str(dispatch_method) + + self.heart_beat_thread = threading.Thread( + target=heart_beat_controller, args=(self,), daemon=True) + self.heart_beat_thread.start() + + logger.info("Init controller") + + def register_worker(self, worker_name: str, check_heart_beat: bool, + worker_status: dict): + if worker_name not in self.worker_info: + logger.info(f"Register a new worker: {worker_name}") + else: + logger.info(f"Register an existing worker: {worker_name}") + + if not worker_status: + worker_status = self.get_worker_status(worker_name) + if not worker_status: + return False + + self.worker_info[worker_name] = WorkerInfo( + worker_status["model_names"], worker_status["speed"], worker_status["queue_length"], + check_heart_beat, time.time()) + + logger.info(f"Register done: {worker_name}, {worker_status}") + return True + + def get_worker_status(self, worker_name: str): + try: + r = requests.post(worker_name + "/worker_get_status", timeout=5) + except requests.exceptions.RequestException as e: + logger.error(f"Get status fails: {worker_name}, {e}") + return None + + if r.status_code != 200: + logger.error(f"Get status fails: {worker_name}, {r}") + return None + + return r.json() + + def remove_worker(self, worker_name: str): + del self.worker_info[worker_name] + + def refresh_all_workers(self): + old_info = dict(self.worker_info) + self.worker_info = {} + + for w_name, w_info in old_info.items(): + if not self.register_worker(w_name, w_info.check_heart_beat, None): + logger.info(f"Remove stale worker: {w_name}") + + def list_models(self): + model_names = set() + + for w_name, w_info in self.worker_info.items(): + model_names.update(w_info.model_names) + + return list(model_names) + + def get_worker_address(self, model_name: str): + if self.dispatch_method == DispatchMethod.LOTTERY: + worker_names = [] + worker_speeds = [] + for w_name, w_info in self.worker_info.items(): + if model_name in w_info.model_names: + worker_names.append(w_name) + worker_speeds.append(w_info.speed) + worker_speeds = np.array(worker_speeds, dtype=np.float32) + norm = np.sum(worker_speeds) + if norm < 1e-4: + return "" + worker_speeds = worker_speeds / norm + if True: # Directly return address + pt = np.random.choice(np.arange(len(worker_names)), + p=worker_speeds) + worker_name = worker_names[pt] + return worker_name + + # Check status before returning + while True: + pt = np.random.choice(np.arange(len(worker_names)), + p=worker_speeds) + worker_name = worker_names[pt] + + if self.get_worker_status(worker_name): + break + else: + self.remove_worker(worker_name) + worker_speeds[pt] = 0 + norm = np.sum(worker_speeds) + if norm < 1e-4: + return "" + worker_speeds = worker_speeds / norm + continue + return worker_name + elif self.dispatch_method == DispatchMethod.SHORTEST_QUEUE: + worker_names = [] + worker_qlen = [] + for w_name, w_info in self.worker_info.items(): + if model_name in w_info.model_names: + worker_names.append(w_name) + worker_qlen.append(w_info.queue_length / w_info.speed) + if len(worker_names) == 0: + return "" + min_index = np.argmin(worker_qlen) + w_name = worker_names[min_index] + self.worker_info[w_name].queue_length += 1 + logger.info(f"names: {worker_names}, queue_lens: {worker_qlen}, ret: {w_name}") + return w_name + else: + raise ValueError(f"Invalid dispatch method: {self.dispatch_method}") + + def receive_heart_beat(self, worker_name: str, queue_length: int): + if worker_name not in self.worker_info: + logger.info(f"Receive unknown heart beat. {worker_name}") + return False + + self.worker_info[worker_name].queue_length = queue_length + self.worker_info[worker_name].last_heart_beat = time.time() + logger.info(f"Receive heart beat. {worker_name}") + return True + + def remove_stable_workers_by_expiration(self): + expire = time.time() - CONTROLLER_HEART_BEAT_EXPIRATION + to_delete = [] + for worker_name, w_info in self.worker_info.items(): + if w_info.check_heart_beat and w_info.last_heart_beat < expire: + to_delete.append(worker_name) + + for worker_name in to_delete: + self.remove_worker(worker_name) + + def worker_api_generate_stream(self, params): + worker_addr = self.get_worker_address(params["model"]) + if not worker_addr: + logger.info(f"no worker: {params['model']}") + ret = { + "text": server_error_msg, + "error_code": 2, + } + yield json.dumps(ret).encode() + b"\0" + + try: + response = requests.post(worker_addr + "/worker_generate_stream", + json=params, stream=True, timeout=5) + for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"): + if chunk: + yield chunk + b"\0" + except requests.exceptions.RequestException as e: + logger.info(f"worker timeout: {worker_addr}") + ret = { + "text": server_error_msg, + "error_code": 3, + } + yield json.dumps(ret).encode() + b"\0" + + + # Let the controller act as a worker to achieve hierarchical + # management. This can be used to connect isolated sub networks. + def worker_api_get_status(self): + model_names = set() + speed = 0 + queue_length = 0 + + for w_name in self.worker_info: + worker_status = self.get_worker_status(w_name) + if worker_status is not None: + model_names.update(worker_status["model_names"]) + speed += worker_status["speed"] + queue_length += worker_status["queue_length"] + + return { + "model_names": list(model_names), + "speed": speed, + "queue_length": queue_length, + } + + +app = FastAPI() + + +@app.post("/register_worker") +async def register_worker(request: Request): + data = await request.json() + controller.register_worker( + data["worker_name"], data["check_heart_beat"], + data.get("worker_status", None)) + + +@app.post("/refresh_all_workers") +async def refresh_all_workers(): + models = controller.refresh_all_workers() + + +@app.post("/list_models") +async def list_models(): + models = controller.list_models() + return {"models": models} + + +@app.post("/get_worker_address") +async def get_worker_address(request: Request): + data = await request.json() + addr = controller.get_worker_address(data["model"]) + return {"address": addr} + + +@app.post("/receive_heart_beat") +async def receive_heart_beat(request: Request): + data = await request.json() + exist = controller.receive_heart_beat( + data["worker_name"], data["queue_length"]) + return {"exist": exist} + + +@app.post("/worker_generate_stream") +async def worker_api_generate_stream(request: Request): + params = await request.json() + generator = controller.worker_api_generate_stream(params) + return StreamingResponse(generator) + + +@app.post("/worker_get_status") +async def worker_api_get_status(request: Request): + return controller.worker_api_get_status() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--host", type=str, default="localhost") + parser.add_argument("--port", type=int, default=21001) + parser.add_argument("--dispatch-method", type=str, choices=[ + "lottery", "shortest_queue"], default="shortest_queue") + args = parser.parse_args() + logger.info(f"args: {args}") + + controller = Controller(args.dispatch_method) + uvicorn.run(app, host=args.host, port=args.port, log_level="info") diff --git a/llava/serve/examples/extreme_ironing.jpg b/llava/serve/examples/extreme_ironing.jpg new file mode 100644 index 0000000000000000000000000000000000000000..638b078837f175039b2db49a63821288d9681daa Binary files /dev/null and b/llava/serve/examples/extreme_ironing.jpg differ diff --git a/llava/serve/examples/waterview.jpg b/llava/serve/examples/waterview.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6f44ebaba1aa493b8bab3baa4e827b76752b1869 Binary files /dev/null and b/llava/serve/examples/waterview.jpg differ diff --git a/llava/serve/gradio_web_server.py b/llava/serve/gradio_web_server.py new file mode 100644 index 0000000000000000000000000000000000000000..56e3fe5fae9bd8e139bbeb999c4ed4d48fad9ec4 --- /dev/null +++ b/llava/serve/gradio_web_server.py @@ -0,0 +1,602 @@ +import argparse +import datetime +import json +import os +import time + +import gradio as gr +import requests + +from llava.conversation import (default_conversation, conv_templates, + SeparatorStyle) +from llava.constants import LOGDIR +from llava.utils import (build_logger, server_error_msg, + violates_moderation, moderation_msg) +import hashlib + + +logger = build_logger("gradio_web_server", "gradio_web_server.log") + +headers = {"User-Agent": "UGround Client"} + +no_change_btn = gr.Button() +enable_btn = gr.Button(interactive=True) +disable_btn = gr.Button(interactive=False) + +priority = { + "vicuna-13b": "aaaaaaa", + "koala-13b": "aaaaaab", +} +from PIL import Image +import io +import base64 + +def resize_image(image, default_width=(1344, 896), request_width=None): + # 如果 request 中指定了 width,则使用传入的值 + if request_width: + default_width = request_width + + original_width, original_height = image.size + + print(original_width,original_height) + + # 根据宽高比决定 resize 逻辑 + if original_width >= original_height: + # 根据 width 的值进行 resize + new_width = default_width[0] + resize_scale = new_width / original_width + new_height = round(original_height * resize_scale) + else: + # 根据 width 的值进行 resize + new_width = default_width[1] + resize_scale = new_width / original_width + new_height = round(original_height * resize_scale) + + # 调整图像大小 + resized_image = image.resize((new_width, new_height)) + print(new_width,new_height) + return resized_image + + +from PIL import Image, ImageDraw + + +def draw_circle_on_image(image, x, y, radius=10, color=(255, 0, 0)): + """ + 在给定的图片上绘制一个红色圆圈,并返回新的图片。如果 x, y 坐标不在图片范围内, + 并且 y 超出了图片高度,则尝试将 y 减去 224;如果调整后的 y 仍然超出范围,则返回原图。 + + 参数: + - image: 传入的 PIL.Image 对象 + - x, y: 圆心的绝对坐标 + - radius: 圆圈的半径,默认为 10 + - color: 圆圈的颜色,默认为红色 (255, 0, 0) + + 返回: + - 带有红色圆圈的 PIL.Image 对象,或者在坐标不合法时返回原图。 + """ + # 获取图片的宽度和高度 + img_width, img_height = image.size + + # 判断 x 坐标是否在图片范围内 + if not (0 <= x <= img_width): + print(f"x 坐标 {x} 不在图片宽度范围内,直接返回原图。") + return image + + # 判断 y 坐标是否在图片范围内 + if not (0 <= y <= img_height): + print(f"y 坐标 {y} 超出了图片高度范围,尝试减去 224。") + y -= 224 + # 如果调整后的 y 坐标仍然超出范围,返回原图 + if not (0 <= y <= img_height): + print(f"调整后的 y 坐标 {y} 仍然超出了图片范围,直接返回原图。") + return image + + # 创建一个可以在图片上绘制的对象 + draw = ImageDraw.Draw(image) + + # 定义圆圈的外接矩形框 + left_up_point = (x - radius, y - radius) + right_down_point = (x + radius, y + radius) + + # 绘制圆圈 (outline 参数设置圆圈的颜色,width 设置线条粗细) + draw.ellipse([left_up_point, right_down_point], outline=color, width=2) + + return image + +def get_conv_log_filename(): + t = datetime.datetime.now() + name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json") + return name + + +def get_model_list(): + ret = requests.post(args.controller_url + "/refresh_all_workers") + assert ret.status_code == 200 + ret = requests.post(args.controller_url + "/list_models") + models = ret.json()["models"] + models.sort(key=lambda x: priority.get(x, x)) + logger.info(f"Models: {models}") + return models + + +get_window_url_params = """ +function() { + const params = new URLSearchParams(window.location.search); + url_params = Object.fromEntries(params); + console.log(url_params); + return url_params; + } +""" + + +def load_demo(url_params, request: gr.Request): + logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}") + + dropdown_update = gr.Dropdown(visible=True) + if "model" in url_params: + model = url_params["model"] + if model in models: + dropdown_update = gr.Dropdown(value=model, visible=True) + + state = default_conversation.copy() + return state, dropdown_update + + +def load_demo_refresh_model_list(request: gr.Request): + logger.info(f"load_demo. ip: {request.client.host}") + models = get_model_list() + state = default_conversation.copy() + dropdown_update = gr.Dropdown( + choices=models, + value=models[0] if len(models) > 0 else "" + ) + return state, dropdown_update + + +def vote_last_response(state, vote_type, model_selector, request: gr.Request): + with open(get_conv_log_filename(), "a") as fout: + data = { + "tstamp": round(time.time(), 4), + "type": vote_type, + "model": model_selector, + "state": state.dict(), + "ip": request.client.host, + } + fout.write(json.dumps(data) + "\n") + + +def upvote_last_response(state, model_selector, request: gr.Request): + logger.info(f"upvote. ip: {request.client.host}") + vote_last_response(state, "upvote", model_selector, request) + return ("",) + (disable_btn,) * 3 + + +def downvote_last_response(state, model_selector, request: gr.Request): + logger.info(f"downvote. ip: {request.client.host}") + vote_last_response(state, "downvote", model_selector, request) + return ("",) + (disable_btn,) * 3 + + +def flag_last_response(state, model_selector, request: gr.Request): + logger.info(f"flag. ip: {request.client.host}") + vote_last_response(state, "flag", model_selector, request) + return ("",) + (disable_btn,) * 3 + + +def regenerate(state, image_process_mode, request: gr.Request): + logger.info(f"regenerate. ip: {request.client.host}") + state.messages[-1][-1] = None + prev_human_msg = state.messages[-2] + if type(prev_human_msg[1]) in (tuple, list): + prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode) + state.skip_next = False + return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5 + + +def clear_history(request: gr.Request): + logger.info(f"clear_history. ip: {request.client.host}") + state = default_conversation.copy() + return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5 + + +def add_text(state, text, image, image_process_mode, request: gr.Request): + logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}") + if len(text) <= 0 and image is None: + state.skip_next = True + return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5 + if args.moderate: + flagged = violates_moderation(text) + if flagged: + state.skip_next = True + return (state, state.to_gradio_chatbot(), moderation_msg, None) + ( + no_change_btn,) * 5 + + text = text[:500] # Hard cut-off + text=f"In the screenshot, where are the pixel coordinates (x, y) of the element corresponding to \"{text}\"?" + + if image is not None: + text = text[:1200] # Hard cut-off for images + if '' not in text: + # text = '' + text + text = text + '\n' + resized_image = resize_image(image) + text = (text, resized_image, image_process_mode) + if len(state.get_images(return_pil=True)) > 0: + state = default_conversation.copy() + state.append_message(state.roles[0], text) + state.append_message(state.roles[1], None) + state.skip_next = False + return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5 + + +def http_bot(state, model_selector, temperature, top_p, max_new_tokens, request: gr.Request): + logger.info(f"http_bot. ip: {request.client.host}") + start_tstamp = time.time() + model_name = model_selector + + if state.skip_next: + # This generate call is skipped due to invalid inputs + yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5 + return + + if len(state.messages) == state.offset + 2: + # First round of conversation + if "llava" in model_name.lower(): + if 'llama-2' in model_name.lower(): + template_name = "llava_llama_2" + elif "mistral" in model_name.lower() or "mixtral" in model_name.lower(): + if 'orca' in model_name.lower(): + template_name = "mistral_orca" + elif 'hermes' in model_name.lower(): + template_name = "chatml_direct" + else: + template_name = "mistral_instruct" + elif 'llava-v1.6-34b' in model_name.lower(): + template_name = "chatml_direct" + elif "v1" in model_name.lower(): + if 'mmtag' in model_name.lower(): + template_name = "v1_mmtag" + elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower(): + template_name = "v1_mmtag" + else: + template_name = "llava_v1" + elif "mpt" in model_name.lower(): + template_name = "mpt" + else: + if 'mmtag' in model_name.lower(): + template_name = "v0_mmtag" + elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower(): + template_name = "v0_mmtag" + else: + template_name = "llava_v0" + elif "mpt" in model_name: + template_name = "mpt_text" + elif "llama-2" in model_name: + template_name = "llama_2" + else: + template_name = "vicuna_v1" + new_state = conv_templates[template_name].copy() + new_state.append_message(new_state.roles[0], state.messages[-2][1]) + new_state.append_message(new_state.roles[1], None) + state = new_state + + # Query worker address + controller_url = args.controller_url + ret = requests.post(controller_url + "/get_worker_address", + json={"model": model_name}) + worker_addr = ret.json()["address"] + logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}") + + # No available worker + if worker_addr == "": + state.messages[-1][-1] = server_error_msg + yield (state, state.to_gradio_chatbot(), disable_btn, disable_btn, disable_btn, enable_btn, enable_btn) + return + + # Construct prompt + + + + + + prompt = state.get_prompt() + + all_images = state.get_images(return_pil=True) + all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images] + for image, hash in zip(all_images, all_image_hash): + t = datetime.datetime.now() + filename = os.path.join(LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg") + if not os.path.isfile(filename): + os.makedirs(os.path.dirname(filename), exist_ok=True) + image.save(filename) + + # Make requests + pload = { + "model": model_name, + "prompt": prompt, + "temperature": float(temperature), + "top_p": float(top_p), + "max_new_tokens": min(int(max_new_tokens), 1536), + "stop": state.sep if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT] else state.sep2, + "images": f'List of {len(state.get_images())} images: {all_image_hash}', + } + logger.info(f"==== request ====\n{pload}") + + pload['images'] = state.get_images() + + state.messages[-1][-1] = "▌" + yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5 + + try: + # Stream output + full_output = "" + response = requests.post(worker_addr + "/worker_generate_stream", + headers=headers, json=pload, stream=True, timeout=10) + for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"): + if chunk: + data = json.loads(chunk.decode()) + if data["error_code"] == 0: + output = data["text"][len(prompt):].strip() + state.messages[-1][-1] = output + "▌" + # full_output += output + yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5 + else: + output = data["text"] + f" (error_code: {data['error_code']})" + state.messages[-1][-1] = output + yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn) + return + time.sleep(0.03) + # full_output=state.messages[-1][-1] + # if "▌" in full_output: + # full_output=full_output[:-1] + except requests.exceptions.RequestException as e: + state.messages[-1][-1] = server_error_msg + yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn) + return + + state.messages[-1][-1] = state.messages[-1][-1][:-1] + full_output=state.messages[-1][-1][:-1] + yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5 + + # print(f"Complete output: {full_output}") + # logger.info(f"Complete output: {full_output}") + + finish_tstamp = time.time() + logger.info(f"{output}") + + print(f"Complete output: {full_output}") + logger.info(f"Complete output: {full_output}") + full_output=output + logger.info(f"{output}") + + print(f"Complete output: {full_output}") + logger.info(f"Complete output: {full_output}") + + original_coord=(0,0) + try: + original_coord = eval(full_output) + logger.info(f"successfully get {original_coord}") + except Exception as e: + logger.info(f"{e}") + + if len(all_images) > 0: + # 假设我们对第一张图片进行 resize 并展示 + resized_image = draw_circle_on_image(resize_image(all_images[0]),original_coord[0],original_coord[1]) + # state.append_message(state.roles[1], ("", resized_image,"Default")) + yield (state, state.to_gradio_chatbot(resized_image)) + (enable_btn,) * 5 + + with open(get_conv_log_filename(), "a") as fout: + data = { + "tstamp": round(finish_tstamp, 4), + "type": "chat", + "model": model_name, + "start": round(start_tstamp, 4), + "finish": round(finish_tstamp, 4), + "state": state.dict(), + "images": all_image_hash, + "ip": request.client.host, + } + fout.write(json.dumps(data) + "\n") + +title_markdown = (""" +# UGround: Universal Visual Grounding for GUI Agents +[[Project Homepage](https://osu-nlp-group.github.io/UGround/)] [[Code](https://github.com/OSU-NLP-Group/UGround)] [[Model](https://huggingface.co/osunlp/UGround)] | 📚 [[Paper](https://arxiv.org/abs/2410.05243)]] +""") + +tos_markdown = (""" +### Terms of use +By using this service, users are required to agree to the following terms: +The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research. +Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator. +For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality. +""") + + +learn_more_markdown = (""" +### License +The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) of LLaMA, [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI. Please contact us if you find any potential violation. +""") + +block_css = """ + +#buttons button { + min-width: min(120px,100%); +} + +#chatbot img { + max-width: 100%; /* 宽图片根据宽度调整 */ + max-height: 100vh; /* 高图片根据视口高度调整 */ + width: auto; /* 保持宽度自适应 */ + height: auto; /* 保持高度自适应 */ + object-fit: contain; /* 保持图片宽高比,不失真 */ +} + +""" + +def build_demo(embed_mode, cur_dir=None, concurrency_count=1): + textbox = gr.Textbox(show_label=False, placeholder="Enter an element description (referring expression) and press ENTER", container=False) + with gr.Blocks(title="UGround", theme=gr.themes.Default(), css=block_css) as demo: + state = gr.State() + + if not embed_mode: + gr.Markdown(title_markdown) + + with gr.Row(): + with gr.Column(scale=3): + with gr.Row(elem_id="model_selector_row"): + model_selector = gr.Dropdown( + choices=models, + value=models[0] if len(models) > 0 else "", + interactive=True, + show_label=False, + container=False) + + imagebox = gr.Image(type="pil") + image_process_mode = gr.Radio( + ["Crop", "Resize", "Pad", "Default"], + value="Default", + label="Preprocess for non-square image", visible=False) + + if cur_dir is None: + cur_dir = os.path.dirname(os.path.abspath(__file__)) + gr.Examples(examples=[ + [f"{cur_dir}/amazon.jpg",f"Search bar at the top of the page"], + # [f"{cur_dir}/examples/waterview.jpg", "What are the things I should be cautious about when I visit here?"], + ], inputs=[imagebox, textbox]) + + with gr.Accordion("Parameters", open=False) as parameter_row: + temperature = gr.Slider(minimum=0.0, maximum=1.0, value=0.2, step=0.1, interactive=True, label="Temperature",) + top_p = gr.Slider(minimum=0.0, maximum=1.0, value=0.7, step=0.1, interactive=True, label="Top P",) + max_output_tokens = gr.Slider(minimum=0, maximum=1024, value=512, step=64, interactive=True, label="Max output tokens",) + + with gr.Column(scale=8): + chatbot = gr.Chatbot( + elem_id="chatbot", + label="UGround Chatbot", + height=650, + # min_width=400, + layout="panel", + ) + with gr.Row(): + with gr.Column(scale=8): + textbox.render() + with gr.Column(scale=1, min_width=50): + submit_btn = gr.Button(value="Send", variant="primary") + with gr.Row(elem_id="buttons") as button_row: + upvote_btn = gr.Button(value="👍 Upvote", interactive=False) + downvote_btn = gr.Button(value="👎 Downvote", interactive=False) + flag_btn = gr.Button(value="⚠️ Flag", interactive=False) + #stop_btn = gr.Button(value="⏹️ Stop Generation", interactive=False) + regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False) + clear_btn = gr.Button(value="🗑️ Clear", interactive=False) + + if not embed_mode: + gr.Markdown(tos_markdown) + gr.Markdown(learn_more_markdown) + url_params = gr.JSON(visible=False) + + # Register listeners + btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn] + upvote_btn.click( + upvote_last_response, + [state, model_selector], + [textbox, upvote_btn, downvote_btn, flag_btn] + ) + downvote_btn.click( + downvote_last_response, + [state, model_selector], + [textbox, upvote_btn, downvote_btn, flag_btn] + ) + flag_btn.click( + flag_last_response, + [state, model_selector], + [textbox, upvote_btn, downvote_btn, flag_btn] + ) + + regenerate_btn.click( + regenerate, + [state, image_process_mode], + [state, chatbot, textbox, imagebox] + btn_list + ).then( + http_bot, + [state, model_selector, temperature, top_p, max_output_tokens], + [state, chatbot] + btn_list, + concurrency_limit=concurrency_count + ) + + clear_btn.click( + clear_history, + None, + [state, chatbot, textbox, imagebox] + btn_list, + queue=False + ) + + textbox.submit( + add_text, + [state, textbox, imagebox, image_process_mode], + [state, chatbot, textbox, imagebox] + btn_list, + queue=False + ).then( + http_bot, + [state, model_selector, temperature, top_p, max_output_tokens], + [state, chatbot] + btn_list, + concurrency_limit=concurrency_count + ) + + submit_btn.click( + add_text, + [state, textbox, imagebox, image_process_mode], + [state, chatbot, textbox, imagebox] + btn_list + ).then( + http_bot, + [state, model_selector, temperature, top_p, max_output_tokens], + [state, chatbot] + btn_list, + concurrency_limit=concurrency_count + ) + + if args.model_list_mode == "once": + demo.load( + load_demo, + [url_params], + [state, model_selector], + _js=get_window_url_params + ) + elif args.model_list_mode == "reload": + demo.load( + load_demo_refresh_model_list, + None, + [state, model_selector], + queue=False + ) + else: + raise ValueError(f"Unknown model list mode: {args.model_list_mode}") + + return demo + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--host", type=str, default="0.0.0.0") + parser.add_argument("--port", type=int) + parser.add_argument("--controller-url", type=str, default="http://localhost:21001") + parser.add_argument("--concurrency-count", type=int, default=2) + parser.add_argument("--model-list-mode", type=str, default="once", + choices=["once", "reload"]) + parser.add_argument("--share", action="store_true") + parser.add_argument("--moderate", action="store_true") + parser.add_argument("--embed", action="store_true") + args = parser.parse_args() + logger.info(f"args: {args}") + + models = get_model_list() + + logger.info(args) + demo = build_demo(args.embed, concurrency_count=args.concurrency_count) + demo.queue( + api_open=False + ).launch( + server_name=args.host, + server_port=args.port, + share=args.share + ) diff --git a/llava/serve/model_worker.py b/llava/serve/model_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..f955d11f5218433c600aa8a2bcfb42e36dd09fee --- /dev/null +++ b/llava/serve/model_worker.py @@ -0,0 +1,290 @@ +""" +A model worker executes the model. +""" +import argparse +import asyncio +import json +import time +import threading +import uuid + +from fastapi import FastAPI, Request, BackgroundTasks +from fastapi.responses import StreamingResponse +import requests +import torch +import uvicorn +from functools import partial + +from llava.constants import WORKER_HEART_BEAT_INTERVAL +from llava.utils import (build_logger, server_error_msg, + pretty_print_semaphore) +from llava.model.builder import load_pretrained_model +from llava.mm_utils import process_images, load_image_from_base64, tokenizer_image_token, KeywordsStoppingCriteria +from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from transformers import TextIteratorStreamer +from threading import Thread + + +GB = 1 << 30 + +worker_id = str(uuid.uuid4())[:6] +logger = build_logger("model_worker", f"model_worker_{worker_id}.log") +global_counter = 0 + +model_semaphore = None + + +def heart_beat_worker(controller): + + while True: + time.sleep(WORKER_HEART_BEAT_INTERVAL) + controller.send_heart_beat() + + +class ModelWorker: + def __init__(self, controller_addr, worker_addr, + worker_id, no_register, + model_path, model_base, model_name, + load_8bit, load_4bit, device, use_flash_attn=False): + self.controller_addr = controller_addr + self.worker_addr = worker_addr + self.worker_id = worker_id + if model_path.endswith("/"): + model_path = model_path[:-1] + if model_name is None: + model_paths = model_path.split("/") + if model_paths[-1].startswith('checkpoint-'): + self.model_name = model_paths[-2] + "_" + model_paths[-1] + else: + self.model_name = model_paths[-1] + else: + self.model_name = model_name + + self.device = device + logger.info(f"Loading the model {self.model_name} on worker {worker_id} ...") + self.tokenizer, self.model, self.image_processor, self.context_len = load_pretrained_model( + model_path, model_base, self.model_name, load_8bit, load_4bit, device=self.device, use_flash_attn=use_flash_attn) + self.is_multimodal = 'llava' in self.model_name.lower() + + if not no_register: + self.register_to_controller() + self.heart_beat_thread = threading.Thread( + target=heart_beat_worker, args=(self,)) + self.heart_beat_thread.start() + + def register_to_controller(self): + logger.info("Register to controller") + + url = self.controller_addr + "/register_worker" + data = { + "worker_name": self.worker_addr, + "check_heart_beat": True, + "worker_status": self.get_status() + } + r = requests.post(url, json=data) + assert r.status_code == 200 + + def send_heart_beat(self): + logger.info(f"Send heart beat. Models: {[self.model_name]}. " + f"Semaphore: {pretty_print_semaphore(model_semaphore)}. " + f"global_counter: {global_counter}") + + url = self.controller_addr + "/receive_heart_beat" + + while True: + try: + ret = requests.post(url, json={ + "worker_name": self.worker_addr, + "queue_length": self.get_queue_length()}, timeout=5) + exist = ret.json()["exist"] + break + except requests.exceptions.RequestException as e: + logger.error(f"heart beat error: {e}") + time.sleep(5) + + if not exist: + self.register_to_controller() + + def get_queue_length(self): + if model_semaphore is None: + return 0 + else: + return args.limit_model_concurrency - model_semaphore._value + (len( + model_semaphore._waiters) if model_semaphore._waiters is not None else 0) + + def get_status(self): + return { + "model_names": [self.model_name], + "speed": 1, + "queue_length": self.get_queue_length(), + } + + @torch.inference_mode() + def generate_stream(self, params): + tokenizer, model, image_processor = self.tokenizer, self.model, self.image_processor + + prompt = params["prompt"] + ori_prompt = prompt + images = params.get("images", None) + num_image_tokens = 0 + if images is not None and len(images) > 0 and self.is_multimodal: + if len(images) > 0: + if len(images) != prompt.count(DEFAULT_IMAGE_TOKEN): + raise ValueError("Number of images does not match number of tokens in prompt") + + images = [load_image_from_base64(image) for image in images] + image_sizes = [image.size for image in images] + # images = process_images(images, image_processor, model.config) + image_tensor, image_new_size= process_images(images, image_processor, model.config) + # image_tensor=image_tensor.to(self.model.device, dtype=torch.float16) + # if type(images) is list: + # images = [image.to(self.model.device, dtype=torch.float16) for image in images] + # else: + # images = images.to(self.model.device, dtype=torch.float16) + + replace_token = DEFAULT_IMAGE_TOKEN + if getattr(self.model.config, 'mm_use_im_start_end', False): + replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN + prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token) + + num_image_tokens = prompt.count(replace_token) * model.get_vision_tower().num_patches + else: + images = None + image_sizes = None + image_args = {"images": image_tensor.half().cuda(), "image_sizes": [image_new_size]} + else: + images = None + image_args = {} + + temperature = float(params.get("temperature", 1.0)) + top_p = float(params.get("top_p", 1.0)) + max_context_length = getattr(model.config, 'max_position_embeddings', 2048) + max_new_tokens = min(int(params.get("max_new_tokens", 256)), 1024) + stop_str = params.get("stop", None) + do_sample = True if temperature > 0.001 else False + + input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(self.device) + keywords = [stop_str] + stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids) + streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=15) + + # max_new_tokens = min(max_new_tokens, max_context_length - input_ids.shape[-1] - num_image_tokens) + + if max_new_tokens < 1: + yield json.dumps({"text": ori_prompt + "Exceeds max token length. Please start a new conversation, thanks.", "error_code": 0}).encode() + b"\0" + return + + thread = Thread(target=model.generate, kwargs=dict( + inputs=input_ids, + do_sample=do_sample, + temperature=temperature, + top_p=top_p, + max_new_tokens=16384, + streamer=streamer, + stopping_criteria=[stopping_criteria], + use_cache=True, + **image_args + )) + thread.start() + + generated_text = ori_prompt + for new_text in streamer: + generated_text += new_text + if generated_text.endswith(stop_str): + generated_text = generated_text[:-len(stop_str)] + yield json.dumps({"text": generated_text, "error_code": 0}).encode() + b"\0" + + def generate_stream_gate(self, params): + try: + for x in self.generate_stream(params): + yield x + except ValueError as e: + print("Caught ValueError:", e) + ret = { + "text": server_error_msg, + "error_code": 1, + } + yield json.dumps(ret).encode() + b"\0" + except torch.cuda.CudaError as e: + print("Caught torch.cuda.CudaError:", e) + ret = { + "text": server_error_msg, + "error_code": 1, + } + yield json.dumps(ret).encode() + b"\0" + except Exception as e: + print("Caught Unknown Error", e) + ret = { + "text": server_error_msg, + "error_code": 1, + } + yield json.dumps(ret).encode() + b"\0" + + +app = FastAPI() + + +def release_model_semaphore(fn=None): + model_semaphore.release() + if fn is not None: + fn() + + +@app.post("/worker_generate_stream") +async def generate_stream(request: Request): + global model_semaphore, global_counter + global_counter += 1 + params = await request.json() + + if model_semaphore is None: + model_semaphore = asyncio.Semaphore(args.limit_model_concurrency) + await model_semaphore.acquire() + worker.send_heart_beat() + generator = worker.generate_stream_gate(params) + background_tasks = BackgroundTasks() + background_tasks.add_task(partial(release_model_semaphore, fn=worker.send_heart_beat)) + return StreamingResponse(generator, background=background_tasks) + + +@app.post("/worker_get_status") +async def get_status(request: Request): + return worker.get_status() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--host", type=str, default="localhost") + parser.add_argument("--port", type=int, default=21002) + parser.add_argument("--worker-address", type=str, + default="http://localhost:21002") + parser.add_argument("--controller-address", type=str, + default="http://localhost:21001") + parser.add_argument("--model-path", type=str, default="facebook/opt-350m") + parser.add_argument("--model-base", type=str, default=None) + parser.add_argument("--model-name", type=str) + parser.add_argument("--device", type=str, default="cuda") + parser.add_argument("--multi-modal", action="store_true", help="Multimodal mode is automatically detected with model name, please make sure `llava` is included in the model path.") + parser.add_argument("--limit-model-concurrency", type=int, default=5) + parser.add_argument("--stream-interval", type=int, default=1) + parser.add_argument("--no-register", action="store_true") + parser.add_argument("--load-8bit", action="store_true") + parser.add_argument("--load-4bit", action="store_true") + parser.add_argument("--use-flash-attn", action="store_true") + args = parser.parse_args() + logger.info(f"args: {args}") + + if args.multi_modal: + logger.warning("Multimodal mode is automatically detected with model name, please make sure `llava` is included in the model path.") + + worker = ModelWorker(args.controller_address, + args.worker_address, + worker_id, + args.no_register, + args.model_path, + args.model_base, + args.model_name, + args.load_8bit, + args.load_4bit, + args.device, + use_flash_attn=args.use_flash_attn) + uvicorn.run(app, host=args.host, port=args.port, log_level="info") diff --git a/llava/serve/new_gws.py b/llava/serve/new_gws.py new file mode 100644 index 0000000000000000000000000000000000000000..030e0b8f849e6199911aba181d421b1ed2caac40 --- /dev/null +++ b/llava/serve/new_gws.py @@ -0,0 +1,526 @@ +import argparse +import datetime +import json +import os +import time + +import gradio as gr +import requests + +from llava.conversation import (default_conversation, conv_templates, + SeparatorStyle) +from llava.constants import LOGDIR +from llava.utils import (build_logger, server_error_msg, + violates_moderation, moderation_msg) +import hashlib + +from PIL import Image, ImageDraw,ImageFont +def get_scale_factor(original_size): + original_width, original_height = original_size + new_width = min(nearest_multiple_of_224_at_least_224(original_width, ceiling=False), 1344) + scale_factor = new_width / original_width + return scale_factor + + +def nearest_multiple_of_224_at_least_224(num, ceiling=False): + if num <= 224: + return 224 + division, remainder = divmod(num, 224) + if ceiling and remainder > 0: + return (division + 1) * 224 + if remainder < 112: + return division * 224 + else: + return (division + 1) * 224 + +logger = build_logger("gradio_web_server", "gradio_web_server.log") + +headers = {"User-Agent": "UGround Client"} + +no_change_btn = gr.Button() +enable_btn = gr.Button(interactive=True) +disable_btn = gr.Button(interactive=False) + +priority = { + "vicuna-13b": "aaaaaaa", + "koala-13b": "aaaaaab", +} + + +def get_conv_log_filename(): + t = datetime.datetime.now() + name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json") + return name + + +def get_model_list(): + ret = requests.post(args.controller_url + "/refresh_all_workers") + assert ret.status_code == 200 + ret = requests.post(args.controller_url + "/list_models") + models = ret.json()["models"] + models.sort(key=lambda x: priority.get(x, x)) + logger.info(f"Models: {models}") + return models + + +get_window_url_params = """ +function() { + const params = new URLSearchParams(window.location.search); + url_params = Object.fromEntries(params); + console.log(url_params); + return url_params; + } +""" + + +def load_demo(url_params, request: gr.Request): + logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}") + + dropdown_update = gr.Dropdown(visible=True) + if "model" in url_params: + model = url_params["model"] + if model in models: + dropdown_update = gr.Dropdown(value=model, visible=True) + + state = default_conversation.copy() + return state, dropdown_update + + +def load_demo_refresh_model_list(request: gr.Request): + logger.info(f"load_demo. ip: {request.client.host}") + models = get_model_list() + state = default_conversation.copy() + dropdown_update = gr.Dropdown( + choices=models, + value=models[0] if len(models) > 0 else "" + ) + return state, dropdown_update + + +def vote_last_response(state, vote_type, model_selector, request: gr.Request): + with open(get_conv_log_filename(), "a") as fout: + data = { + "tstamp": round(time.time(), 4), + "type": vote_type, + "model": model_selector, + "state": state.dict(), + "ip": request.client.host, + } + fout.write(json.dumps(data) + "\n") + + +def upvote_last_response(state, model_selector, request: gr.Request): + logger.info(f"upvote. ip: {request.client.host}") + vote_last_response(state, "upvote", model_selector, request) + return ("",) + (disable_btn,) * 3 + + +def downvote_last_response(state, model_selector, request: gr.Request): + logger.info(f"downvote. ip: {request.client.host}") + vote_last_response(state, "downvote", model_selector, request) + return ("",) + (disable_btn,) * 3 + + +def flag_last_response(state, model_selector, request: gr.Request): + logger.info(f"flag. ip: {request.client.host}") + vote_last_response(state, "flag", model_selector, request) + return ("",) + (disable_btn,) * 3 + + +def regenerate(state, image_process_mode, request: gr.Request): + logger.info(f"regenerate. ip: {request.client.host}") + state.messages[-1][-1] = None + prev_human_msg = state.messages[-2] + if type(prev_human_msg[1]) in (tuple, list): + prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode) + state.skip_next = False + return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5 + + +def clear_history(request: gr.Request): + logger.info(f"clear_history. ip: {request.client.host}") + state = default_conversation.copy() + return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5 + + +def add_text(state, text, image, image_process_mode, request: gr.Request): + logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}") + + + if image is not None: + # 默认的宽度和高度 + default_width = (1344, 896) + # 读取图像 + original_width, original_height = image.size + + # Resize逻辑基于宽度和高度比较 + if original_width >= original_height: + # 基于宽度调整大小 + new_width = default_width[0] + resize_scale = new_width / original_width + new_height = round(original_height * resize_scale) + else: + # 基于高度调整大小 + new_width = default_width[1] + resize_scale = new_width / original_width + new_height = round(original_height * resize_scale) + + # 调整图像大小 + image = image.resize((new_width, new_height)) + + + + if len(text) <= 0 and image is None: + state.skip_next = True + return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5 + if args.moderate: + flagged = violates_moderation(text) + if flagged: + state.skip_next = True + return (state, state.to_gradio_chatbot(), moderation_msg, None) + ( + no_change_btn,) * 5 + + text = text[:16384] # Hard cut-off + if image is not None: + text = text[:16384] # Hard cut-off for images + if '' not in text: + # text = '' + text + text ="In the screenshot, where are the pixel coordinates (x, y) of the element corresponding to "+ f"\"{text}\"?" + '\n' + + + + text = (text, image, image_process_mode) + state = default_conversation.copy() + state.append_message(state.roles[0], text) + state.append_message(state.roles[1], None) + state.skip_next = False + return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5 + + +def http_bot(state, model_selector, temperature, top_p, max_new_tokens, request: gr.Request): + logger.info(f"http_bot. ip: {request.client.host}") + start_tstamp = time.time() + # model_name = model_selector + model_name="osunlp/UGround" + if state.skip_next: + # This generate call is skipped due to invalid inputs + yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5 + return + + if len(state.messages) == state.offset + 2: + # First round of conversation + # if "llava" in model_name.lower(): + # if 'llama-2' in model_name.lower(): + # template_name = "llava_llama_2" + # elif "mistral" in model_name.lower() or "mixtral" in model_name.lower(): + # if 'orca' in model_name.lower(): + # template_name = "mistral_orca" + # elif 'hermes' in model_name.lower(): + # template_name = "chatml_direct" + # else: + # template_name = "mistral_instruct" + # elif 'llava-v1.6-34b' in model_name.lower(): + # template_name = "chatml_direct" + # elif "v1" in model_name.lower(): + # if 'mmtag' in model_name.lower(): + # template_name = "v1_mmtag" + # elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower(): + # template_name = "v1_mmtag" + # else: + # template_name = "llava_v1" + # elif "mpt" in model_name.lower(): + # template_name = "mpt" + # else: + # if 'mmtag' in model_name.lower(): + # template_name = "v0_mmtag" + # elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower(): + # template_name = "v0_mmtag" + # else: + # template_name = "llava_v0" + # elif "mpt" in model_name: + # template_name = "mpt_text" + # elif "llama-2" in model_name: + # template_name = "llama_2" + # else: + # template_name = "vicuna_v1" + template_name='llava_v1' + new_state = conv_templates[template_name].copy() + new_state.append_message(new_state.roles[0], state.messages[-2][1]) + new_state.append_message(new_state.roles[1], None) + state = new_state + + # Query worker address + controller_url = args.controller_url + ret = requests.post(controller_url + "/get_worker_address", + json={"model": model_name}) + worker_addr = ret.json()["address"] + logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}") + + # No available worker + if worker_addr == "": + state.messages[-1][-1] = server_error_msg + yield (state, state.to_gradio_chatbot(), disable_btn, disable_btn, disable_btn, enable_btn, enable_btn) + return + + # Construct prompt + prompt = state.get_prompt() + + all_images = state.get_images(return_pil=True) + all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images] + for image, hash in zip(all_images, all_image_hash): + t = datetime.datetime.now() + filename = os.path.join(LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg") + if not os.path.isfile(filename): + os.makedirs(os.path.dirname(filename), exist_ok=True) + image.save(filename) + + # Make requests + pload = { + "model": model_name, + "prompt": prompt, + "temperature": float(temperature), + "top_p": float(top_p), + "max_new_tokens": min(int(max_new_tokens), 16384), + "stop": state.sep if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT] else state.sep2, + "images": f'List of {len(state.get_images())} images: {all_image_hash}', + } + logger.info(f"==== request ====\n{pload}") + + pload['images'] = state.get_images() + + state.messages[-1][-1] = "▌" + yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5 + + try: + # Stream output + response = requests.post(worker_addr + "/worker_generate_stream", + headers=headers, json=pload, stream=True, timeout=20) + for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"): + if chunk: + data = json.loads(chunk.decode()) + if data["error_code"] == 0: + output = data["text"][len(prompt):].strip() + state.messages[-1][-1] = output + "▌" + yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5 + else: + output = data["text"] + f" (error_code: {data['error_code']})" + state.messages[-1][-1] = output + yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn) + return + time.sleep(0.03) + except requests.exceptions.RequestException as e: + state.messages[-1][-1] = server_error_msg + yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn) + return + + state.messages[-1][-1] = state.messages[-1][-1][:-1] + yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5 + + finish_tstamp = time.time() + logger.info(f"{output}") + + with open(get_conv_log_filename(), "a") as fout: + data = { + "tstamp": round(finish_tstamp, 4), + "type": "chat", + "model": model_name, + "start": round(start_tstamp, 4), + "finish": round(finish_tstamp, 4), + "state": state.dict(), + "images": all_image_hash, + "ip": request.client.host, + } + fout.write(json.dumps(data) + "\n") + +title_markdown = (""" +# UGround: Universal Visual Grounding For GUI Agents + [[Project Page]](https://osu-nlp-group.github.io/UGround/) [[Paper]](https://github.com/OSU-NLP-Group/UGround/blob/gh-pages/static/papers/UGround_paper.pdf) [[Code]](https://github.com/OSU-NLP-Group/UGround) [[Model]](https://huggingface.co/osunlp/UGround) +""") + +tos_markdown = (""" +### Terms of use +By using this service, users are required to agree to the following terms: +The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research. +Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator. +For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality. +""") + + +learn_more_markdown = (""" +### License +The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) of LLaMA, [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI, and [Privacy Practices](https://chrome.google.com/webstore/detail/sharegpt-share-your-chatg/daiacboceoaocpibfodeljbdfacokfjb) of ShareGPT. Please contact us if you find any potential violation. +""") + +block_css = """ + +#buttons button { + min-width: min(120px,100%); +} + +""" + +def build_demo(embed_mode, cur_dir=None, concurrency_count=10): + textbox = gr.Textbox(show_label=False, placeholder="Enter an element description (referring expression) and press ENTER", container=False) + with gr.Blocks(title="UGround", theme=gr.themes.Default(), css=block_css) as demo: + state = gr.State() + + if not embed_mode: + gr.Markdown(title_markdown) + + with gr.Row(): + with gr.Column(scale=3): + with gr.Row(elem_id="model_selector_row"): + model_selector = gr.Dropdown( + choices=models, + value=models[0] if len(models) > 0 else "", + interactive=True, + show_label=False, + container=False) + + imagebox = gr.Image(type="pil") + image_process_mode = gr.Radio( + ["Crop", "Resize", "Pad", "Default"], + value="Default", + label="Preprocess for non-square image", visible=False) + + if cur_dir is None: + cur_dir = os.path.dirname(os.path.abspath(__file__)) + gr.Examples(examples=[ + [f"{cur_dir}/amazon.jpg", "Where is the search bar at the top of the page?"], + # [f"{cur_dir}/examples/waterview.jpg", "What are the things I should be cautious about when I visit here?"], + ], inputs=[imagebox, textbox]) + + with gr.Accordion("Parameters", open=False) as parameter_row: + temperature = gr.Slider(minimum=0.0, maximum=1.0, value=0.1, step=0.1, interactive=True, label="Temperature",) + top_p = gr.Slider(minimum=0.0, maximum=1.0, value=0.7, step=0.1, interactive=True, label="Top P",) + max_output_tokens = gr.Slider(minimum=0, maximum=16384, value=16384, step=64, interactive=True, label="Max output tokens",) + + with gr.Column(scale=8): + chatbot = gr.Chatbot( + elem_id="chatbot", + label="UGround Chatbot", + height=650, + layout="panel", + ) + with gr.Row(): + with gr.Column(scale=8): + textbox.render() + with gr.Column(scale=1, min_width=50): + submit_btn = gr.Button(value="Send", variant="primary") + with gr.Row(elem_id="buttons") as button_row: + upvote_btn = gr.Button(value="👍 Upvote", interactive=False) + downvote_btn = gr.Button(value="👎 Downvote", interactive=False) + flag_btn = gr.Button(value="⚠️ Flag", interactive=False) + #stop_btn = gr.Button(value="⏹️ Stop Generation", interactive=False) + regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False) + clear_btn = gr.Button(value="🗑️ Clear", interactive=False) + + if not embed_mode: + gr.Markdown(tos_markdown) + gr.Markdown(learn_more_markdown) + url_params = gr.JSON(visible=False) + + # Register listeners + btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn] + upvote_btn.click( + upvote_last_response, + [state, model_selector], + [textbox, upvote_btn, downvote_btn, flag_btn] + ) + downvote_btn.click( + downvote_last_response, + [state, model_selector], + [textbox, upvote_btn, downvote_btn, flag_btn] + ) + flag_btn.click( + flag_last_response, + [state, model_selector], + [textbox, upvote_btn, downvote_btn, flag_btn] + ) + + regenerate_btn.click( + regenerate, + [state, image_process_mode], + [state, chatbot, textbox, imagebox] + btn_list + ).then( + http_bot, + [state, model_selector, temperature, top_p, max_output_tokens], + [state, chatbot] + btn_list, + concurrency_limit=concurrency_count + ) + + clear_btn.click( + clear_history, + None, + [state, chatbot, textbox, imagebox] + btn_list, + queue=False + ) + + textbox.submit( + add_text, + [state, textbox, imagebox, image_process_mode], + [state, chatbot, textbox, imagebox] + btn_list, + queue=False + ).then( + http_bot, + [state, model_selector, temperature, top_p, max_output_tokens], + [state, chatbot] + btn_list, + concurrency_limit=concurrency_count + ) + + submit_btn.click( + add_text, + [state, textbox, imagebox, image_process_mode], + [state, chatbot, textbox, imagebox] + btn_list + ).then( + http_bot, + [state, model_selector, temperature, top_p, max_output_tokens], + [state, chatbot] + btn_list, + concurrency_limit=concurrency_count + ) + + if args.model_list_mode == "once": + demo.load( + load_demo, + [url_params], + [state, model_selector], + js=get_window_url_params + ) + elif args.model_list_mode == "reload": + demo.load( + load_demo_refresh_model_list, + None, + [state, model_selector], + queue=False + ) + else: + raise ValueError(f"Unknown model list mode: {args.model_list_mode}") + + return demo + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--host", type=str, default="0.0.0.0") + parser.add_argument("--port", type=int) + parser.add_argument("--controller-url", type=str, default="http://localhost:21001") + parser.add_argument("--concurrency-count", type=int, default=2) + parser.add_argument("--model-list-mode", type=str, default="once", + choices=["once", "reload"]) + parser.add_argument("--share", action="store_true") + parser.add_argument("--moderate", action="store_true") + parser.add_argument("--embed", action="store_true") + args = parser.parse_args() + logger.info(f"args: {args}") + + models = get_model_list() + + logger.info(args) + demo = build_demo(args.embed, concurrency_count=args.concurrency_count) + demo.queue( + api_open=False + ).launch( + server_name=args.host, + server_port=args.port, + share=args.share + ) diff --git a/llava/serve/register_worker.py b/llava/serve/register_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..2c2c40295e0351f25709ba25554c9329f15bf0d2 --- /dev/null +++ b/llava/serve/register_worker.py @@ -0,0 +1,26 @@ +""" +Manually register workers. + +Usage: +python3 -m fastchat.serve.register_worker --controller http://localhost:21001 --worker-name http://localhost:21002 +""" + +import argparse + +import requests + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--controller-address", type=str) + parser.add_argument("--worker-name", type=str) + parser.add_argument("--check-heart-beat", action="store_true") + args = parser.parse_args() + + url = args.controller_address + "/register_worker" + data = { + "worker_name": args.worker_name, + "check_heart_beat": args.check_heart_beat, + "worker_status": None, + } + r = requests.post(url, json=data) + assert r.status_code == 200 diff --git a/llava/serve/sglang_worker.py b/llava/serve/sglang_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..a3297b7c295abddedfaac7f6fbe882d7b672487d --- /dev/null +++ b/llava/serve/sglang_worker.py @@ -0,0 +1,244 @@ +""" +A model worker executes the model. +""" +import argparse +import asyncio +from concurrent.futures import ThreadPoolExecutor +import json +import time +import threading +import uuid + +from fastapi import FastAPI, Request, BackgroundTasks +from fastapi.responses import StreamingResponse +import requests +import re +import uvicorn +from functools import partial + +from llava.constants import WORKER_HEART_BEAT_INTERVAL +from llava.utils import (build_logger, server_error_msg, + pretty_print_semaphore) +from llava.mm_utils import process_images, load_image_from_base64, tokenizer_image_token, expand2square +from llava.constants import DEFAULT_IMAGE_TOKEN + +import sglang as sgl +from sglang.backend.runtime_endpoint import RuntimeEndpoint + + +GB = 1 << 30 + +worker_id = str(uuid.uuid4())[:6] +logger = build_logger("model_worker", f"model_worker_{worker_id}.log") +global_counter = 0 + +model_semaphore = None + + +def heart_beat_worker(controller): + while True: + time.sleep(WORKER_HEART_BEAT_INTERVAL) + controller.send_heart_beat() + + +@sgl.function +def pipeline(s, prompt, max_tokens): + for p in prompt: + if type(p) is str: + s += p + else: + s += sgl.image(p) + s += sgl.gen("response", max_tokens=max_tokens) + + +class ModelWorker: + def __init__(self, controller_addr, worker_addr, sgl_endpoint, + worker_id, no_register, model_name): + self.controller_addr = controller_addr + self.worker_addr = worker_addr + self.worker_id = worker_id + + # Select backend + backend = RuntimeEndpoint(sgl_endpoint) + sgl.set_default_backend(backend) + model_path = backend.model_info["model_path"] + + if model_path.endswith("/"): + model_path = model_path[:-1] + if model_name is None: + model_paths = model_path.split("/") + if model_paths[-1].startswith('checkpoint-'): + self.model_name = model_paths[-2] + "_" + model_paths[-1] + else: + self.model_name = model_paths[-1] + else: + self.model_name = model_name + + logger.info(f"Loading the SGLANG model {self.model_name} on worker {worker_id} ...") + + if not no_register: + self.register_to_controller() + self.heart_beat_thread = threading.Thread( + target=heart_beat_worker, args=(self,), daemon=True) + self.heart_beat_thread.start() + + def register_to_controller(self): + logger.info("Register to controller") + + url = self.controller_addr + "/register_worker" + data = { + "worker_name": self.worker_addr, + "check_heart_beat": True, + "worker_status": self.get_status() + } + r = requests.post(url, json=data) + assert r.status_code == 200 + + def send_heart_beat(self): + logger.info(f"Send heart beat. Models: {[self.model_name]}. " + f"Semaphore: {pretty_print_semaphore(model_semaphore)}. " + f"global_counter: {global_counter}") + + url = self.controller_addr + "/receive_heart_beat" + + while True: + try: + ret = requests.post(url, json={ + "worker_name": self.worker_addr, + "queue_length": self.get_queue_length()}, timeout=5) + exist = ret.json()["exist"] + break + except requests.exceptions.RequestException as e: + logger.error(f"heart beat error: {e}") + time.sleep(5) + + if not exist: + self.register_to_controller() + + def get_queue_length(self): + if model_semaphore is None: + return 0 + else: + return args.limit_model_concurrency - model_semaphore._value + (len( + model_semaphore._waiters) if model_semaphore._waiters is not None else 0) + + def get_status(self): + return { + "model_names": [self.model_name], + "speed": 1, + "queue_length": self.get_queue_length(), + } + + async def generate_stream(self, params): + ori_prompt = prompt = params["prompt"] + images = params.get("images", None) + if images is not None and len(images) > 0: + if len(images) > 0: + if len(images) != prompt.count(DEFAULT_IMAGE_TOKEN): + raise ValueError("Number of images does not match number of tokens in prompt") + + images = [load_image_from_base64(image) for image in images] + + # FIXME: for image-start/end token + # replace_token = DEFAULT_IMAGE_TOKEN + # if getattr(self.model.config, 'mm_use_im_start_end', False): + # replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN + # prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token) + prompt = prompt.replace(' ' + DEFAULT_IMAGE_TOKEN + '\n', DEFAULT_IMAGE_TOKEN) + prompt_split = prompt.split(DEFAULT_IMAGE_TOKEN) + prompt = [] + for i in range(len(prompt_split)): + prompt.append(prompt_split[i]) + if i < len(images): + prompt.append(images[i]) + else: + prompt = [prompt] + + temperature = float(params.get("temperature", 1.0)) + top_p = float(params.get("top_p", 1.0)) + # max_context_length = getattr(model.config, 'max_position_embeddings', 2048) + max_new_tokens = min(int(params.get("max_new_tokens", 256)), 1024) + stop_str = params.get("stop", None) + stop_str = [stop_str] if stop_str is not None else None + + print({'prompt': prompt, 'max_new_tokens': max_new_tokens, 'temperature': temperature, 'top_p': top_p}) + state = pipeline.run(prompt, max_new_tokens, temperature=temperature, top_p=top_p, stream=True) + + generated_text = ori_prompt + async for text_outputs in state.text_async_iter(var_name="response"): + generated_text += text_outputs + yield json.dumps({"text": generated_text, "error_code": 0}).encode() + b"\0" + + async def generate_stream_gate(self, params): + try: + async for x in self.generate_stream(params): + yield x + except ValueError as e: + print("Caught ValueError:", e) + ret = { + "text": server_error_msg, + "error_code": 1, + } + yield json.dumps(ret).encode() + b"\0" + except Exception as e: + print("Caught Unknown Error", e) + ret = { + "text": server_error_msg, + "error_code": 1, + } + yield json.dumps(ret).encode() + b"\0" + + +app = FastAPI() + + +def release_model_semaphore(fn=None): + model_semaphore.release() + if fn is not None: + fn() + + +@app.post("/worker_generate_stream") +async def generate_stream(request: Request): + global model_semaphore, global_counter + global_counter += 1 + params = await request.json() + + if model_semaphore is None: + model_semaphore = asyncio.Semaphore(args.limit_model_concurrency) + await model_semaphore.acquire() + worker.send_heart_beat() + generator = worker.generate_stream_gate(params) + background_tasks = BackgroundTasks() + background_tasks.add_task(partial(release_model_semaphore, fn=worker.send_heart_beat)) + return StreamingResponse(generator, background=background_tasks) + + +@app.post("/worker_get_status") +async def get_status(request: Request): + return worker.get_status() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--host", type=str, default="localhost") + parser.add_argument("--port", type=int, default=21002) + parser.add_argument("--worker-address", type=str, + default="http://localhost:21002") + parser.add_argument("--controller-address", type=str, + default="http://localhost:21001") + parser.add_argument("--model-name", type=str) + parser.add_argument("--sgl-endpoint", type=str) + parser.add_argument("--limit-model-concurrency", type=int, default=5) + parser.add_argument("--stream-interval", type=int, default=1) + parser.add_argument("--no-register", action="store_true") + args = parser.parse_args() + logger.info(f"args: {args}") + + worker = ModelWorker(args.controller_address, + args.worker_address, + args.sgl_endpoint, + worker_id, + args.no_register, + args.model_name) + uvicorn.run(app, host=args.host, port=args.port, log_level="info") diff --git a/llava/serve/test_message.py b/llava/serve/test_message.py new file mode 100644 index 0000000000000000000000000000000000000000..6b090faed0e630b03b2294545050f1f4f5032cad --- /dev/null +++ b/llava/serve/test_message.py @@ -0,0 +1,62 @@ +import argparse +import json + +import requests + +from llava.conversation import default_conversation + + +def main(): + if args.worker_address: + worker_addr = args.worker_address + else: + controller_addr = args.controller_address + ret = requests.post(controller_addr + "/refresh_all_workers") + ret = requests.post(controller_addr + "/list_models") + models = ret.json()["models"] + models.sort() + print(f"Models: {models}") + + ret = requests.post(controller_addr + "/get_worker_address", + json={"model": args.model_name}) + worker_addr = ret.json()["address"] + print(f"worker_addr: {worker_addr}") + + if worker_addr == "": + return + + conv = default_conversation.copy() + conv.append_message(conv.roles[0], args.message) + prompt = conv.get_prompt() + + headers = {"User-Agent": "LLaVA Client"} + pload = { + "model": args.model_name, + "prompt": prompt, + "max_new_tokens": args.max_new_tokens, + "temperature": 0.7, + "stop": conv.sep, + } + response = requests.post(worker_addr + "/worker_generate_stream", headers=headers, + json=pload, stream=True) + + print(prompt.replace(conv.sep, "\n"), end="") + for chunk in response.iter_lines(chunk_size=8192, decode_unicode=False, delimiter=b"\0"): + if chunk: + data = json.loads(chunk.decode("utf-8")) + output = data["text"].split(conv.sep)[-1] + print(output, end="\r") + print("") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--controller-address", type=str, default="http://localhost:21001") + parser.add_argument("--worker-address", type=str) + parser.add_argument("--model-name", type=str, default="facebook/opt-350m") + parser.add_argument("--max-new-tokens", type=int, default=32) + parser.add_argument("--message", type=str, default= + "Tell me a story with more than 1000 words.") + args = parser.parse_args() + + main() diff --git a/llava/train/llama_flash_attn_monkey_patch.py b/llava/train/llama_flash_attn_monkey_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..31db2eff8d1c4b3ae645583dfc5e156e818b6f1c --- /dev/null +++ b/llava/train/llama_flash_attn_monkey_patch.py @@ -0,0 +1,115 @@ +from typing import Optional, Tuple +import warnings + +import torch + +import transformers +from transformers.models.llama.modeling_llama import apply_rotary_pos_emb, repeat_kv + +try: + from flash_attn.flash_attn_interface import flash_attn_unpadded_qkvpacked_func +except ImportError: + from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func +from flash_attn.bert_padding import unpad_input, pad_input + + +def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.Tensor] = None, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + output_attentions: bool = False, + use_cache: bool = False, +) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + if output_attentions: + warnings.warn( + "Output attentions is not supported for patched `LlamaAttention`, returning `None` instead." + ) + + bsz, q_len, _ = hidden_states.size() + + query_states = ( + self.q_proj(hidden_states) + .view(bsz, q_len, self.num_heads, self.head_dim) + .transpose(1, 2) + ) + key_states = ( + self.k_proj(hidden_states) + .view(bsz, q_len, self.num_key_value_heads, self.head_dim) + .transpose(1, 2) + ) + value_states = ( + self.v_proj(hidden_states) + .view(bsz, q_len, self.num_key_value_heads, self.head_dim) + .transpose(1, 2) + ) # shape: (b, num_heads, s, head_dim) + + kv_seq_len = key_states.shape[-2] + if past_key_value is not None: + kv_seq_len += past_key_value[0].shape[-2] + + cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) + query_states, key_states = apply_rotary_pos_emb( + query_states, key_states, cos, sin, position_ids + ) + + if past_key_value is not None: + # reuse k, v + key_states = torch.cat([past_key_value[0], key_states], dim=2) + value_states = torch.cat([past_key_value[1], value_states], dim=2) + + past_key_value = (key_states, value_states) if use_cache else None + + # repeat k/v heads if n_kv_heads < n_heads + key_states = repeat_kv(key_states, self.num_key_value_groups) + value_states = repeat_kv(value_states, self.num_key_value_groups) + + # Transform the data into the format required by flash attention + qkv = torch.stack([query_states, key_states, value_states], dim=2) + qkv = qkv.transpose(1, 3) # shape: [b, s, 3, num_heads, head_dim] + key_padding_mask = attention_mask + + if key_padding_mask is None: + qkv = qkv.reshape(-1, 3, self.num_heads, self.head_dim) + cu_q_lens = torch.arange( + 0, (bsz + 1) * q_len, step=q_len, dtype=torch.int32, device=qkv.device + ) + max_s = q_len + output = flash_attn_unpadded_qkvpacked_func( + qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True + ) + output = output.view(bsz, q_len, -1) + else: + qkv = qkv.reshape(bsz, q_len, -1) + qkv, indices, cu_q_lens, max_s = unpad_input(qkv, key_padding_mask) + qkv = qkv.view(-1, 3, self.num_heads, self.head_dim) + output_unpad = flash_attn_unpadded_qkvpacked_func( + qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True + ) + output_unpad = output_unpad.reshape(-1, self.num_heads * self.head_dim) + output = pad_input(output_unpad, indices, bsz, q_len) + + return self.o_proj(output), None, past_key_value + + +# Disable the transformation of the attention mask in LlamaModel as the flash attention +# requires the attention mask to be the same as the key_padding_mask +def _prepare_decoder_attention_mask( + self, attention_mask, input_shape, inputs_embeds, past_key_values_length +): + # [bsz, seq_len] + return attention_mask + + +def replace_llama_attn_with_flash_attn(): + cuda_major, cuda_minor = torch.cuda.get_device_capability() + if cuda_major < 8: + warnings.warn( + "Flash attention is only supported on A100 or H100 GPU during training due to head dim > 64 backward." + "ref: https://github.com/HazyResearch/flash-attention/issues/190#issuecomment-1523359593" + ) + transformers.models.llama.modeling_llama.LlamaModel._prepare_decoder_attention_mask = ( + _prepare_decoder_attention_mask + ) + transformers.models.llama.modeling_llama.LlamaAttention.forward = forward diff --git a/llava/train/llama_xformers_attn_monkey_patch.py b/llava/train/llama_xformers_attn_monkey_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f8351e41ccd4a64dca237bd8f8be0702b23989dc --- /dev/null +++ b/llava/train/llama_xformers_attn_monkey_patch.py @@ -0,0 +1,129 @@ +""" +Directly copied the code from https://raw.githubusercontent.com/oobabooga/text-generation-webui/main/modules/llama_attn_hijack.py and made some adjustments +""" + +import logging +import math +from typing import Optional, Tuple + +import torch +import transformers.models.llama.modeling_llama +from torch import nn + +try: + import xformers.ops +except ImportError: + logging.error("xformers not found! Please install it before trying to use it.") + + +def replace_llama_attn_with_xformers_attn(): + transformers.models.llama.modeling_llama.LlamaAttention.forward = xformers_forward + + +def xformers_forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + output_attentions: bool = False, + use_cache: bool = False, +) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + # pylint: disable=duplicate-code + bsz, q_len, _ = hidden_states.size() + + query_states = ( + self.q_proj(hidden_states) + .view(bsz, q_len, self.num_heads, self.head_dim) + .transpose(1, 2) + ) + key_states = ( + self.k_proj(hidden_states) + .view(bsz, q_len, self.num_heads, self.head_dim) + .transpose(1, 2) + ) + value_states = ( + self.v_proj(hidden_states) + .view(bsz, q_len, self.num_heads, self.head_dim) + .transpose(1, 2) + ) + + kv_seq_len = key_states.shape[-2] + if past_key_value is not None: + kv_seq_len += past_key_value[0].shape[-2] + cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) + ( + query_states, + key_states, + ) = transformers.models.llama.modeling_llama.apply_rotary_pos_emb( + query_states, key_states, cos, sin, position_ids + ) + # [bsz, nh, t, hd] + + if past_key_value is not None: + # reuse k, v, self_attention + key_states = torch.cat([past_key_value[0], key_states], dim=2) + value_states = torch.cat([past_key_value[1], value_states], dim=2) + + past_key_value = (key_states, value_states) if use_cache else None + + # We only apply xformers optimizations if we don't need to output the whole attention matrix + if not output_attentions: + query_states = query_states.transpose(1, 2) + key_states = key_states.transpose(1, 2) + value_states = value_states.transpose(1, 2) + + # This is a nasty hack. We know attention_mask in transformers is either LowerTriangular or all Zeros. + # We therefore check if one element in the upper triangular portion is zero. If it is, then the mask is all zeros. + if attention_mask is None or attention_mask[0, 0, 0, 1] == 0: + # input and output should be of form (bsz, q_len, num_heads, head_dim) + attn_output = xformers.ops.memory_efficient_attention( + query_states, key_states, value_states, attn_bias=None + ) + else: + # input and output should be of form (bsz, q_len, num_heads, head_dim) + attn_output = xformers.ops.memory_efficient_attention( + query_states, + key_states, + value_states, + attn_bias=xformers.ops.LowerTriangularMask(), + ) + attn_weights = None + else: + attn_weights = torch.matmul( + query_states, key_states.transpose(2, 3) + ) / math.sqrt(self.head_dim) + + if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len): + raise ValueError( + f"Attention weights should be of size {(bsz * self.num_heads, q_len, kv_seq_len)}, but is" + f" {attn_weights.size()}" + ) + + if attention_mask is not None: + if attention_mask.size() != (bsz, 1, q_len, kv_seq_len): + raise ValueError( + f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}" + ) + attn_weights = attn_weights + attention_mask + attn_weights = torch.max( + attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min) + ) + + # upcast attention to fp32 + attn_weights = nn.functional.softmax( + attn_weights, dim=-1, dtype=torch.float32 + ).to(query_states.dtype) + attn_output = torch.matmul(attn_weights, value_states) + + if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim): + raise ValueError( + f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is" + f" {attn_output.size()}" + ) + + attn_output = attn_output.transpose(1, 2) + + attn_output = attn_output.reshape(bsz, q_len, self.hidden_size) + attn_output = self.o_proj(attn_output) + return attn_output, attn_weights, past_key_value diff --git a/llava/train/llava2parquet_to_Luke.py b/llava/train/llava2parquet_to_Luke.py new file mode 100644 index 0000000000000000000000000000000000000000..e0aef5155b59956db43811ac39ff5de984015bd7 --- /dev/null +++ b/llava/train/llava2parquet_to_Luke.py @@ -0,0 +1,72 @@ +import json +import pyarrow as pa +import pyarrow.parquet as pq +import pandas as pd +import os +from concurrent.futures import ThreadPoolExecutor, as_completed +from tqdm import tqdm + + +def process_item(item): + # Read the image and convert it to byte format + with open(item["image"], "rb") as img_file: + img_bytes = img_file.read() + + record = { + "image": img_bytes, + "conversations": json.dumps(item["conversations"]) # Serialize as JSON string + } + return record + + +# Read the JSON file +with open('merged_half.json', 'r') as file: + data = json.load(file) + +local_path = 'merged_first_half.parquet' + +# Get the number of CPU cores in the system +cpu_count = os.cpu_count() + +# Process data in batches +batch_size = 100000 # Can be adjusted based on actual needs +num_batches = (len(data) + batch_size - 1) // batch_size + +# Local file path +# local_path = 'final_data_4ch.parquet' + +# Initialize ParquetWriter +with open(local_path, 'wb') as local_file: + writer = None + + for batch_index in range(num_batches): + start_index = batch_index * batch_size + end_index = min((batch_index + 1) * batch_size, len(data)) + batch_data = data[start_index:end_index] + + # Use ThreadPoolExecutor for parallel processing + records = [] + with ThreadPoolExecutor(max_workers=cpu_count) as executor: + future_to_record = {executor.submit(process_item, item): item for item in batch_data} + for future in tqdm(as_completed(future_to_record), total=len(future_to_record), + desc=f"Processing Batch {batch_index + 1}/{num_batches}"): + try: + record = future.result() + records.append(record) + except Exception as exc: + print(f'Generated an exception: {exc}') + + # Create a PyArrow table + table = pa.Table.from_pandas(pd.DataFrame(records)) + + # If it's the first batch, set the writer and schema + if writer is None: + writer = pq.ParquetWriter(local_file, table.schema, version='2.6', use_dictionary=True, compression='snappy') + + # Write to the Parquet file in chunks + for i in tqdm(range(0, len(table), 4), desc=f"Writing Batch {batch_index + 1}/{num_batches} to Parquet"): + writer.write_table(table.slice(i, 4)) + + writer.close() + +print("Completed: Batches saved as Parquet files to local directory") diff --git a/llava/train/llava_trainer.py b/llava/train/llava_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..488bf61f85b31a356b5560e89a74f5d68e889dc9 --- /dev/null +++ b/llava/train/llava_trainer.py @@ -0,0 +1,261 @@ +import os +import torch +import torch.nn as nn + +from torch.utils.data import Sampler +from torch.utils.data.sampler import SequentialSampler + +from transformers import Trainer +from transformers.trainer import ( + is_sagemaker_mp_enabled, + get_parameter_names, + has_length, + ALL_LAYERNORM_LAYERS, + logger, +) +from typing import List, Optional + + +def maybe_zero_3(param, ignore_status=False, name=None): + from deepspeed import zero + from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus + if hasattr(param, "ds_id"): + if param.ds_status == ZeroParamStatus.NOT_AVAILABLE: + if not ignore_status: + print(name, 'no ignore status') + with zero.GatheredParameters([param]): + param = param.data.detach().cpu().clone() + else: + param = param.detach().cpu().clone() + return param + + +def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match): + to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)} + to_return = {k: maybe_zero_3(v, ignore_status=True, name=k).cpu() for k, v in to_return.items()} + return to_return + + +def split_to_even_chunks(indices, lengths, num_chunks): + """ + Split a list of indices into `chunks` chunks of roughly equal lengths. + """ + + if len(indices) % num_chunks != 0: + return [indices[i::num_chunks] for i in range(num_chunks)] + + num_indices_per_chunk = len(indices) // num_chunks + + chunks = [[] for _ in range(num_chunks)] + chunks_lengths = [0 for _ in range(num_chunks)] + for index in indices: + shortest_chunk = chunks_lengths.index(min(chunks_lengths)) + chunks[shortest_chunk].append(index) + chunks_lengths[shortest_chunk] += lengths[index] + if len(chunks[shortest_chunk]) == num_indices_per_chunk: + chunks_lengths[shortest_chunk] = float("inf") + + return chunks + + +def get_modality_length_grouped_indices(lengths, batch_size, world_size, generator=None): + # We need to use torch for the random part as a distributed sampler will set the random seed for torch. + assert all(l != 0 for l in lengths), "Should not have zero length." + if all(l > 0 for l in lengths) or all(l < 0 for l in lengths): + # all samples are in the same modality + return get_length_grouped_indices(lengths, batch_size, world_size, generator=generator) + mm_indices, mm_lengths = zip(*[(i, l) for i, l in enumerate(lengths) if l > 0]) + lang_indices, lang_lengths = zip(*[(i, -l) for i, l in enumerate(lengths) if l < 0]) + + mm_shuffle = [mm_indices[i] for i in get_length_grouped_indices(mm_lengths, batch_size, world_size, generator=None)] + lang_shuffle = [lang_indices[i] for i in get_length_grouped_indices(lang_lengths, batch_size, world_size, generator=None)] + megabatch_size = world_size * batch_size + mm_megabatches = [mm_shuffle[i : i + megabatch_size] for i in range(0, len(mm_shuffle), megabatch_size)] + lang_megabatches = [lang_shuffle[i : i + megabatch_size] for i in range(0, len(lang_shuffle), megabatch_size)] + + last_mm = mm_megabatches[-1] + last_lang = lang_megabatches[-1] + additional_batch = last_mm + last_lang + megabatches = mm_megabatches[:-1] + lang_megabatches[:-1] + megabatch_indices = torch.randperm(len(megabatches), generator=generator) + megabatches = [megabatches[i] for i in megabatch_indices] + + if len(additional_batch) > 0: + megabatches.append(sorted(additional_batch)) + + return [i for megabatch in megabatches for i in megabatch] + + +def get_length_grouped_indices(lengths, batch_size, world_size, generator=None, merge=True): + # We need to use torch for the random part as a distributed sampler will set the random seed for torch. + indices = torch.randperm(len(lengths), generator=generator) + megabatch_size = world_size * batch_size + megabatches = [indices[i : i + megabatch_size].tolist() for i in range(0, len(lengths), megabatch_size)] + megabatches = [sorted(megabatch, key=lambda i: lengths[i], reverse=True) for megabatch in megabatches] + megabatches = [split_to_even_chunks(megabatch, lengths, world_size) for megabatch in megabatches] + + return [i for megabatch in megabatches for batch in megabatch for i in batch] + + +class LengthGroupedSampler(Sampler): + r""" + Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while + keeping a bit of randomness. + """ + + def __init__( + self, + batch_size: int, + world_size: int, + lengths: Optional[List[int]] = None, + generator=None, + group_by_modality: bool = False, + ): + if lengths is None: + raise ValueError("Lengths must be provided.") + + self.batch_size = batch_size + self.world_size = world_size + self.lengths = lengths + self.generator = generator + self.group_by_modality = group_by_modality + + def __len__(self): + return len(self.lengths) + + def __iter__(self): + if self.group_by_modality: + indices = get_modality_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator) + else: + indices = get_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator) + return iter(indices) + + +class LLaVATrainer(Trainer): + + def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]: + + + + if self.train_dataset is None or not has_length(self.train_dataset): + return None + + return SequentialSampler(self.train_dataset) + + if self.args.group_by_modality_length: + lengths = self.train_dataset.modality_lengths + return LengthGroupedSampler( + self.args.train_batch_size, + world_size=self.args.world_size * self.args.gradient_accumulation_steps, + lengths=lengths, + group_by_modality=True, + ) + else: + return super()._get_train_sampler() + + def create_optimizer(self): + """ + Setup the optimizer. + + We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the + Trainer's init through `optimizers`, or subclass and override this method in a subclass. + """ + if is_sagemaker_mp_enabled(): + return super().create_optimizer() + + opt_model = self.model + + if self.optimizer is None: + decay_parameters = get_parameter_names(opt_model, ALL_LAYERNORM_LAYERS) + decay_parameters = [name for name in decay_parameters if "bias" not in name] + if self.args.mm_projector_lr is not None: + projector_parameters = [name for name, _ in opt_model.named_parameters() if "mm_projector" in name] + optimizer_grouped_parameters = [ + { + "params": [ + p for n, p in opt_model.named_parameters() if (n in decay_parameters and n not in projector_parameters and p.requires_grad) + ], + "weight_decay": self.args.weight_decay, + }, + { + "params": [ + p for n, p in opt_model.named_parameters() if (n not in decay_parameters and n not in projector_parameters and p.requires_grad) + ], + "weight_decay": 0.0, + }, + { + "params": [ + p for n, p in opt_model.named_parameters() if (n in decay_parameters and n in projector_parameters and p.requires_grad) + ], + "weight_decay": self.args.weight_decay, + "lr": self.args.mm_projector_lr, + }, + { + "params": [ + p for n, p in opt_model.named_parameters() if (n not in decay_parameters and n in projector_parameters and p.requires_grad) + ], + "weight_decay": 0.0, + "lr": self.args.mm_projector_lr, + }, + ] + else: + optimizer_grouped_parameters = [ + { + "params": [ + p for n, p in opt_model.named_parameters() if (n in decay_parameters and p.requires_grad) + ], + "weight_decay": self.args.weight_decay, + }, + { + "params": [ + p for n, p in opt_model.named_parameters() if (n not in decay_parameters and p.requires_grad) + ], + "weight_decay": 0.0, + }, + ] + + optimizer_cls, optimizer_kwargs = Trainer.get_optimizer_cls_and_kwargs(self.args) + + self.optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs) + if optimizer_cls.__name__ == "Adam8bit": + import bitsandbytes + + manager = bitsandbytes.optim.GlobalOptimManager.get_instance() + + skipped = 0 + for module in opt_model.modules(): + if isinstance(module, nn.Embedding): + skipped += sum({p.data_ptr(): p.numel() for p in module.parameters()}.values()) + logger.info(f"skipped {module}: {skipped/2**20}M params") + manager.register_module_override(module, "weight", {"optim_bits": 32}) + logger.debug(f"bitsandbytes: will optimize {module} in fp32") + logger.info(f"skipped: {skipped/2**20}M params") + + return self.optimizer + + def _save_checkpoint(self, model, trial, metrics=None): + if getattr(self.args, 'tune_mm_mlp_adapter', False): + from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR + checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}" + + run_dir = self._get_output_dir(trial=trial) + output_dir = os.path.join(run_dir, checkpoint_folder) + + # Only save Adapter + keys_to_match = ['mm_projector', 'vision_resampler'] + if getattr(self.args, "use_im_start_end", False): + keys_to_match.extend(['embed_tokens', 'embed_in']) + + weight_to_save = get_mm_adapter_state_maybe_zero_3(self.model.named_parameters(), keys_to_match) + + if self.args.local_rank == 0 or self.args.local_rank == -1: + self.model.config.save_pretrained(output_dir) + torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin')) + else: + super(LLaVATrainer, self)._save_checkpoint(model, trial, metrics) + + def _save(self, output_dir: Optional[str] = None, state_dict=None): + if getattr(self.args, 'tune_mm_mlp_adapter', False): + pass + else: + super(LLaVATrainer, self)._save(output_dir, state_dict) diff --git a/llava/train/train.py b/llava/train/train.py new file mode 100644 index 0000000000000000000000000000000000000000..f1b538d9adb4474402f3e399ed20c235db6b6c5b --- /dev/null +++ b/llava/train/train.py @@ -0,0 +1,1132 @@ +# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright: +# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright: +# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +from dataclasses import dataclass, field +import json +import logging +import pathlib +from typing import Dict, Optional, Sequence, List +import boto3 +import pyarrow.parquet as pq +import pandas as pd +import fsspec +import s3fs +import io +import torch + +import transformers +import tokenizers + +from llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from torch.utils.data import Dataset +from llava.train.llava_trainer import LLaVATrainer + +from llava import conversation as conversation_lib +from llava.model import * +from llava.mm_utils import tokenizer_image_token,process_anyres_ui_image + +from PIL import Image + +import os +# LOCAL_RANK = int(os.environ['LOCAL_RANK']) + +local_rank = None + + +def rank0_print(*args): + if local_rank == 0: + print(*args) + + +from packaging import version +IS_TOKENIZER_GREATER_THAN_0_14 = version.parse(tokenizers.__version__) >= version.parse('0.14') + + +@dataclass +class ModelArguments: + model_name_or_path: Optional[str] = field(default="facebook/opt-125m") + version: Optional[str] = field(default="v0") + freeze_backbone: bool = field(default=False) + tune_mm_mlp_adapter: bool = field(default=False) + vision_tower: Optional[str] = field(default=None) + mm_vision_select_layer: Optional[int] = field(default=-1) # default to the last layer + pretrain_mm_mlp_adapter: Optional[str] = field(default=None) + mm_projector_type: Optional[str] = field(default='mlp2x_gelu') + mm_use_im_start_end: bool = field(default=False) + mm_use_im_patch_token: bool = field(default=True) + mm_patch_merge_type: Optional[str] = field(default='spatial') + mm_vision_select_feature: Optional[str] = field(default="patch") + + +@dataclass +class DataArguments: + data_path: str = field(default=None, + metadata={"help": "Path to the training data."}) + lazy_preprocess: bool = False + is_multimodal: bool = False + image_folder: Optional[str] = field(default=None) + image_aspect_ratio: str = 'square' + + +@dataclass +class TrainingArguments(transformers.TrainingArguments): + cache_dir: Optional[str] = field(default=None) + optim: str = field(default="adamw_torch") + remove_unused_columns: bool = field(default=False) + freeze_mm_mlp_adapter: bool = field(default=False) + mpt_attn_impl: Optional[str] = field(default="triton") + model_max_length: int = field( + default=512, + metadata={ + "help": + "Maximum sequence length. Sequences will be right padded (and possibly truncated)." + }, + ) + double_quant: bool = field( + default=True, + metadata={"help": "Compress the quantization statistics through double quantization."} + ) + quant_type: str = field( + default="nf4", + metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."} + ) + bits: int = field( + default=16, + metadata={"help": "How many bits to use."} + ) + lora_enable: bool = False + lora_r: int = 64 + lora_alpha: int = 16 + lora_dropout: float = 0.05 + lora_weight_path: str = "" + lora_bias: str = "none" + mm_projector_lr: Optional[float] = None + group_by_modality_length: bool = field(default=False) + + +def maybe_zero_3(param, ignore_status=False, name=None): + from deepspeed import zero + from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus + if hasattr(param, "ds_id"): + if param.ds_status == ZeroParamStatus.NOT_AVAILABLE: + if not ignore_status: + logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}") + with zero.GatheredParameters([param]): + param = param.data.detach().cpu().clone() + else: + param = param.detach().cpu().clone() + return param + + +# Borrowed from peft.utils.get_peft_model_state_dict +def get_peft_state_maybe_zero_3(named_params, bias): + if bias == "none": + to_return = {k: t for k, t in named_params if "lora_" in k} + elif bias == "all": + to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k} + elif bias == "lora_only": + to_return = {} + maybe_lora_bias = {} + lora_bias_names = set() + for k, t in named_params: + if "lora_" in k: + to_return[k] = t + bias_name = k.split("lora_")[0] + "bias" + lora_bias_names.add(bias_name) + elif "bias" in k: + maybe_lora_bias[k] = t + for k, t in maybe_lora_bias: + if bias_name in lora_bias_names: + to_return[bias_name] = t + else: + raise NotImplementedError + to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()} + return to_return + + +def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True): + to_return = {k: t for k, t in named_params if "lora_" not in k} + if require_grad_only: + to_return = {k: t for k, t in to_return.items() if t.requires_grad} + to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} + return to_return + + +def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match): + to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)} + to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} + return to_return + + +def find_all_linear_names(model): + cls = torch.nn.Linear + lora_module_names = set() + multimodal_keywords = ['mm_projector', 'vision_tower', 'vision_resampler'] + for name, module in model.named_modules(): + if any(mm_keyword in name for mm_keyword in multimodal_keywords): + continue + if isinstance(module, cls): + names = name.split('.') + lora_module_names.add(names[0] if len(names) == 1 else names[-1]) + + if 'lm_head' in lora_module_names: # needed for 16-bit + lora_module_names.remove('lm_head') + return list(lora_module_names) + + +def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, + output_dir: str): + """Collects the state dict and dump to disk.""" + + if getattr(trainer.args, "tune_mm_mlp_adapter", False): + # Only save Adapter + keys_to_match = ['mm_projector'] + if getattr(trainer.args, "use_im_start_end", False): + keys_to_match.extend(['embed_tokens', 'embed_in']) + + weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match) + trainer.model.config.save_pretrained(output_dir) + + current_folder = output_dir.split('/')[-1] + parent_folder = os.path.dirname(output_dir) + if trainer.args.local_rank == 0 or trainer.args.local_rank == -1: + if current_folder.startswith('checkpoint-'): + mm_projector_folder = os.path.join(parent_folder, "mm_projector") + os.makedirs(mm_projector_folder, exist_ok=True) + torch.save(weight_to_save, os.path.join(mm_projector_folder, f'{current_folder}.bin')) + else: + torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin')) + return + + if trainer.deepspeed: + torch.cuda.synchronize() + trainer.save_model(output_dir) + return + + state_dict = trainer.model.state_dict() + if trainer.args.should_save: + cpu_state_dict = { + key: value.cpu() + for key, value in state_dict.items() + } + del state_dict + trainer._save(output_dir, state_dict=cpu_state_dict) # noqa + + +def smart_tokenizer_and_embedding_resize( + special_tokens_dict: Dict, + tokenizer: transformers.PreTrainedTokenizer, + model: transformers.PreTrainedModel, +): + """Resize tokenizer and embedding. + + Note: This is the unoptimized version that may make your embedding size not be divisible by 64. + """ + num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict) + model.resize_token_embeddings(len(tokenizer)) + + if num_new_tokens > 0: + input_embeddings = model.get_input_embeddings().weight.data + output_embeddings = model.get_output_embeddings().weight.data + + input_embeddings_avg = input_embeddings[:-num_new_tokens].mean( + dim=0, keepdim=True) + output_embeddings_avg = output_embeddings[:-num_new_tokens].mean( + dim=0, keepdim=True) + + input_embeddings[-num_new_tokens:] = input_embeddings_avg + output_embeddings[-num_new_tokens:] = output_embeddings_avg + + +def _tokenize_fn(strings: Sequence[str], + tokenizer: transformers.PreTrainedTokenizer) -> Dict: + """Tokenize a list of strings.""" + tokenized_list = [ + tokenizer( + text, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ) for text in strings + ] + input_ids = labels = [ + tokenized.input_ids[0] for tokenized in tokenized_list + ] + input_ids_lens = labels_lens = [ + tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() + for tokenized in tokenized_list + ] + return dict( + input_ids=input_ids, + labels=labels, + input_ids_lens=input_ids_lens, + labels_lens=labels_lens, + ) + + +def _mask_targets(target, tokenized_lens, speakers): + # cur_idx = 0 + cur_idx = tokenized_lens[0] + tokenized_lens = tokenized_lens[1:] + target[:cur_idx] = IGNORE_INDEX + for tokenized_len, speaker in zip(tokenized_lens, speakers): + if speaker == "human": + target[cur_idx+2:cur_idx + tokenized_len] = IGNORE_INDEX + cur_idx += tokenized_len + + +def _add_speaker_and_signal(header, source, get_conversation=True): + """Add speaker and start/end signal on each round.""" + BEGIN_SIGNAL = "### " + END_SIGNAL = "\n" + conversation = header + for sentence in source: + from_str = sentence["from"] + if from_str.lower() == "human": + from_str = conversation_lib.default_conversation.roles[0] + elif from_str.lower() == "gpt": + from_str = conversation_lib.default_conversation.roles[1] + else: + from_str = 'unknown' + sentence["value"] = (BEGIN_SIGNAL + from_str + ": " + + sentence["value"] + END_SIGNAL) + if get_conversation: + conversation += sentence["value"] + conversation += BEGIN_SIGNAL + return conversation + + +def preprocess_multimodal( + sources: Sequence[str], + data_args: DataArguments +) -> Dict: + is_multimodal = data_args.is_multimodal + if not is_multimodal: + return sources + + for source in sources: + for sentence in source: + if DEFAULT_IMAGE_TOKEN in sentence['value']: + sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '').strip() + sentence['value'] = DEFAULT_IMAGE_TOKEN + '\n' + sentence['value'] + sentence['value'] = sentence['value'].strip() + if "mmtag" in conversation_lib.default_conversation.version: + sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '' + DEFAULT_IMAGE_TOKEN + '') + replace_token = DEFAULT_IMAGE_TOKEN + if data_args.mm_use_im_start_end: + replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN + sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token) + + return sources + + +def preprocess_llama_2( + sources, + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False +) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + + assert conv.sep_style == conversation_lib.SeparatorStyle.LLAMA_2 + + # Mask targets + sep = "[/INST] " + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep2) + cur_len = 1 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 2 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print( + f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." + f" (ignored)" + ) + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_v1( + sources, + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False +) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + + assert conv.sep_style == conversation_lib.SeparatorStyle.TWO + + # Mask targets + sep = conv.sep + conv.roles[1] + ": " + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep2) + cur_len = 1 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 2 + + if i != 0 and not tokenizer.legacy and IS_TOKENIZER_GREATER_THAN_0_14: + round_len -= 1 + instruction_len -= 1 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print( + f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." + f" (ignored)" + ) + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_mpt( + sources, + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False +) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + assert conv.sep_style == conversation_lib.SeparatorStyle.MPT + + # Mask targets + sep = conv.sep + conv.roles[1] + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep) + re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt + for conv_idx in range(3, len(rounds), 2): + re_rounds.append(conv.sep.join(rounds[conv_idx:conv_idx+2])) # user + gpt + cur_len = 0 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(re_rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 1 + + if i != 0 and getattr(tokenizer, 'legacy', False) and IS_TOKENIZER_GREATER_THAN_0_14: + round_len += 1 + instruction_len += 1 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print( + f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." + f" (ignored)" + ) + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_plain( + sources: Sequence[str], + tokenizer: transformers.PreTrainedTokenizer, +) -> Dict: + # add end signal and concatenate together + conversations = [] + for source in sources: + assert len(source) == 2 + assert DEFAULT_IMAGE_TOKEN in source[0]['value'] + source[0]['value'] = DEFAULT_IMAGE_TOKEN + conversation = source[0]['value'] + source[1]['value'] + conversation_lib.default_conversation.sep + conversations.append(conversation) + # tokenize conversations + input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations] + targets = copy.deepcopy(input_ids) + for target, source in zip(targets, sources): + tokenized_len = len(tokenizer_image_token(source[0]['value'], tokenizer)) + target[:tokenized_len] = IGNORE_INDEX + + return dict(input_ids=input_ids, labels=targets) + + +def preprocess( + sources: Sequence[str], + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False +) -> Dict: + """ + Given a list of sources, each is a conversation list. This transform: + 1. Add signal '### ' at the beginning each sentence, with end signal '\n'; + 2. Concatenate conversations together; + 3. Tokenize the concatenated conversation; + 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX. + """ + if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN: + return preprocess_plain(sources, tokenizer) + if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.LLAMA_2: + return preprocess_llama_2(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version.startswith("v1"): + return preprocess_v1(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version == "mpt": + return preprocess_mpt(sources, tokenizer, has_image=has_image) + # add end signal and concatenate together + conversations = [] + for source in sources: + header = f"{conversation_lib.default_conversation.system}\n\n" + conversation = _add_speaker_and_signal(header, source) + conversations.append(conversation) + # tokenize conversations + def get_tokenize_len(prompts): + return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts] + + if has_image: + input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations] + else: + conversations_tokenized = _tokenize_fn(conversations, tokenizer) + input_ids = conversations_tokenized["input_ids"] + + targets = copy.deepcopy(input_ids) + for target, source in zip(targets, sources): + if has_image: + tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source]) + else: + tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"] + speakers = [sentence["from"] for sentence in source] + _mask_targets(target, tokenized_lens, speakers) + + return dict(input_ids=input_ids, labels=targets) + +class LazySupervisedDataset(Dataset): + def __init__(self, data_path: str, + tokenizer: transformers.PreTrainedTokenizer, + data_args: DataArguments, + chunk_size: int = 4): + super(LazySupervisedDataset, self).__init__() + self.data_path = data_path + self.tokenizer = tokenizer + self.data_args = data_args + self.chunk_size = chunk_size + + # Setup S3 filesystem + self.s3 = s3fs.S3FileSystem() + + self.f = self.s3.open(self.data_path, 'rb') + # self.parquet_file = pq.ParquetFile(self.f, buffer_size=2048) + self.parquet_file = pq.ParquetFile(self.f) + self.metadata = self.parquet_file.metadata + + # Get total number of rows without loading the entire file + # with open(self.data_path, 'rb') as f: + self.total_rows = sum(self.metadata.row_group(i).num_rows for i in range(self.metadata.num_row_groups)) + + # rank0_print("Formatting inputs...Skip in lazy mode") + + def __len__(self): + + # rank0_print(f"Getting Length: {self.total_rows}") + return self.total_rows + + def __getitem__(self, idx): + + # rank0_print(f"Getting item at index: {idx}") + + if isinstance(idx, int): + try: + + return self._get_single_item(idx) + except Exception as e: + print(e) + self.f = self.s3.open(self.data_path, 'rb') + # self.parquet_file = pq.ParquetFile(self.f, buffer_size=2048) + self.parquet_file = pq.ParquetFile(self.f) + return self._get_single_item(idx) + + elif isinstance(idx, slice): + try: + return [self._get_single_item(i) for i in range(*idx.indices(len(self)))] + except Exception as e: + print(e) + self.f = self.s3.open(self.data_path, 'rb') + # self.parquet_file = pq.ParquetFile(self.f, buffer_size=2048) + self.parquet_file = pq.ParquetFile(self.f) + return [self._get_single_item(i) for i in range(*idx.indices(len(self)))] + else: + raise TypeError("Invalid argument type") + + def _get_single_item(self, idx): + + rank0_print(f"Getting single item at index: {idx}") + chunk_idx = idx // self.chunk_size + row_idx = idx % self.chunk_size + + # with open(self.data_path, 'rb') as f: + # num_row_groups = parquet_file.num_row_groups + # row_group_size = self.chunk_size + # if chunk_idx >= num_row_groups: + # raise IndexError(f"chunk_idx {chunk_idx} out of bounds {num_row_groups}") + + # target_row_group = chunk_idx * self.chunk_size // row_group_size + table = self.parquet_file.read_row_group(chunk_idx) + chunk = table.to_pandas() + + # if chunk_idx == num_row_groups - 1: + # row_group_size = len(chunk) + # if row_idx >= row_group_size: + # raise IndexError(f"row_idx {row_idx} out of bounds {row_group_size}") + # else: + # if row_idx >= self.chunk_size: + # raise IndexError(f"row_idx {row_idx} out of bounds {row_group_size}") + + # start_row = (chunk_idx * self.chunk_size) % row_group_size + # end_row = start_row + self.chunk_size + # chunk = chunk.iloc[start_row:end_row] + + sample = chunk.iloc[row_idx] + + # Process the sample as before + sources = json.loads(sample['conversations']) + + if isinstance(idx, int): + sources = [sources] + + if 'image' in sample: + image_bytes = sample['image'] + image = Image.open(io.BytesIO(image_bytes)).convert('RGB') + + if self.data_args.image_aspect_ratio == 'pad': + def expand2square(pil_img, background_color): + width, height = pil_img.size + if width == height: + return pil_img + elif width > height: + result = Image.new(pil_img.mode, (width, width), background_color) + result.paste(pil_img, (0, (width - height) // 2)) + return result + else: + result = Image.new(pil_img.mode, (height, height), background_color) + result.paste(pil_img, ((height - width) // 2, 0)) + return result + + image = expand2square(image, tuple(int(x * 255) for x in self.data_args.image_processor.image_mean)) + image = self.data_args.image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0] + elif self.data_args.image_aspect_ratio == 'square': + image = self.data_args.image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0] + elif self.data_args.image_aspect_ratio == 'anyres_ui': + image, new_size = process_anyres_ui_image(image, self.data_args.image_processor, fusion=False) + elif self.data_args.image_aspect_ratio == 'anyres_ui_fusion': + image, new_size = process_anyres_ui_image(image, self.data_args.image_processor, fusion=True) + sources = preprocess_multimodal( + copy.deepcopy([e for e in sources]), + self.data_args) + else: + sources = copy.deepcopy([e for e in sources]) + + data_dict = preprocess( + sources, + self.tokenizer, + has_image=('image' in sample)) + if isinstance(idx, int): + data_dict = dict(input_ids=data_dict["input_ids"][0], + labels=data_dict["labels"][0]) + + # image exist in the data + if 'image' in sample: + data_dict['image'] = image + if ( + self.data_args.image_aspect_ratio == 'anyres_ui' or self.data_args.image_aspect_ratio == 'anyres_ui_fusion'): + data_dict['image_size'] = new_size + else: + data_dict['image_size'] = (0, 0) + + elif self.data_args.is_multimodal: + crop_size = self.data_args.image_processor.crop_size + data_dict['image'] = torch.zeros(3, crop_size['height'], crop_size['width']) + data_dict['image_size'] = (crop_size['height'], crop_size['width']) + return data_dict + + @property + def lengths(self): + + rank0_print(f"Getting lengths property function") + return LazyList(self._get_length, self.total_rows) + + def _get_length(self, idx): + rank0_print(f"Getting __get_length property function {idx}") + sample = self._get_single_item(idx) + img_tokens = 128 if 'image' in sample else 0 + return sum(len(conv['value'].split()) for conv in json.loads(sample['conversations'])) + img_tokens + @property + def modality_lengths(self): + rank0_print(f"Getting modality_lengths property function") + return LazyList(self._get_modality_length, self.total_rows) + def _get_modality_length(self, idx): + rank0_print(f"Getting get_modality_length property function {idx}") + sample = self._get_single_item(idx) + cur_len = sum(len(conv['value'].split()) for conv in json.loads(sample['conversations'])) + return cur_len if 'image' in sample else -cur_len + + +@dataclass +class DataCollatorForSupervisedDataset(object): + """Collate examples for supervised fine-tuning.""" + + tokenizer: transformers.PreTrainedTokenizer + + def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]: + input_ids, labels = tuple([instance[key] for instance in instances] + for key in ("input_ids", "labels")) + input_ids = torch.nn.utils.rnn.pad_sequence( + input_ids, + batch_first=True, + padding_value=self.tokenizer.pad_token_id) + labels = torch.nn.utils.rnn.pad_sequence(labels, + batch_first=True, + padding_value=IGNORE_INDEX) + input_ids = input_ids[:, :self.tokenizer.model_max_length] + labels = labels[:, :self.tokenizer.model_max_length] + batch = dict( + input_ids=input_ids, + labels=labels, + attention_mask=input_ids.ne(self.tokenizer.pad_token_id), + ) + + if 'image' in instances[0]: + images = [instance['image'] for instance in instances] + # if all(x is not None and x.shape == images[0].shape for x in images): + # batch['images'] = torch.stack(images) + # else: + # batch['images'] = images + + batch['images'] = images + batch['image_sizes'] = [instance['image_size'] for instance in instances] + # print(f"DEBUG batch['image_sizes'] {batch['image_sizes']}") + + return batch +def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, + data_args) -> Dict: + """Make dataset and collator for supervised fine-tuning.""" + train_dataset = LazySupervisedDataset(tokenizer=tokenizer, + data_path=data_args.data_path, + data_args=data_args) + data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer) + return dict(train_dataset=train_dataset, + eval_dataset=None, + data_collator=data_collator) + +class LazyList: + def __init__(self, get_item_func, length): + self.get_item_func = get_item_func + self.length = length + + def __getitem__(self, idx): + return self.get_item_func(idx) + + def __len__(self): + return self.length + +def train(attn_implementation=None): + global local_rank + + parser = transformers.HfArgumentParser( + (ModelArguments, DataArguments, TrainingArguments)) + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + local_rank = training_args.local_rank + compute_dtype = (torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)) + + bnb_model_from_pretrained_args = {} + if training_args.bits in [4, 8]: + from transformers import BitsAndBytesConfig + bnb_model_from_pretrained_args.update(dict( + device_map={"": training_args.device}, + load_in_4bit=training_args.bits == 4, + load_in_8bit=training_args.bits == 8, + quantization_config=BitsAndBytesConfig( + load_in_4bit=training_args.bits == 4, + load_in_8bit=training_args.bits == 8, + llm_int8_skip_modules=["mm_projector"], + llm_int8_threshold=6.0, + llm_int8_has_fp16_weight=False, + bnb_4bit_compute_dtype=compute_dtype, + bnb_4bit_use_double_quant=training_args.double_quant, + bnb_4bit_quant_type=training_args.quant_type # {'fp4', 'nf4'} + ) + )) + + if model_args.vision_tower is not None: + if 'mpt' in model_args.model_name_or_path: + config = transformers.AutoConfig.from_pretrained(model_args.model_name_or_path, trust_remote_code=True) + config.attn_config['attn_impl'] = training_args.mpt_attn_impl + model = LlavaMptForCausalLM.from_pretrained( + model_args.model_name_or_path, + config=config, + cache_dir=training_args.cache_dir, + **bnb_model_from_pretrained_args + ) + else: + model = LlavaLlamaForCausalLM.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + attn_implementation=attn_implementation, + torch_dtype=(torch.bfloat16 if training_args.bf16 else None), + **bnb_model_from_pretrained_args + ) + else: + model = transformers.LlamaForCausalLM.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + attn_implementation=attn_implementation, + torch_dtype=(torch.bfloat16 if training_args.bf16 else None), + **bnb_model_from_pretrained_args + ) + model.config.use_cache = False + + if model_args.freeze_backbone: + model.model.requires_grad_(False) + + if training_args.bits in [4, 8]: + from peft import prepare_model_for_kbit_training + model.config.torch_dtype=(torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)) + model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing) + + if training_args.gradient_checkpointing: + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if training_args.lora_enable: + from peft import LoraConfig, get_peft_model + lora_config = LoraConfig( + r=training_args.lora_r, + lora_alpha=training_args.lora_alpha, + target_modules=find_all_linear_names(model), + lora_dropout=training_args.lora_dropout, + bias=training_args.lora_bias, + task_type="CAUSAL_LM", + ) + if training_args.bits == 16: + if training_args.bf16: + model.to(torch.bfloat16) + if training_args.fp16: + model.to(torch.float16) + rank0_print("Adding LoRA adapters...") + model = get_peft_model(model, lora_config) + + if 'mpt' in model_args.model_name_or_path: + tokenizer = transformers.AutoTokenizer.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + model_max_length=training_args.model_max_length, + padding_side="right" + ) + else: + tokenizer = transformers.AutoTokenizer.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + model_max_length=training_args.model_max_length, + padding_side="right", + use_fast=False, + ) + + if model_args.version == "v0": + if tokenizer.pad_token is None: + smart_tokenizer_and_embedding_resize( + special_tokens_dict=dict(pad_token="[PAD]"), + tokenizer=tokenizer, + model=model, + ) + elif model_args.version == "v0.5": + tokenizer.pad_token = tokenizer.unk_token + else: + tokenizer.pad_token = tokenizer.unk_token + if model_args.version in conversation_lib.conv_templates: + conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version] + else: + conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"] + + if model_args.vision_tower is not None: + model.get_model().initialize_vision_modules( + model_args=model_args, + fsdp=training_args.fsdp + ) + + vision_tower = model.get_vision_tower() + vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device) + + data_args.image_processor = vision_tower.image_processor + data_args.is_multimodal = True + + model.config.image_aspect_ratio = data_args.image_aspect_ratio + model.config.tokenizer_padding_side = tokenizer.padding_side + model.config.tokenizer_model_max_length = tokenizer.model_max_length + # print("DEBUGG!!!-----\'model.config.tokenizer_model_max_length:\'",model.config.tokenizer_model_max_length) + + model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter + if model_args.tune_mm_mlp_adapter: + model.requires_grad_(False) + for p in model.get_model().mm_projector.parameters(): + p.requires_grad = True + + model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter + if training_args.freeze_mm_mlp_adapter: + for p in model.get_model().mm_projector.parameters(): + p.requires_grad = False + + if training_args.bits in [4, 8]: + model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device) + + model.config.mm_use_im_start_end = data_args.mm_use_im_start_end = model_args.mm_use_im_start_end + model.config.mm_projector_lr = training_args.mm_projector_lr + training_args.use_im_start_end = model_args.mm_use_im_start_end + model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token + model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer) + + if training_args.bits in [4, 8]: + from peft.tuners.lora import LoraLayer + for name, module in model.named_modules(): + if isinstance(module, LoraLayer): + if training_args.bf16: + module = module.to(torch.bfloat16) + if 'norm' in name: + module = module.to(torch.float32) + if 'lm_head' in name or 'embed_tokens' in name: + if hasattr(module, 'weight'): + if training_args.bf16 and module.weight.dtype == torch.float32: + module = module.to(torch.bfloat16) + # rank0_print(f"make_supervised_data_module") + + # original_socket_recv = socket.socket.recv + + # def monitoring_socket_recv(sock, bufsize, *args, **kwargs): + # data = original_socket_recv(sock, bufsize, *args, **kwargs) + # if data: + # monitoring_socket_recv.total_downloaded += len(data) + # monitoring_socket_recv.progress_bar.update(len(data)) + # return data + # import tqdm + # monitoring_socket_recv.total_downloaded = 0 + # monitoring_socket_recv.progress_bar = tqdm(total=0, unit='B', unit_scale=True, desc='Total Downloaded') + # # Apply the patch + # socket.socket.recv = monitoring_socket_recv + data_module = make_supervised_data_module(tokenizer=tokenizer, + data_args=data_args) + + # rank0_print(f"LLaVATrainer") + trainer = LLaVATrainer(model=model, + tokenizer=tokenizer, + args=training_args, + **data_module) + # rank0_print(f"Start Train") + if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")): + trainer.train(resume_from_checkpoint=True) + else: + trainer.train() + try: + monitoring_socket_recv.progress_bar.close() + except Exception as e: + print(e) + + + trainer.save_state() + + model.config.use_cache = True + + # print("DEBUG---NAMED_PARAMETERS", model.named_parameters()) + + if training_args.lora_enable: + # print("DEBUG--- ENTER LORA_ENABLE") + + + # print("DEBUG---NONE-LORA-STATE-DICT", model.named_parameters()) + state_dict = get_peft_state_maybe_zero_3( + model.named_parameters(), training_args.lora_bias + ) + + # print("DEBUG---LORA-STATE-DICT",state_dict) + + + # raise Exception + + non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3( + model.named_parameters() + ) + + # print("DEBUG---NONE-LORA-STATE-DICT", non_lora_state_dict) + if training_args.local_rank == 0 or training_args.local_rank == -1: + model.config.save_pretrained(training_args.output_dir) + model.save_pretrained(training_args.output_dir, state_dict=state_dict) + torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, 'non_lora_trainables.bin')) + else: + # print("DEBUG--- ENTER ELSE") + safe_save_model_for_hf_trainer(trainer=trainer, + output_dir=training_args.output_dir) + + +if __name__ == "__main__": + train() diff --git a/llava/train/train_from_s3_to_Luke.py b/llava/train/train_from_s3_to_Luke.py new file mode 100644 index 0000000000000000000000000000000000000000..f1b538d9adb4474402f3e399ed20c235db6b6c5b --- /dev/null +++ b/llava/train/train_from_s3_to_Luke.py @@ -0,0 +1,1132 @@ +# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright: +# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright: +# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +from dataclasses import dataclass, field +import json +import logging +import pathlib +from typing import Dict, Optional, Sequence, List +import boto3 +import pyarrow.parquet as pq +import pandas as pd +import fsspec +import s3fs +import io +import torch + +import transformers +import tokenizers + +from llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from torch.utils.data import Dataset +from llava.train.llava_trainer import LLaVATrainer + +from llava import conversation as conversation_lib +from llava.model import * +from llava.mm_utils import tokenizer_image_token,process_anyres_ui_image + +from PIL import Image + +import os +# LOCAL_RANK = int(os.environ['LOCAL_RANK']) + +local_rank = None + + +def rank0_print(*args): + if local_rank == 0: + print(*args) + + +from packaging import version +IS_TOKENIZER_GREATER_THAN_0_14 = version.parse(tokenizers.__version__) >= version.parse('0.14') + + +@dataclass +class ModelArguments: + model_name_or_path: Optional[str] = field(default="facebook/opt-125m") + version: Optional[str] = field(default="v0") + freeze_backbone: bool = field(default=False) + tune_mm_mlp_adapter: bool = field(default=False) + vision_tower: Optional[str] = field(default=None) + mm_vision_select_layer: Optional[int] = field(default=-1) # default to the last layer + pretrain_mm_mlp_adapter: Optional[str] = field(default=None) + mm_projector_type: Optional[str] = field(default='mlp2x_gelu') + mm_use_im_start_end: bool = field(default=False) + mm_use_im_patch_token: bool = field(default=True) + mm_patch_merge_type: Optional[str] = field(default='spatial') + mm_vision_select_feature: Optional[str] = field(default="patch") + + +@dataclass +class DataArguments: + data_path: str = field(default=None, + metadata={"help": "Path to the training data."}) + lazy_preprocess: bool = False + is_multimodal: bool = False + image_folder: Optional[str] = field(default=None) + image_aspect_ratio: str = 'square' + + +@dataclass +class TrainingArguments(transformers.TrainingArguments): + cache_dir: Optional[str] = field(default=None) + optim: str = field(default="adamw_torch") + remove_unused_columns: bool = field(default=False) + freeze_mm_mlp_adapter: bool = field(default=False) + mpt_attn_impl: Optional[str] = field(default="triton") + model_max_length: int = field( + default=512, + metadata={ + "help": + "Maximum sequence length. Sequences will be right padded (and possibly truncated)." + }, + ) + double_quant: bool = field( + default=True, + metadata={"help": "Compress the quantization statistics through double quantization."} + ) + quant_type: str = field( + default="nf4", + metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."} + ) + bits: int = field( + default=16, + metadata={"help": "How many bits to use."} + ) + lora_enable: bool = False + lora_r: int = 64 + lora_alpha: int = 16 + lora_dropout: float = 0.05 + lora_weight_path: str = "" + lora_bias: str = "none" + mm_projector_lr: Optional[float] = None + group_by_modality_length: bool = field(default=False) + + +def maybe_zero_3(param, ignore_status=False, name=None): + from deepspeed import zero + from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus + if hasattr(param, "ds_id"): + if param.ds_status == ZeroParamStatus.NOT_AVAILABLE: + if not ignore_status: + logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}") + with zero.GatheredParameters([param]): + param = param.data.detach().cpu().clone() + else: + param = param.detach().cpu().clone() + return param + + +# Borrowed from peft.utils.get_peft_model_state_dict +def get_peft_state_maybe_zero_3(named_params, bias): + if bias == "none": + to_return = {k: t for k, t in named_params if "lora_" in k} + elif bias == "all": + to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k} + elif bias == "lora_only": + to_return = {} + maybe_lora_bias = {} + lora_bias_names = set() + for k, t in named_params: + if "lora_" in k: + to_return[k] = t + bias_name = k.split("lora_")[0] + "bias" + lora_bias_names.add(bias_name) + elif "bias" in k: + maybe_lora_bias[k] = t + for k, t in maybe_lora_bias: + if bias_name in lora_bias_names: + to_return[bias_name] = t + else: + raise NotImplementedError + to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()} + return to_return + + +def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True): + to_return = {k: t for k, t in named_params if "lora_" not in k} + if require_grad_only: + to_return = {k: t for k, t in to_return.items() if t.requires_grad} + to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} + return to_return + + +def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match): + to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)} + to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} + return to_return + + +def find_all_linear_names(model): + cls = torch.nn.Linear + lora_module_names = set() + multimodal_keywords = ['mm_projector', 'vision_tower', 'vision_resampler'] + for name, module in model.named_modules(): + if any(mm_keyword in name for mm_keyword in multimodal_keywords): + continue + if isinstance(module, cls): + names = name.split('.') + lora_module_names.add(names[0] if len(names) == 1 else names[-1]) + + if 'lm_head' in lora_module_names: # needed for 16-bit + lora_module_names.remove('lm_head') + return list(lora_module_names) + + +def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, + output_dir: str): + """Collects the state dict and dump to disk.""" + + if getattr(trainer.args, "tune_mm_mlp_adapter", False): + # Only save Adapter + keys_to_match = ['mm_projector'] + if getattr(trainer.args, "use_im_start_end", False): + keys_to_match.extend(['embed_tokens', 'embed_in']) + + weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match) + trainer.model.config.save_pretrained(output_dir) + + current_folder = output_dir.split('/')[-1] + parent_folder = os.path.dirname(output_dir) + if trainer.args.local_rank == 0 or trainer.args.local_rank == -1: + if current_folder.startswith('checkpoint-'): + mm_projector_folder = os.path.join(parent_folder, "mm_projector") + os.makedirs(mm_projector_folder, exist_ok=True) + torch.save(weight_to_save, os.path.join(mm_projector_folder, f'{current_folder}.bin')) + else: + torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin')) + return + + if trainer.deepspeed: + torch.cuda.synchronize() + trainer.save_model(output_dir) + return + + state_dict = trainer.model.state_dict() + if trainer.args.should_save: + cpu_state_dict = { + key: value.cpu() + for key, value in state_dict.items() + } + del state_dict + trainer._save(output_dir, state_dict=cpu_state_dict) # noqa + + +def smart_tokenizer_and_embedding_resize( + special_tokens_dict: Dict, + tokenizer: transformers.PreTrainedTokenizer, + model: transformers.PreTrainedModel, +): + """Resize tokenizer and embedding. + + Note: This is the unoptimized version that may make your embedding size not be divisible by 64. + """ + num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict) + model.resize_token_embeddings(len(tokenizer)) + + if num_new_tokens > 0: + input_embeddings = model.get_input_embeddings().weight.data + output_embeddings = model.get_output_embeddings().weight.data + + input_embeddings_avg = input_embeddings[:-num_new_tokens].mean( + dim=0, keepdim=True) + output_embeddings_avg = output_embeddings[:-num_new_tokens].mean( + dim=0, keepdim=True) + + input_embeddings[-num_new_tokens:] = input_embeddings_avg + output_embeddings[-num_new_tokens:] = output_embeddings_avg + + +def _tokenize_fn(strings: Sequence[str], + tokenizer: transformers.PreTrainedTokenizer) -> Dict: + """Tokenize a list of strings.""" + tokenized_list = [ + tokenizer( + text, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ) for text in strings + ] + input_ids = labels = [ + tokenized.input_ids[0] for tokenized in tokenized_list + ] + input_ids_lens = labels_lens = [ + tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() + for tokenized in tokenized_list + ] + return dict( + input_ids=input_ids, + labels=labels, + input_ids_lens=input_ids_lens, + labels_lens=labels_lens, + ) + + +def _mask_targets(target, tokenized_lens, speakers): + # cur_idx = 0 + cur_idx = tokenized_lens[0] + tokenized_lens = tokenized_lens[1:] + target[:cur_idx] = IGNORE_INDEX + for tokenized_len, speaker in zip(tokenized_lens, speakers): + if speaker == "human": + target[cur_idx+2:cur_idx + tokenized_len] = IGNORE_INDEX + cur_idx += tokenized_len + + +def _add_speaker_and_signal(header, source, get_conversation=True): + """Add speaker and start/end signal on each round.""" + BEGIN_SIGNAL = "### " + END_SIGNAL = "\n" + conversation = header + for sentence in source: + from_str = sentence["from"] + if from_str.lower() == "human": + from_str = conversation_lib.default_conversation.roles[0] + elif from_str.lower() == "gpt": + from_str = conversation_lib.default_conversation.roles[1] + else: + from_str = 'unknown' + sentence["value"] = (BEGIN_SIGNAL + from_str + ": " + + sentence["value"] + END_SIGNAL) + if get_conversation: + conversation += sentence["value"] + conversation += BEGIN_SIGNAL + return conversation + + +def preprocess_multimodal( + sources: Sequence[str], + data_args: DataArguments +) -> Dict: + is_multimodal = data_args.is_multimodal + if not is_multimodal: + return sources + + for source in sources: + for sentence in source: + if DEFAULT_IMAGE_TOKEN in sentence['value']: + sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '').strip() + sentence['value'] = DEFAULT_IMAGE_TOKEN + '\n' + sentence['value'] + sentence['value'] = sentence['value'].strip() + if "mmtag" in conversation_lib.default_conversation.version: + sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '' + DEFAULT_IMAGE_TOKEN + '') + replace_token = DEFAULT_IMAGE_TOKEN + if data_args.mm_use_im_start_end: + replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN + sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token) + + return sources + + +def preprocess_llama_2( + sources, + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False +) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + + assert conv.sep_style == conversation_lib.SeparatorStyle.LLAMA_2 + + # Mask targets + sep = "[/INST] " + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep2) + cur_len = 1 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 2 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print( + f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." + f" (ignored)" + ) + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_v1( + sources, + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False +) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + + assert conv.sep_style == conversation_lib.SeparatorStyle.TWO + + # Mask targets + sep = conv.sep + conv.roles[1] + ": " + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep2) + cur_len = 1 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 2 + + if i != 0 and not tokenizer.legacy and IS_TOKENIZER_GREATER_THAN_0_14: + round_len -= 1 + instruction_len -= 1 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print( + f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." + f" (ignored)" + ) + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_mpt( + sources, + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False +) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + assert conv.sep_style == conversation_lib.SeparatorStyle.MPT + + # Mask targets + sep = conv.sep + conv.roles[1] + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep) + re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt + for conv_idx in range(3, len(rounds), 2): + re_rounds.append(conv.sep.join(rounds[conv_idx:conv_idx+2])) # user + gpt + cur_len = 0 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(re_rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 1 + + if i != 0 and getattr(tokenizer, 'legacy', False) and IS_TOKENIZER_GREATER_THAN_0_14: + round_len += 1 + instruction_len += 1 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print( + f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." + f" (ignored)" + ) + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_plain( + sources: Sequence[str], + tokenizer: transformers.PreTrainedTokenizer, +) -> Dict: + # add end signal and concatenate together + conversations = [] + for source in sources: + assert len(source) == 2 + assert DEFAULT_IMAGE_TOKEN in source[0]['value'] + source[0]['value'] = DEFAULT_IMAGE_TOKEN + conversation = source[0]['value'] + source[1]['value'] + conversation_lib.default_conversation.sep + conversations.append(conversation) + # tokenize conversations + input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations] + targets = copy.deepcopy(input_ids) + for target, source in zip(targets, sources): + tokenized_len = len(tokenizer_image_token(source[0]['value'], tokenizer)) + target[:tokenized_len] = IGNORE_INDEX + + return dict(input_ids=input_ids, labels=targets) + + +def preprocess( + sources: Sequence[str], + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False +) -> Dict: + """ + Given a list of sources, each is a conversation list. This transform: + 1. Add signal '### ' at the beginning each sentence, with end signal '\n'; + 2. Concatenate conversations together; + 3. Tokenize the concatenated conversation; + 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX. + """ + if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN: + return preprocess_plain(sources, tokenizer) + if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.LLAMA_2: + return preprocess_llama_2(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version.startswith("v1"): + return preprocess_v1(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version == "mpt": + return preprocess_mpt(sources, tokenizer, has_image=has_image) + # add end signal and concatenate together + conversations = [] + for source in sources: + header = f"{conversation_lib.default_conversation.system}\n\n" + conversation = _add_speaker_and_signal(header, source) + conversations.append(conversation) + # tokenize conversations + def get_tokenize_len(prompts): + return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts] + + if has_image: + input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations] + else: + conversations_tokenized = _tokenize_fn(conversations, tokenizer) + input_ids = conversations_tokenized["input_ids"] + + targets = copy.deepcopy(input_ids) + for target, source in zip(targets, sources): + if has_image: + tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source]) + else: + tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"] + speakers = [sentence["from"] for sentence in source] + _mask_targets(target, tokenized_lens, speakers) + + return dict(input_ids=input_ids, labels=targets) + +class LazySupervisedDataset(Dataset): + def __init__(self, data_path: str, + tokenizer: transformers.PreTrainedTokenizer, + data_args: DataArguments, + chunk_size: int = 4): + super(LazySupervisedDataset, self).__init__() + self.data_path = data_path + self.tokenizer = tokenizer + self.data_args = data_args + self.chunk_size = chunk_size + + # Setup S3 filesystem + self.s3 = s3fs.S3FileSystem() + + self.f = self.s3.open(self.data_path, 'rb') + # self.parquet_file = pq.ParquetFile(self.f, buffer_size=2048) + self.parquet_file = pq.ParquetFile(self.f) + self.metadata = self.parquet_file.metadata + + # Get total number of rows without loading the entire file + # with open(self.data_path, 'rb') as f: + self.total_rows = sum(self.metadata.row_group(i).num_rows for i in range(self.metadata.num_row_groups)) + + # rank0_print("Formatting inputs...Skip in lazy mode") + + def __len__(self): + + # rank0_print(f"Getting Length: {self.total_rows}") + return self.total_rows + + def __getitem__(self, idx): + + # rank0_print(f"Getting item at index: {idx}") + + if isinstance(idx, int): + try: + + return self._get_single_item(idx) + except Exception as e: + print(e) + self.f = self.s3.open(self.data_path, 'rb') + # self.parquet_file = pq.ParquetFile(self.f, buffer_size=2048) + self.parquet_file = pq.ParquetFile(self.f) + return self._get_single_item(idx) + + elif isinstance(idx, slice): + try: + return [self._get_single_item(i) for i in range(*idx.indices(len(self)))] + except Exception as e: + print(e) + self.f = self.s3.open(self.data_path, 'rb') + # self.parquet_file = pq.ParquetFile(self.f, buffer_size=2048) + self.parquet_file = pq.ParquetFile(self.f) + return [self._get_single_item(i) for i in range(*idx.indices(len(self)))] + else: + raise TypeError("Invalid argument type") + + def _get_single_item(self, idx): + + rank0_print(f"Getting single item at index: {idx}") + chunk_idx = idx // self.chunk_size + row_idx = idx % self.chunk_size + + # with open(self.data_path, 'rb') as f: + # num_row_groups = parquet_file.num_row_groups + # row_group_size = self.chunk_size + # if chunk_idx >= num_row_groups: + # raise IndexError(f"chunk_idx {chunk_idx} out of bounds {num_row_groups}") + + # target_row_group = chunk_idx * self.chunk_size // row_group_size + table = self.parquet_file.read_row_group(chunk_idx) + chunk = table.to_pandas() + + # if chunk_idx == num_row_groups - 1: + # row_group_size = len(chunk) + # if row_idx >= row_group_size: + # raise IndexError(f"row_idx {row_idx} out of bounds {row_group_size}") + # else: + # if row_idx >= self.chunk_size: + # raise IndexError(f"row_idx {row_idx} out of bounds {row_group_size}") + + # start_row = (chunk_idx * self.chunk_size) % row_group_size + # end_row = start_row + self.chunk_size + # chunk = chunk.iloc[start_row:end_row] + + sample = chunk.iloc[row_idx] + + # Process the sample as before + sources = json.loads(sample['conversations']) + + if isinstance(idx, int): + sources = [sources] + + if 'image' in sample: + image_bytes = sample['image'] + image = Image.open(io.BytesIO(image_bytes)).convert('RGB') + + if self.data_args.image_aspect_ratio == 'pad': + def expand2square(pil_img, background_color): + width, height = pil_img.size + if width == height: + return pil_img + elif width > height: + result = Image.new(pil_img.mode, (width, width), background_color) + result.paste(pil_img, (0, (width - height) // 2)) + return result + else: + result = Image.new(pil_img.mode, (height, height), background_color) + result.paste(pil_img, ((height - width) // 2, 0)) + return result + + image = expand2square(image, tuple(int(x * 255) for x in self.data_args.image_processor.image_mean)) + image = self.data_args.image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0] + elif self.data_args.image_aspect_ratio == 'square': + image = self.data_args.image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0] + elif self.data_args.image_aspect_ratio == 'anyres_ui': + image, new_size = process_anyres_ui_image(image, self.data_args.image_processor, fusion=False) + elif self.data_args.image_aspect_ratio == 'anyres_ui_fusion': + image, new_size = process_anyres_ui_image(image, self.data_args.image_processor, fusion=True) + sources = preprocess_multimodal( + copy.deepcopy([e for e in sources]), + self.data_args) + else: + sources = copy.deepcopy([e for e in sources]) + + data_dict = preprocess( + sources, + self.tokenizer, + has_image=('image' in sample)) + if isinstance(idx, int): + data_dict = dict(input_ids=data_dict["input_ids"][0], + labels=data_dict["labels"][0]) + + # image exist in the data + if 'image' in sample: + data_dict['image'] = image + if ( + self.data_args.image_aspect_ratio == 'anyres_ui' or self.data_args.image_aspect_ratio == 'anyres_ui_fusion'): + data_dict['image_size'] = new_size + else: + data_dict['image_size'] = (0, 0) + + elif self.data_args.is_multimodal: + crop_size = self.data_args.image_processor.crop_size + data_dict['image'] = torch.zeros(3, crop_size['height'], crop_size['width']) + data_dict['image_size'] = (crop_size['height'], crop_size['width']) + return data_dict + + @property + def lengths(self): + + rank0_print(f"Getting lengths property function") + return LazyList(self._get_length, self.total_rows) + + def _get_length(self, idx): + rank0_print(f"Getting __get_length property function {idx}") + sample = self._get_single_item(idx) + img_tokens = 128 if 'image' in sample else 0 + return sum(len(conv['value'].split()) for conv in json.loads(sample['conversations'])) + img_tokens + @property + def modality_lengths(self): + rank0_print(f"Getting modality_lengths property function") + return LazyList(self._get_modality_length, self.total_rows) + def _get_modality_length(self, idx): + rank0_print(f"Getting get_modality_length property function {idx}") + sample = self._get_single_item(idx) + cur_len = sum(len(conv['value'].split()) for conv in json.loads(sample['conversations'])) + return cur_len if 'image' in sample else -cur_len + + +@dataclass +class DataCollatorForSupervisedDataset(object): + """Collate examples for supervised fine-tuning.""" + + tokenizer: transformers.PreTrainedTokenizer + + def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]: + input_ids, labels = tuple([instance[key] for instance in instances] + for key in ("input_ids", "labels")) + input_ids = torch.nn.utils.rnn.pad_sequence( + input_ids, + batch_first=True, + padding_value=self.tokenizer.pad_token_id) + labels = torch.nn.utils.rnn.pad_sequence(labels, + batch_first=True, + padding_value=IGNORE_INDEX) + input_ids = input_ids[:, :self.tokenizer.model_max_length] + labels = labels[:, :self.tokenizer.model_max_length] + batch = dict( + input_ids=input_ids, + labels=labels, + attention_mask=input_ids.ne(self.tokenizer.pad_token_id), + ) + + if 'image' in instances[0]: + images = [instance['image'] for instance in instances] + # if all(x is not None and x.shape == images[0].shape for x in images): + # batch['images'] = torch.stack(images) + # else: + # batch['images'] = images + + batch['images'] = images + batch['image_sizes'] = [instance['image_size'] for instance in instances] + # print(f"DEBUG batch['image_sizes'] {batch['image_sizes']}") + + return batch +def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, + data_args) -> Dict: + """Make dataset and collator for supervised fine-tuning.""" + train_dataset = LazySupervisedDataset(tokenizer=tokenizer, + data_path=data_args.data_path, + data_args=data_args) + data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer) + return dict(train_dataset=train_dataset, + eval_dataset=None, + data_collator=data_collator) + +class LazyList: + def __init__(self, get_item_func, length): + self.get_item_func = get_item_func + self.length = length + + def __getitem__(self, idx): + return self.get_item_func(idx) + + def __len__(self): + return self.length + +def train(attn_implementation=None): + global local_rank + + parser = transformers.HfArgumentParser( + (ModelArguments, DataArguments, TrainingArguments)) + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + local_rank = training_args.local_rank + compute_dtype = (torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)) + + bnb_model_from_pretrained_args = {} + if training_args.bits in [4, 8]: + from transformers import BitsAndBytesConfig + bnb_model_from_pretrained_args.update(dict( + device_map={"": training_args.device}, + load_in_4bit=training_args.bits == 4, + load_in_8bit=training_args.bits == 8, + quantization_config=BitsAndBytesConfig( + load_in_4bit=training_args.bits == 4, + load_in_8bit=training_args.bits == 8, + llm_int8_skip_modules=["mm_projector"], + llm_int8_threshold=6.0, + llm_int8_has_fp16_weight=False, + bnb_4bit_compute_dtype=compute_dtype, + bnb_4bit_use_double_quant=training_args.double_quant, + bnb_4bit_quant_type=training_args.quant_type # {'fp4', 'nf4'} + ) + )) + + if model_args.vision_tower is not None: + if 'mpt' in model_args.model_name_or_path: + config = transformers.AutoConfig.from_pretrained(model_args.model_name_or_path, trust_remote_code=True) + config.attn_config['attn_impl'] = training_args.mpt_attn_impl + model = LlavaMptForCausalLM.from_pretrained( + model_args.model_name_or_path, + config=config, + cache_dir=training_args.cache_dir, + **bnb_model_from_pretrained_args + ) + else: + model = LlavaLlamaForCausalLM.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + attn_implementation=attn_implementation, + torch_dtype=(torch.bfloat16 if training_args.bf16 else None), + **bnb_model_from_pretrained_args + ) + else: + model = transformers.LlamaForCausalLM.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + attn_implementation=attn_implementation, + torch_dtype=(torch.bfloat16 if training_args.bf16 else None), + **bnb_model_from_pretrained_args + ) + model.config.use_cache = False + + if model_args.freeze_backbone: + model.model.requires_grad_(False) + + if training_args.bits in [4, 8]: + from peft import prepare_model_for_kbit_training + model.config.torch_dtype=(torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)) + model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing) + + if training_args.gradient_checkpointing: + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if training_args.lora_enable: + from peft import LoraConfig, get_peft_model + lora_config = LoraConfig( + r=training_args.lora_r, + lora_alpha=training_args.lora_alpha, + target_modules=find_all_linear_names(model), + lora_dropout=training_args.lora_dropout, + bias=training_args.lora_bias, + task_type="CAUSAL_LM", + ) + if training_args.bits == 16: + if training_args.bf16: + model.to(torch.bfloat16) + if training_args.fp16: + model.to(torch.float16) + rank0_print("Adding LoRA adapters...") + model = get_peft_model(model, lora_config) + + if 'mpt' in model_args.model_name_or_path: + tokenizer = transformers.AutoTokenizer.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + model_max_length=training_args.model_max_length, + padding_side="right" + ) + else: + tokenizer = transformers.AutoTokenizer.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + model_max_length=training_args.model_max_length, + padding_side="right", + use_fast=False, + ) + + if model_args.version == "v0": + if tokenizer.pad_token is None: + smart_tokenizer_and_embedding_resize( + special_tokens_dict=dict(pad_token="[PAD]"), + tokenizer=tokenizer, + model=model, + ) + elif model_args.version == "v0.5": + tokenizer.pad_token = tokenizer.unk_token + else: + tokenizer.pad_token = tokenizer.unk_token + if model_args.version in conversation_lib.conv_templates: + conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version] + else: + conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"] + + if model_args.vision_tower is not None: + model.get_model().initialize_vision_modules( + model_args=model_args, + fsdp=training_args.fsdp + ) + + vision_tower = model.get_vision_tower() + vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device) + + data_args.image_processor = vision_tower.image_processor + data_args.is_multimodal = True + + model.config.image_aspect_ratio = data_args.image_aspect_ratio + model.config.tokenizer_padding_side = tokenizer.padding_side + model.config.tokenizer_model_max_length = tokenizer.model_max_length + # print("DEBUGG!!!-----\'model.config.tokenizer_model_max_length:\'",model.config.tokenizer_model_max_length) + + model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter + if model_args.tune_mm_mlp_adapter: + model.requires_grad_(False) + for p in model.get_model().mm_projector.parameters(): + p.requires_grad = True + + model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter + if training_args.freeze_mm_mlp_adapter: + for p in model.get_model().mm_projector.parameters(): + p.requires_grad = False + + if training_args.bits in [4, 8]: + model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device) + + model.config.mm_use_im_start_end = data_args.mm_use_im_start_end = model_args.mm_use_im_start_end + model.config.mm_projector_lr = training_args.mm_projector_lr + training_args.use_im_start_end = model_args.mm_use_im_start_end + model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token + model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer) + + if training_args.bits in [4, 8]: + from peft.tuners.lora import LoraLayer + for name, module in model.named_modules(): + if isinstance(module, LoraLayer): + if training_args.bf16: + module = module.to(torch.bfloat16) + if 'norm' in name: + module = module.to(torch.float32) + if 'lm_head' in name or 'embed_tokens' in name: + if hasattr(module, 'weight'): + if training_args.bf16 and module.weight.dtype == torch.float32: + module = module.to(torch.bfloat16) + # rank0_print(f"make_supervised_data_module") + + # original_socket_recv = socket.socket.recv + + # def monitoring_socket_recv(sock, bufsize, *args, **kwargs): + # data = original_socket_recv(sock, bufsize, *args, **kwargs) + # if data: + # monitoring_socket_recv.total_downloaded += len(data) + # monitoring_socket_recv.progress_bar.update(len(data)) + # return data + # import tqdm + # monitoring_socket_recv.total_downloaded = 0 + # monitoring_socket_recv.progress_bar = tqdm(total=0, unit='B', unit_scale=True, desc='Total Downloaded') + # # Apply the patch + # socket.socket.recv = monitoring_socket_recv + data_module = make_supervised_data_module(tokenizer=tokenizer, + data_args=data_args) + + # rank0_print(f"LLaVATrainer") + trainer = LLaVATrainer(model=model, + tokenizer=tokenizer, + args=training_args, + **data_module) + # rank0_print(f"Start Train") + if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")): + trainer.train(resume_from_checkpoint=True) + else: + trainer.train() + try: + monitoring_socket_recv.progress_bar.close() + except Exception as e: + print(e) + + + trainer.save_state() + + model.config.use_cache = True + + # print("DEBUG---NAMED_PARAMETERS", model.named_parameters()) + + if training_args.lora_enable: + # print("DEBUG--- ENTER LORA_ENABLE") + + + # print("DEBUG---NONE-LORA-STATE-DICT", model.named_parameters()) + state_dict = get_peft_state_maybe_zero_3( + model.named_parameters(), training_args.lora_bias + ) + + # print("DEBUG---LORA-STATE-DICT",state_dict) + + + # raise Exception + + non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3( + model.named_parameters() + ) + + # print("DEBUG---NONE-LORA-STATE-DICT", non_lora_state_dict) + if training_args.local_rank == 0 or training_args.local_rank == -1: + model.config.save_pretrained(training_args.output_dir) + model.save_pretrained(training_args.output_dir, state_dict=state_dict) + torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, 'non_lora_trainables.bin')) + else: + # print("DEBUG--- ENTER ELSE") + safe_save_model_for_hf_trainer(trainer=trainer, + output_dir=training_args.output_dir) + + +if __name__ == "__main__": + train() diff --git a/llava/train/train_mem.py b/llava/train/train_mem.py new file mode 100644 index 0000000000000000000000000000000000000000..29ea06170f23a845627c7e3dd52d3a5bdb379767 --- /dev/null +++ b/llava/train/train_mem.py @@ -0,0 +1,4 @@ +from llava.train.train import train + +if __name__ == "__main__": + train(attn_implementation="flash_attention_2") diff --git a/llava/train/train_s3.py b/llava/train/train_s3.py new file mode 100644 index 0000000000000000000000000000000000000000..fc5a6d2ec5a72fded3840eabaf3bdec0f9ec951c --- /dev/null +++ b/llava/train/train_s3.py @@ -0,0 +1,1089 @@ +# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright: +# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright: +# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import copy +from dataclasses import dataclass, field +import json +import logging +import pathlib +from typing import Dict, Optional, Sequence, List +import boto3 +import pyarrow.parquet as pq +import pandas as pd +import fsspec +import s3fs +import io +import torch + +import transformers +import tokenizers + +from llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from torch.utils.data import Dataset +from llava.train.llava_trainer import LLaVATrainer + +from llava import conversation as conversation_lib +from llava.model import * +from llava.mm_utils import tokenizer_image_token,process_anyres_ui_image + +from PIL import Image + +import os +# LOCAL_RANK = int(os.environ['LOCAL_RANK']) + +local_rank = None + + +def rank0_print(*args): + if local_rank == 0: + print(*args) + + +from packaging import version +IS_TOKENIZER_GREATER_THAN_0_14 = version.parse(tokenizers.__version__) >= version.parse('0.14') + + +@dataclass +class ModelArguments: + model_name_or_path: Optional[str] = field(default="facebook/opt-125m") + version: Optional[str] = field(default="v0") + freeze_backbone: bool = field(default=False) + tune_mm_mlp_adapter: bool = field(default=False) + vision_tower: Optional[str] = field(default=None) + mm_vision_select_layer: Optional[int] = field(default=-1) # default to the last layer + pretrain_mm_mlp_adapter: Optional[str] = field(default=None) + mm_projector_type: Optional[str] = field(default='mlp2x_gelu') + mm_use_im_start_end: bool = field(default=False) + mm_use_im_patch_token: bool = field(default=True) + mm_patch_merge_type: Optional[str] = field(default='spatial') + mm_vision_select_feature: Optional[str] = field(default="patch") + + +@dataclass +class DataArguments: + data_path: str = field(default=None, + metadata={"help": "Path to the training data."}) + lazy_preprocess: bool = False + is_multimodal: bool = False + image_folder: Optional[str] = field(default=None) + image_aspect_ratio: str = 'square' + + +@dataclass +class TrainingArguments(transformers.TrainingArguments): + cache_dir: Optional[str] = field(default=None) + optim: str = field(default="adamw_torch") + remove_unused_columns: bool = field(default=False) + freeze_mm_mlp_adapter: bool = field(default=False) + mpt_attn_impl: Optional[str] = field(default="triton") + model_max_length: int = field( + default=512, + metadata={ + "help": + "Maximum sequence length. Sequences will be right padded (and possibly truncated)." + }, + ) + double_quant: bool = field( + default=True, + metadata={"help": "Compress the quantization statistics through double quantization."} + ) + quant_type: str = field( + default="nf4", + metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."} + ) + bits: int = field( + default=16, + metadata={"help": "How many bits to use."} + ) + lora_enable: bool = False + lora_r: int = 64 + lora_alpha: int = 16 + lora_dropout: float = 0.05 + lora_weight_path: str = "" + lora_bias: str = "none" + mm_projector_lr: Optional[float] = None + group_by_modality_length: bool = field(default=False) + + +def maybe_zero_3(param, ignore_status=False, name=None): + from deepspeed import zero + from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus + if hasattr(param, "ds_id"): + if param.ds_status == ZeroParamStatus.NOT_AVAILABLE: + if not ignore_status: + logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}") + with zero.GatheredParameters([param]): + param = param.data.detach().cpu().clone() + else: + param = param.detach().cpu().clone() + return param + + +# Borrowed from peft.utils.get_peft_model_state_dict +def get_peft_state_maybe_zero_3(named_params, bias): + if bias == "none": + to_return = {k: t for k, t in named_params if "lora_" in k} + elif bias == "all": + to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k} + elif bias == "lora_only": + to_return = {} + maybe_lora_bias = {} + lora_bias_names = set() + for k, t in named_params: + if "lora_" in k: + to_return[k] = t + bias_name = k.split("lora_")[0] + "bias" + lora_bias_names.add(bias_name) + elif "bias" in k: + maybe_lora_bias[k] = t + for k, t in maybe_lora_bias: + if bias_name in lora_bias_names: + to_return[bias_name] = t + else: + raise NotImplementedError + to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()} + return to_return + + +def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True): + to_return = {k: t for k, t in named_params if "lora_" not in k} + if require_grad_only: + to_return = {k: t for k, t in to_return.items() if t.requires_grad} + to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} + return to_return + + +def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match): + to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)} + to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} + return to_return + + +def find_all_linear_names(model): + cls = torch.nn.Linear + lora_module_names = set() + multimodal_keywords = ['mm_projector', 'vision_tower', 'vision_resampler'] + for name, module in model.named_modules(): + if any(mm_keyword in name for mm_keyword in multimodal_keywords): + continue + if isinstance(module, cls): + names = name.split('.') + lora_module_names.add(names[0] if len(names) == 1 else names[-1]) + + if 'lm_head' in lora_module_names: # needed for 16-bit + lora_module_names.remove('lm_head') + return list(lora_module_names) + + +def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, + output_dir: str): + """Collects the state dict and dump to disk.""" + + if getattr(trainer.args, "tune_mm_mlp_adapter", False): + # Only save Adapter + keys_to_match = ['mm_projector'] + if getattr(trainer.args, "use_im_start_end", False): + keys_to_match.extend(['embed_tokens', 'embed_in']) + + weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match) + trainer.model.config.save_pretrained(output_dir) + + current_folder = output_dir.split('/')[-1] + parent_folder = os.path.dirname(output_dir) + if trainer.args.local_rank == 0 or trainer.args.local_rank == -1: + if current_folder.startswith('checkpoint-'): + mm_projector_folder = os.path.join(parent_folder, "mm_projector") + os.makedirs(mm_projector_folder, exist_ok=True) + torch.save(weight_to_save, os.path.join(mm_projector_folder, f'{current_folder}.bin')) + else: + torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin')) + return + + if trainer.deepspeed: + torch.cuda.synchronize() + trainer.save_model(output_dir) + return + + state_dict = trainer.model.state_dict() + if trainer.args.should_save: + cpu_state_dict = { + key: value.cpu() + for key, value in state_dict.items() + } + del state_dict + trainer._save(output_dir, state_dict=cpu_state_dict) # noqa + + +def smart_tokenizer_and_embedding_resize( + special_tokens_dict: Dict, + tokenizer: transformers.PreTrainedTokenizer, + model: transformers.PreTrainedModel, +): + """Resize tokenizer and embedding. + + Note: This is the unoptimized version that may make your embedding size not be divisible by 64. + """ + num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict) + model.resize_token_embeddings(len(tokenizer)) + + if num_new_tokens > 0: + input_embeddings = model.get_input_embeddings().weight.data + output_embeddings = model.get_output_embeddings().weight.data + + input_embeddings_avg = input_embeddings[:-num_new_tokens].mean( + dim=0, keepdim=True) + output_embeddings_avg = output_embeddings[:-num_new_tokens].mean( + dim=0, keepdim=True) + + input_embeddings[-num_new_tokens:] = input_embeddings_avg + output_embeddings[-num_new_tokens:] = output_embeddings_avg + + +def _tokenize_fn(strings: Sequence[str], + tokenizer: transformers.PreTrainedTokenizer) -> Dict: + """Tokenize a list of strings.""" + tokenized_list = [ + tokenizer( + text, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ) for text in strings + ] + input_ids = labels = [ + tokenized.input_ids[0] for tokenized in tokenized_list + ] + input_ids_lens = labels_lens = [ + tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() + for tokenized in tokenized_list + ] + return dict( + input_ids=input_ids, + labels=labels, + input_ids_lens=input_ids_lens, + labels_lens=labels_lens, + ) + + +def _mask_targets(target, tokenized_lens, speakers): + # cur_idx = 0 + cur_idx = tokenized_lens[0] + tokenized_lens = tokenized_lens[1:] + target[:cur_idx] = IGNORE_INDEX + for tokenized_len, speaker in zip(tokenized_lens, speakers): + if speaker == "human": + target[cur_idx+2:cur_idx + tokenized_len] = IGNORE_INDEX + cur_idx += tokenized_len + + +def _add_speaker_and_signal(header, source, get_conversation=True): + """Add speaker and start/end signal on each round.""" + BEGIN_SIGNAL = "### " + END_SIGNAL = "\n" + conversation = header + for sentence in source: + from_str = sentence["from"] + if from_str.lower() == "human": + from_str = conversation_lib.default_conversation.roles[0] + elif from_str.lower() == "gpt": + from_str = conversation_lib.default_conversation.roles[1] + else: + from_str = 'unknown' + sentence["value"] = (BEGIN_SIGNAL + from_str + ": " + + sentence["value"] + END_SIGNAL) + if get_conversation: + conversation += sentence["value"] + conversation += BEGIN_SIGNAL + return conversation + + +def preprocess_multimodal( + sources: Sequence[str], + data_args: DataArguments +) -> Dict: + is_multimodal = data_args.is_multimodal + if not is_multimodal: + return sources + + for source in sources: + for sentence in source: + if DEFAULT_IMAGE_TOKEN in sentence['value']: + sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '').strip() + sentence['value'] = DEFAULT_IMAGE_TOKEN + '\n' + sentence['value'] + sentence['value'] = sentence['value'].strip() + if "mmtag" in conversation_lib.default_conversation.version: + sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '' + DEFAULT_IMAGE_TOKEN + '') + replace_token = DEFAULT_IMAGE_TOKEN + if data_args.mm_use_im_start_end: + replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN + sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token) + + return sources + + +def preprocess_llama_2( + sources, + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False +) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + + assert conv.sep_style == conversation_lib.SeparatorStyle.LLAMA_2 + + # Mask targets + sep = "[/INST] " + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep2) + cur_len = 1 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 2 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print( + f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." + f" (ignored)" + ) + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_v1( + sources, + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False +) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + + assert conv.sep_style == conversation_lib.SeparatorStyle.TWO + + # Mask targets + sep = conv.sep + conv.roles[1] + ": " + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep2) + cur_len = 1 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 2 + + if i != 0 and not tokenizer.legacy and IS_TOKENIZER_GREATER_THAN_0_14: + round_len -= 1 + instruction_len -= 1 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print( + f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." + f" (ignored)" + ) + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_mpt( + sources, + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False +) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + assert conv.sep_style == conversation_lib.SeparatorStyle.MPT + + # Mask targets + sep = conv.sep + conv.roles[1] + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep) + re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt + for conv_idx in range(3, len(rounds), 2): + re_rounds.append(conv.sep.join(rounds[conv_idx:conv_idx+2])) # user + gpt + cur_len = 0 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(re_rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 1 + + if i != 0 and getattr(tokenizer, 'legacy', False) and IS_TOKENIZER_GREATER_THAN_0_14: + round_len += 1 + instruction_len += 1 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print( + f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." + f" (ignored)" + ) + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_plain( + sources: Sequence[str], + tokenizer: transformers.PreTrainedTokenizer, +) -> Dict: + # add end signal and concatenate together + conversations = [] + for source in sources: + assert len(source) == 2 + assert DEFAULT_IMAGE_TOKEN in source[0]['value'] + source[0]['value'] = DEFAULT_IMAGE_TOKEN + conversation = source[0]['value'] + source[1]['value'] + conversation_lib.default_conversation.sep + conversations.append(conversation) + # tokenize conversations + input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations] + targets = copy.deepcopy(input_ids) + for target, source in zip(targets, sources): + tokenized_len = len(tokenizer_image_token(source[0]['value'], tokenizer)) + target[:tokenized_len] = IGNORE_INDEX + + return dict(input_ids=input_ids, labels=targets) + + +def preprocess( + sources: Sequence[str], + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False +) -> Dict: + """ + Given a list of sources, each is a conversation list. This transform: + 1. Add signal '### ' at the beginning each sentence, with end signal '\n'; + 2. Concatenate conversations together; + 3. Tokenize the concatenated conversation; + 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX. + """ + if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN: + return preprocess_plain(sources, tokenizer) + if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.LLAMA_2: + return preprocess_llama_2(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version.startswith("v1"): + return preprocess_v1(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version == "mpt": + return preprocess_mpt(sources, tokenizer, has_image=has_image) + # add end signal and concatenate together + conversations = [] + for source in sources: + header = f"{conversation_lib.default_conversation.system}\n\n" + conversation = _add_speaker_and_signal(header, source) + conversations.append(conversation) + # tokenize conversations + def get_tokenize_len(prompts): + return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts] + + if has_image: + input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations] + else: + conversations_tokenized = _tokenize_fn(conversations, tokenizer) + input_ids = conversations_tokenized["input_ids"] + + targets = copy.deepcopy(input_ids) + for target, source in zip(targets, sources): + if has_image: + tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source]) + else: + tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"] + speakers = [sentence["from"] for sentence in source] + _mask_targets(target, tokenized_lens, speakers) + + return dict(input_ids=input_ids, labels=targets) + +class LazySupervisedDataset(Dataset): + def __init__(self, data_path: str, + tokenizer: transformers.PreTrainedTokenizer, + data_args: DataArguments, + chunk_size: int = 1,): + super(LazySupervisedDataset, self).__init__() + self.data_path = data_path + self.tokenizer = tokenizer + self.data_args = data_args + self.chunk_size = chunk_size + + # Setup S3 filesystem + self.s3 = s3fs.S3FileSystem() + + # Get total number of rows without loading the entire file + with self.s3.open(data_path, 'rb') as f: + parquet_file = pq.ParquetFile(f) + self.parquet_metadata = parquet_file.metadata + self.total_rows = sum(self.parquet_metadata.row_group(i).num_rows for i in range(self.parquet_metadata.num_row_groups)) + rank0_print("Formatting inputs...Skip in lazy mode") + + def __len__(self): + return self.total_rows + + def __getitem__(self, idx): + if isinstance(idx, int): + return self._get_single_item(idx) + elif isinstance(idx, slice): + return [self._get_single_item(i) for i in range(*idx.indices(len(self)))] + else: + raise TypeError("Invalid argument type") + + def _get_single_item(self, idx): + + chunk_idx = idx // self.chunk_size + row_idx = idx % self.chunk_size + + with self.s3.open(self.data_path, 'rb') as f: + # parquet_file = pq.ParquetFile(f) + # num_row_groups = parquet_file.num_row_groups + num_row_groups=self.parquet_metadata.num_row_groups + row_group_size = self.chunk_size + if chunk_idx >= num_row_groups: + raise IndexError(f"chunk_idx {chunk_idx} out of bounds {num_row_groups}") + + # target_row_group = chunk_idx * self.chunk_size // row_group_size + # table = parquet_file.read_row_group(chunk_idx) + table=pq.read_table(f, row_indices=chunk_idx) + chunk = table.to_pandas() + + if chunk_idx == num_row_groups - 1: + row_group_size = len(chunk) + if row_idx >= row_group_size: + raise IndexError(f"row_idx {row_idx} out of bounds {row_group_size}") + else: + if row_idx >= self.chunk_size: + raise IndexError(f"row_idx {row_idx} out of bounds {row_group_size}") + + # start_row = (chunk_idx * self.chunk_size) % row_group_size + # end_row = start_row + self.chunk_size + # chunk = chunk.iloc[start_row:end_row] + + sample = chunk.iloc[row_idx] + + # Process the sample as before + sources = json.loads(sample['conversations']) + + if isinstance(idx, int): + sources = [sources] + # print(sources) + # print(len(sources)) + # print(type(sources)) + assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME + + if 'image' in sample: + image_bytes = sample['image'] + image = Image.open(io.BytesIO(image_bytes)).convert('RGB') + + if self.data_args.image_aspect_ratio == 'pad': + def expand2square(pil_img, background_color): + width, height = pil_img.size + if width == height: + return pil_img + elif width > height: + result = Image.new(pil_img.mode, (width, width), background_color) + result.paste(pil_img, (0, (width - height) // 2)) + return result + else: + result = Image.new(pil_img.mode, (height, height), background_color) + result.paste(pil_img, ((height - width) // 2, 0)) + return result + + image = expand2square(image, tuple(int(x * 255) for x in self.data_args.image_processor.image_mean)) + image = self.data_args.image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0] + elif self.data_args.image_aspect_ratio == 'square': + image = self.data_args.image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0] + elif self.data_args.image_aspect_ratio == 'anyres_ui': + image, new_size = process_anyres_ui_image(image, self.data_args.image_processor, fusion=False) + elif self.data_args.image_aspect_ratio == 'anyres_ui_fusion': + image, new_size = process_anyres_ui_image(image, self.data_args.image_processor, fusion=True) + sources = preprocess_multimodal( + copy.deepcopy([e for e in sources]), + self.data_args) + else: + sources = copy.deepcopy([e for e in sources]) + + data_dict = preprocess( + sources, + self.tokenizer, + has_image=('image' in sample)) + if isinstance(idx, int): + data_dict = dict(input_ids=data_dict["input_ids"][0], + labels=data_dict["labels"][0]) + + # image exist in the data + if 'image' in sample: + data_dict['image'] = image + if ( + self.data_args.image_aspect_ratio == 'anyres_ui' or self.data_args.image_aspect_ratio == 'anyres_ui_fusion'): + data_dict['image_size'] = new_size + else: + data_dict['image_size'] = (0, 0) + + elif self.data_args.is_multimodal: + crop_size = self.data_args.image_processor.crop_size + data_dict['image'] = torch.zeros(3, crop_size['height'], crop_size['width']) + data_dict['image_size'] = (crop_size['height'], crop_size['width']) + return data_dict + + @property + def lengths(self): + return LazyList(self._get_length, self.total_rows) + + def _get_length(self, idx): + sample = self._get_single_item(idx) + img_tokens = 128 if 'image' in sample else 0 + return sum(len(conv['value'].split()) for conv in json.loads(sample['conversations'])) + img_tokens + + @property + def modality_lengths(self): + return LazyList(self._get_modality_length, self.total_rows) + + def _get_modality_length(self, idx): + sample = self._get_single_item(idx) + cur_len = sum(len(conv['value'].split()) for conv in json.loads(sample['conversations'])) + return cur_len if 'image' in sample else -cur_len + + +@dataclass +class DataCollatorForSupervisedDataset(object): + """Collate examples for supervised fine-tuning.""" + + tokenizer: transformers.PreTrainedTokenizer + + def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]: + input_ids, labels = tuple([instance[key] for instance in instances] + for key in ("input_ids", "labels")) + input_ids = torch.nn.utils.rnn.pad_sequence( + input_ids, + batch_first=True, + padding_value=self.tokenizer.pad_token_id) + labels = torch.nn.utils.rnn.pad_sequence(labels, + batch_first=True, + padding_value=IGNORE_INDEX) + input_ids = input_ids[:, :self.tokenizer.model_max_length] + labels = labels[:, :self.tokenizer.model_max_length] + batch = dict( + input_ids=input_ids, + labels=labels, + attention_mask=input_ids.ne(self.tokenizer.pad_token_id), + ) + + if 'image' in instances[0]: + images = [instance['image'] for instance in instances] + # if all(x is not None and x.shape == images[0].shape for x in images): + # batch['images'] = torch.stack(images) + # else: + # batch['images'] = images + + batch['images'] = images + batch['image_sizes'] = [instance['image_size'] for instance in instances] + # print(f"DEBUG batch['image_sizes'] {batch['image_sizes']}") + + return batch +def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, + data_args) -> Dict: + """Make dataset and collator for supervised fine-tuning.""" + train_dataset = LazySupervisedDataset(tokenizer=tokenizer, + data_path=data_args.data_path, + data_args=data_args) + data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer) + return dict(train_dataset=train_dataset, + eval_dataset=None, + data_collator=data_collator) + +class LazyList: + def __init__(self, get_item_func, length): + self.get_item_func = get_item_func + self.length = length + + def __getitem__(self, idx): + return self.get_item_func(idx) + + def __len__(self): + return self.length + +def train(attn_implementation=None): + global local_rank + + parser = transformers.HfArgumentParser( + (ModelArguments, DataArguments, TrainingArguments)) + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + local_rank = training_args.local_rank + compute_dtype = (torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)) + + bnb_model_from_pretrained_args = {} + if training_args.bits in [4, 8]: + from transformers import BitsAndBytesConfig + bnb_model_from_pretrained_args.update(dict( + device_map={"": training_args.device}, + load_in_4bit=training_args.bits == 4, + load_in_8bit=training_args.bits == 8, + quantization_config=BitsAndBytesConfig( + load_in_4bit=training_args.bits == 4, + load_in_8bit=training_args.bits == 8, + llm_int8_skip_modules=["mm_projector"], + llm_int8_threshold=6.0, + llm_int8_has_fp16_weight=False, + bnb_4bit_compute_dtype=compute_dtype, + bnb_4bit_use_double_quant=training_args.double_quant, + bnb_4bit_quant_type=training_args.quant_type # {'fp4', 'nf4'} + ) + )) + + if model_args.vision_tower is not None: + if 'mpt' in model_args.model_name_or_path: + config = transformers.AutoConfig.from_pretrained(model_args.model_name_or_path, trust_remote_code=True) + config.attn_config['attn_impl'] = training_args.mpt_attn_impl + model = LlavaMptForCausalLM.from_pretrained( + model_args.model_name_or_path, + config=config, + cache_dir=training_args.cache_dir, + **bnb_model_from_pretrained_args + ) + else: + model = LlavaLlamaForCausalLM.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + attn_implementation=attn_implementation, + torch_dtype=(torch.bfloat16 if training_args.bf16 else None), + **bnb_model_from_pretrained_args + ) + else: + model = transformers.LlamaForCausalLM.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + attn_implementation=attn_implementation, + torch_dtype=(torch.bfloat16 if training_args.bf16 else None), + **bnb_model_from_pretrained_args + ) + model.config.use_cache = False + + if model_args.freeze_backbone: + model.model.requires_grad_(False) + + if training_args.bits in [4, 8]: + from peft import prepare_model_for_kbit_training + model.config.torch_dtype=(torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)) + model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing) + + if training_args.gradient_checkpointing: + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if training_args.lora_enable: + from peft import LoraConfig, get_peft_model + lora_config = LoraConfig( + r=training_args.lora_r, + lora_alpha=training_args.lora_alpha, + target_modules=find_all_linear_names(model), + lora_dropout=training_args.lora_dropout, + bias=training_args.lora_bias, + task_type="CAUSAL_LM", + ) + if training_args.bits == 16: + if training_args.bf16: + model.to(torch.bfloat16) + if training_args.fp16: + model.to(torch.float16) + rank0_print("Adding LoRA adapters...") + model = get_peft_model(model, lora_config) + + if 'mpt' in model_args.model_name_or_path: + tokenizer = transformers.AutoTokenizer.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + model_max_length=training_args.model_max_length, + padding_side="right" + ) + else: + tokenizer = transformers.AutoTokenizer.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + model_max_length=training_args.model_max_length, + padding_side="right", + use_fast=False, + ) + + if model_args.version == "v0": + if tokenizer.pad_token is None: + smart_tokenizer_and_embedding_resize( + special_tokens_dict=dict(pad_token="[PAD]"), + tokenizer=tokenizer, + model=model, + ) + elif model_args.version == "v0.5": + tokenizer.pad_token = tokenizer.unk_token + else: + tokenizer.pad_token = tokenizer.unk_token + if model_args.version in conversation_lib.conv_templates: + conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version] + else: + conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"] + + if model_args.vision_tower is not None: + model.get_model().initialize_vision_modules( + model_args=model_args, + fsdp=training_args.fsdp + ) + + vision_tower = model.get_vision_tower() + vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device) + + data_args.image_processor = vision_tower.image_processor + data_args.is_multimodal = True + + model.config.image_aspect_ratio = data_args.image_aspect_ratio + model.config.tokenizer_padding_side = tokenizer.padding_side + model.config.tokenizer_model_max_length = tokenizer.model_max_length + # print("DEBUGG!!!-----\'model.config.tokenizer_model_max_length:\'",model.config.tokenizer_model_max_length) + + model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter + if model_args.tune_mm_mlp_adapter: + model.requires_grad_(False) + for p in model.get_model().mm_projector.parameters(): + p.requires_grad = True + + model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter + if training_args.freeze_mm_mlp_adapter: + for p in model.get_model().mm_projector.parameters(): + p.requires_grad = False + + if training_args.bits in [4, 8]: + model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device) + + model.config.mm_use_im_start_end = data_args.mm_use_im_start_end = model_args.mm_use_im_start_end + model.config.mm_projector_lr = training_args.mm_projector_lr + training_args.use_im_start_end = model_args.mm_use_im_start_end + model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token + model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer) + + if training_args.bits in [4, 8]: + from peft.tuners.lora import LoraLayer + for name, module in model.named_modules(): + if isinstance(module, LoraLayer): + if training_args.bf16: + module = module.to(torch.bfloat16) + if 'norm' in name: + module = module.to(torch.float32) + if 'lm_head' in name or 'embed_tokens' in name: + if hasattr(module, 'weight'): + if training_args.bf16 and module.weight.dtype == torch.float32: + module = module.to(torch.bfloat16) + + data_module = make_supervised_data_module(tokenizer=tokenizer, + data_args=data_args) + trainer = LLaVATrainer(model=model, + tokenizer=tokenizer, + args=training_args, + **data_module) + + if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")): + trainer.train(resume_from_checkpoint=True) + else: + trainer.train() + trainer.save_state() + + model.config.use_cache = True + + # print("DEBUG---NAMED_PARAMETERS", model.named_parameters()) + + if training_args.lora_enable: + # print("DEBUG--- ENTER LORA_ENABLE") + + + # print("DEBUG---NONE-LORA-STATE-DICT", model.named_parameters()) + state_dict = get_peft_state_maybe_zero_3( + model.named_parameters(), training_args.lora_bias + ) + + # print("DEBUG---LORA-STATE-DICT",state_dict) + + + # raise Exception + + non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3( + model.named_parameters() + ) + + # print("DEBUG---NONE-LORA-STATE-DICT", non_lora_state_dict) + if training_args.local_rank == 0 or training_args.local_rank == -1: + model.config.save_pretrained(training_args.output_dir) + model.save_pretrained(training_args.output_dir, state_dict=state_dict) + torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, 'non_lora_trainables.bin')) + else: + # print("DEBUG--- ENTER ELSE") + safe_save_model_for_hf_trainer(trainer=trainer, + output_dir=training_args.output_dir) + + +if __name__ == "__main__": + train() diff --git a/llava/train/train_together.py b/llava/train/train_together.py new file mode 100644 index 0000000000000000000000000000000000000000..241c823d140e0f6d4bbc606ff18416300859878b --- /dev/null +++ b/llava/train/train_together.py @@ -0,0 +1,1128 @@ +# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright: +# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright: +# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import copy +from dataclasses import dataclass, field +import json +import logging +import pathlib +from typing import Dict, Optional, Sequence, List +import pandas as pd +import pyarrow.parquet as pq +import io +import torch + +import transformers +import tokenizers + +from llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from torch.utils.data import Dataset +from llava.train.llava_trainer import LLaVATrainer + +from llava import conversation as conversation_lib +from llava.model import * +from llava.mm_utils import tokenizer_image_token,process_anyres_ui_image + +from PIL import Image + +import os +# LOCAL_RANK = int(os.environ['LOCAL_RANK']) + +local_rank = None + + +def rank0_print(*args): + if local_rank == 0: + print(*args) + + +from packaging import version +IS_TOKENIZER_GREATER_THAN_0_14 = version.parse(tokenizers.__version__) >= version.parse('0.14') + + +@dataclass +class ModelArguments: + model_name_or_path: Optional[str] = field(default="facebook/opt-125m") + version: Optional[str] = field(default="v0") + freeze_backbone: bool = field(default=False) + tune_mm_mlp_adapter: bool = field(default=False) + vision_tower: Optional[str] = field(default=None) + mm_vision_select_layer: Optional[int] = field(default=-1) # default to the last layer + pretrain_mm_mlp_adapter: Optional[str] = field(default=None) + mm_projector_type: Optional[str] = field(default='mlp2x_gelu') + mm_use_im_start_end: bool = field(default=False) + mm_use_im_patch_token: bool = field(default=True) + mm_patch_merge_type: Optional[str] = field(default='spatial') + mm_vision_select_feature: Optional[str] = field(default="patch") + + +@dataclass +class DataArguments: + data_path: str = field(default=None, + metadata={"help": "Path to the training data."}) + lazy_preprocess: bool = False + is_multimodal: bool = False + image_folder: Optional[str] = field(default=None) + image_aspect_ratio: str = 'square' + + +@dataclass +class TrainingArguments(transformers.TrainingArguments): + cache_dir: Optional[str] = field(default=None) + optim: str = field(default="adamw_torch") + remove_unused_columns: bool = field(default=False) + freeze_mm_mlp_adapter: bool = field(default=False) + mpt_attn_impl: Optional[str] = field(default="triton") + model_max_length: int = field( + default=512, + metadata={ + "help": + "Maximum sequence length. Sequences will be right padded (and possibly truncated)." + }, + ) + double_quant: bool = field( + default=True, + metadata={"help": "Compress the quantization statistics through double quantization."} + ) + quant_type: str = field( + default="nf4", + metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."} + ) + bits: int = field( + default=16, + metadata={"help": "How many bits to use."} + ) + lora_enable: bool = False + lora_r: int = 64 + lora_alpha: int = 16 + lora_dropout: float = 0.05 + lora_weight_path: str = "" + lora_bias: str = "none" + mm_projector_lr: Optional[float] = None + group_by_modality_length: bool = field(default=False) + + +def maybe_zero_3(param, ignore_status=False, name=None): + from deepspeed import zero + from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus + if hasattr(param, "ds_id"): + if param.ds_status == ZeroParamStatus.NOT_AVAILABLE: + if not ignore_status: + logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}") + with zero.GatheredParameters([param]): + param = param.data.detach().cpu().clone() + else: + param = param.detach().cpu().clone() + return param + + +# Borrowed from peft.utils.get_peft_model_state_dict +def get_peft_state_maybe_zero_3(named_params, bias): + if bias == "none": + to_return = {k: t for k, t in named_params if "lora_" in k} + elif bias == "all": + to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k} + elif bias == "lora_only": + to_return = {} + maybe_lora_bias = {} + lora_bias_names = set() + for k, t in named_params: + if "lora_" in k: + to_return[k] = t + bias_name = k.split("lora_")[0] + "bias" + lora_bias_names.add(bias_name) + elif "bias" in k: + maybe_lora_bias[k] = t + for k, t in maybe_lora_bias: + if bias_name in lora_bias_names: + to_return[bias_name] = t + else: + raise NotImplementedError + to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()} + return to_return + + +def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True): + to_return = {k: t for k, t in named_params if "lora_" not in k} + if require_grad_only: + to_return = {k: t for k, t in to_return.items() if t.requires_grad} + to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} + return to_return + + +def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match): + to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)} + to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} + return to_return + + +def find_all_linear_names(model): + cls = torch.nn.Linear + lora_module_names = set() + multimodal_keywords = ['mm_projector', 'vision_tower', 'vision_resampler'] + for name, module in model.named_modules(): + if any(mm_keyword in name for mm_keyword in multimodal_keywords): + continue + if isinstance(module, cls): + names = name.split('.') + lora_module_names.add(names[0] if len(names) == 1 else names[-1]) + + if 'lm_head' in lora_module_names: # needed for 16-bit + lora_module_names.remove('lm_head') + return list(lora_module_names) + + +def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, + output_dir: str): + """Collects the state dict and dump to disk.""" + + if getattr(trainer.args, "tune_mm_mlp_adapter", False): + # Only save Adapter + keys_to_match = ['mm_projector'] + if getattr(trainer.args, "use_im_start_end", False): + keys_to_match.extend(['embed_tokens', 'embed_in']) + + weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match) + trainer.model.config.save_pretrained(output_dir) + + current_folder = output_dir.split('/')[-1] + parent_folder = os.path.dirname(output_dir) + if trainer.args.local_rank == 0 or trainer.args.local_rank == -1: + if current_folder.startswith('checkpoint-'): + mm_projector_folder = os.path.join(parent_folder, "mm_projector") + os.makedirs(mm_projector_folder, exist_ok=True) + torch.save(weight_to_save, os.path.join(mm_projector_folder, f'{current_folder}.bin')) + else: + torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin')) + return + + if trainer.deepspeed: + torch.cuda.synchronize() + trainer.save_model(output_dir) + return + + state_dict = trainer.model.state_dict() + if trainer.args.should_save: + cpu_state_dict = { + key: value.cpu() + for key, value in state_dict.items() + } + del state_dict + trainer._save(output_dir, state_dict=cpu_state_dict) # noqa + + +def smart_tokenizer_and_embedding_resize( + special_tokens_dict: Dict, + tokenizer: transformers.PreTrainedTokenizer, + model: transformers.PreTrainedModel, +): + """Resize tokenizer and embedding. + + Note: This is the unoptimized version that may make your embedding size not be divisible by 64. + """ + num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict) + model.resize_token_embeddings(len(tokenizer)) + + if num_new_tokens > 0: + input_embeddings = model.get_input_embeddings().weight.data + output_embeddings = model.get_output_embeddings().weight.data + + input_embeddings_avg = input_embeddings[:-num_new_tokens].mean( + dim=0, keepdim=True) + output_embeddings_avg = output_embeddings[:-num_new_tokens].mean( + dim=0, keepdim=True) + + input_embeddings[-num_new_tokens:] = input_embeddings_avg + output_embeddings[-num_new_tokens:] = output_embeddings_avg + + +def _tokenize_fn(strings: Sequence[str], + tokenizer: transformers.PreTrainedTokenizer) -> Dict: + """Tokenize a list of strings.""" + tokenized_list = [ + tokenizer( + text, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ) for text in strings + ] + input_ids = labels = [ + tokenized.input_ids[0] for tokenized in tokenized_list + ] + input_ids_lens = labels_lens = [ + tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() + for tokenized in tokenized_list + ] + return dict( + input_ids=input_ids, + labels=labels, + input_ids_lens=input_ids_lens, + labels_lens=labels_lens, + ) + + +def _mask_targets(target, tokenized_lens, speakers): + # cur_idx = 0 + cur_idx = tokenized_lens[0] + tokenized_lens = tokenized_lens[1:] + target[:cur_idx] = IGNORE_INDEX + for tokenized_len, speaker in zip(tokenized_lens, speakers): + if speaker == "human": + target[cur_idx+2:cur_idx + tokenized_len] = IGNORE_INDEX + cur_idx += tokenized_len + + +def _add_speaker_and_signal(header, source, get_conversation=True): + """Add speaker and start/end signal on each round.""" + BEGIN_SIGNAL = "### " + END_SIGNAL = "\n" + conversation = header + for sentence in source: + from_str = sentence["from"] + if from_str.lower() == "human": + from_str = conversation_lib.default_conversation.roles[0] + elif from_str.lower() == "gpt": + from_str = conversation_lib.default_conversation.roles[1] + else: + from_str = 'unknown' + sentence["value"] = (BEGIN_SIGNAL + from_str + ": " + + sentence["value"] + END_SIGNAL) + if get_conversation: + conversation += sentence["value"] + conversation += BEGIN_SIGNAL + return conversation + + +def preprocess_multimodal( + sources: Sequence[str], + data_args: DataArguments +) -> Dict: + is_multimodal = data_args.is_multimodal + if not is_multimodal: + return sources + + for source in sources: + for sentence in source: + if DEFAULT_IMAGE_TOKEN in sentence['value']: + sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '').strip() + sentence['value'] = DEFAULT_IMAGE_TOKEN + '\n' + sentence['value'] + sentence['value'] = sentence['value'].strip() + if "mmtag" in conversation_lib.default_conversation.version: + sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '' + DEFAULT_IMAGE_TOKEN + '') + replace_token = DEFAULT_IMAGE_TOKEN + if data_args.mm_use_im_start_end: + replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN + sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token) + + return sources + + +def preprocess_llama_2( + sources, + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False +) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + + assert conv.sep_style == conversation_lib.SeparatorStyle.LLAMA_2 + + # Mask targets + sep = "[/INST] " + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep2) + cur_len = 1 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 2 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print( + f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." + f" (ignored)" + ) + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_v1( + sources, + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False +) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + + assert conv.sep_style == conversation_lib.SeparatorStyle.TWO + + # Mask targets + sep = conv.sep + conv.roles[1] + ": " + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep2) + cur_len = 1 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 2 + + if i != 0 and not tokenizer.legacy and IS_TOKENIZER_GREATER_THAN_0_14: + round_len -= 1 + instruction_len -= 1 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print( + f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." + f" (ignored)" + ) + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_mpt( + sources, + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False +) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + assert conv.sep_style == conversation_lib.SeparatorStyle.MPT + + # Mask targets + sep = conv.sep + conv.roles[1] + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep) + re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt + for conv_idx in range(3, len(rounds), 2): + re_rounds.append(conv.sep.join(rounds[conv_idx:conv_idx+2])) # user + gpt + cur_len = 0 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(re_rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 1 + + if i != 0 and getattr(tokenizer, 'legacy', False) and IS_TOKENIZER_GREATER_THAN_0_14: + round_len += 1 + instruction_len += 1 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print( + f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." + f" (ignored)" + ) + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_plain( + sources: Sequence[str], + tokenizer: transformers.PreTrainedTokenizer, +) -> Dict: + # add end signal and concatenate together + conversations = [] + for source in sources: + assert len(source) == 2 + assert DEFAULT_IMAGE_TOKEN in source[0]['value'] + source[0]['value'] = DEFAULT_IMAGE_TOKEN + conversation = source[0]['value'] + source[1]['value'] + conversation_lib.default_conversation.sep + conversations.append(conversation) + # tokenize conversations + input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations] + targets = copy.deepcopy(input_ids) + for target, source in zip(targets, sources): + tokenized_len = len(tokenizer_image_token(source[0]['value'], tokenizer)) + target[:tokenized_len] = IGNORE_INDEX + + return dict(input_ids=input_ids, labels=targets) + + +def preprocess( + sources: Sequence[str], + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False +) -> Dict: + """ + Given a list of sources, each is a conversation list. This transform: + 1. Add signal '### ' at the beginning each sentence, with end signal '\n'; + 2. Concatenate conversations together; + 3. Tokenize the concatenated conversation; + 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX. + """ + if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN: + return preprocess_plain(sources, tokenizer) + if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.LLAMA_2: + return preprocess_llama_2(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version.startswith("v1"): + return preprocess_v1(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version == "mpt": + return preprocess_mpt(sources, tokenizer, has_image=has_image) + # add end signal and concatenate together + conversations = [] + for source in sources: + header = f"{conversation_lib.default_conversation.system}\n\n" + conversation = _add_speaker_and_signal(header, source) + conversations.append(conversation) + # tokenize conversations + def get_tokenize_len(prompts): + return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts] + + if has_image: + input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations] + else: + conversations_tokenized = _tokenize_fn(conversations, tokenizer) + input_ids = conversations_tokenized["input_ids"] + + targets = copy.deepcopy(input_ids) + for target, source in zip(targets, sources): + if has_image: + tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source]) + else: + tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"] + speakers = [sentence["from"] for sentence in source] + _mask_targets(target, tokenized_lens, speakers) + + return dict(input_ids=input_ids, labels=targets) + +# +# class LazySupervisedDataset(Dataset): +# """Dataset for supervised fine-tuning.""" +# +# def __init__(self, data_path: str, +# tokenizer: transformers.PreTrainedTokenizer, +# data_args: DataArguments): +# super(LazySupervisedDataset, self).__init__() +# list_data_dict = json.load(open(data_path, "r")) +# +# rank0_print("Formatting inputs...Skip in lazy mode") +# self.tokenizer = tokenizer +# self.list_data_dict = list_data_dict +# self.data_args = data_args +# # print("DEBUG: data_args",data_args) +# +# def __len__(self): +# return len(self.list_data_dict) +# +# @property +# def lengths(self): +# length_list = [] +# for sample in self.list_data_dict: +# img_tokens = 128 if 'image' in sample else 0 +# length_list.append(sum(len(conv['value'].split()) for conv in sample['conversations']) + img_tokens) +# return length_list +# +# @property +# def modality_lengths(self): +# length_list = [] +# for sample in self.list_data_dict: +# cur_len = sum(len(conv['value'].split()) for conv in sample['conversations']) +# cur_len = cur_len if 'image' in sample else -cur_len +# length_list.append(cur_len) +# return length_list +# +# def __getitem__(self, i) -> Dict[str, torch.Tensor]: +# sources = self.list_data_dict[i] +# if isinstance(i, int): +# sources = [sources] +# assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME +# if 'image' in sources[0]: +# image_file = self.list_data_dict[i]['image'] +# image_folder = self.data_args.image_folder +# processor = self.data_args.image_processor +# image = Image.open(os.path.join(image_folder, image_file)).convert('RGB') +# +# # print("DEBUG: image_aspect_ratio", self.data_args.image_aspect_ratio) +# if self.data_args.image_aspect_ratio == 'pad': +# def expand2square(pil_img, background_color): +# width, height = pil_img.size +# if width == height: +# return pil_img +# elif width > height: +# result = Image.new(pil_img.mode, (width, width), background_color) +# result.paste(pil_img, (0, (width - height) // 2)) +# return result +# else: +# result = Image.new(pil_img.mode, (height, height), background_color) +# result.paste(pil_img, ((height - width) // 2, 0)) +# return result +# image = expand2square(image, tuple(int(x*255) for x in processor.image_mean)) +# image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0] +# elif self.data_args.image_aspect_ratio == 'square': +# image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0] +# elif self.data_args.image_aspect_ratio == 'anyres_ui': +# # print("GET anyres in train.py") +# # width, height = image.size +# # print("original width and height: ",width,height) +# image,new_size = process_anyres_ui_image(image, processor, fusion=False) +# # exit() +# elif self.data_args.image_aspect_ratio == 'anyres_ui_fusion': +# image,new_size = process_anyres_ui_image(image, processor, fusion=True) +# sources = preprocess_multimodal( +# copy.deepcopy([e["conversations"] for e in sources]), +# self.data_args) +# else: +# sources = copy.deepcopy([e["conversations"] for e in sources]) +# data_dict = preprocess( +# sources, +# self.tokenizer, +# has_image=('image' in self.list_data_dict[i])) +# if isinstance(i, int): +# data_dict = dict(input_ids=data_dict["input_ids"][0], +# labels=data_dict["labels"][0]) +# +# # image exist in the data +# if 'image' in self.list_data_dict[i]: +# data_dict['image'] = image +# if (self.data_args.image_aspect_ratio == 'anyres_ui' or self.data_args.image_aspect_ratio == 'anyres_ui_fusion'): +# data_dict['image_size']=new_size +# # if new_size==(224,224): +# # print("DEBUGGGGG: data_dict['image_size']=new_size: ",new_size) +# else: +# data_dict['image_size'] = (0,0) +# +# +# elif self.data_args.is_multimodal: +# # image does not exist in the data, but the model is multimodal +# crop_size = self.data_args.image_processor.crop_size +# data_dict['image'] = torch.zeros(3, crop_size['height'], crop_size['width']) +# data_dict['image_size'] = (crop_size['height'], crop_size['width']) +# return data_dict + +class LazySupervisedDataset(Dataset): + """Dataset for supervised fine-tuning.""" + + def __init__(self, data_path: str, + tokenizer: transformers.PreTrainedTokenizer, + data_args: DataArguments): + super(LazySupervisedDataset, self).__init__() + self.data_df = pd.read_parquet(data_path) + + rank0_print("Formatting inputs...Skip in lazy mode") + self.tokenizer = tokenizer + self.data_args = data_args + + def __len__(self): + return len(self.data_df) + + @property + def lengths(self): + length_list = [] + for _, sample in self.data_df.iterrows(): + img_tokens = 128 if 'image' in sample else 0 + length_list.append(sum(len(conv['value'].split()) for conv in json.loads(sample['conversations'])) + img_tokens) + return length_list + + @property + def modality_lengths(self): + length_list = [] + for _, sample in self.data_df.iterrows(): + cur_len = sum(len(conv['value'].split()) for conv in json.loads(sample['conversations'])) + cur_len = cur_len if 'image' in sample else -cur_len + length_list.append(cur_len) + return length_list + + def __getitem__(self, i) -> Dict[str, torch.Tensor]: + sample = self.data_df.iloc[i] + sources = json.loads(sample['conversations']) + if isinstance(i, int): + sources = [sources] + assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME + + if 'image' in sample: + image_bytes = sample['image'] + image = Image.open(io.BytesIO(image_bytes)).convert('RGB') + + if self.data_args.image_aspect_ratio == 'pad': + def expand2square(pil_img, background_color): + width, height = pil_img.size + if width == height: + return pil_img + elif width > height: + result = Image.new(pil_img.mode, (width, width), background_color) + result.paste(pil_img, (0, (width - height) // 2)) + return result + else: + result = Image.new(pil_img.mode, (height, height), background_color) + result.paste(pil_img, ((height - width) // 2, 0)) + return result + image = expand2square(image, tuple(int(x*255) for x in self.data_args.image_processor.image_mean)) + image = self.data_args.image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0] + elif self.data_args.image_aspect_ratio == 'square': + image = self.data_args.image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0] + elif self.data_args.image_aspect_ratio == 'anyres_ui': + image, new_size = process_anyres_ui_image(image, self.data_args.image_processor, fusion=False) + elif self.data_args.image_aspect_ratio == 'anyres_ui_fusion': + image, new_size = process_anyres_ui_image(image, self.data_args.image_processor, fusion=True) + sources = preprocess_multimodal( + copy.deepcopy([e for e in sources]), + self.data_args) + else: + sources = copy.deepcopy([e for e in sources]) + + data_dict = preprocess( + sources, + self.tokenizer, + has_image=('image' in sample)) + if isinstance(i, int): + data_dict = dict(input_ids=data_dict["input_ids"][0], + labels=data_dict["labels"][0]) + + # image exist in the data + if 'image' in sample: + data_dict['image'] = image + if (self.data_args.image_aspect_ratio == 'anyres_ui' or self.data_args.image_aspect_ratio == 'anyres_ui_fusion'): + data_dict['image_size'] = new_size + else: + data_dict['image_size'] = (0, 0) + + elif self.data_args.is_multimodal: + crop_size = self.data_args.image_processor.crop_size + data_dict['image'] = torch.zeros(3, crop_size['height'], crop_size['width']) + data_dict['image_size'] = (crop_size['height'], crop_size['width']) + return data_dict + + +@dataclass +class DataCollatorForSupervisedDataset(object): + """Collate examples for supervised fine-tuning.""" + + tokenizer: transformers.PreTrainedTokenizer + + def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]: + input_ids, labels = tuple([instance[key] for instance in instances] + for key in ("input_ids", "labels")) + input_ids = torch.nn.utils.rnn.pad_sequence( + input_ids, + batch_first=True, + padding_value=self.tokenizer.pad_token_id) + labels = torch.nn.utils.rnn.pad_sequence(labels, + batch_first=True, + padding_value=IGNORE_INDEX) + input_ids = input_ids[:, :self.tokenizer.model_max_length] + labels = labels[:, :self.tokenizer.model_max_length] + batch = dict( + input_ids=input_ids, + labels=labels, + attention_mask=input_ids.ne(self.tokenizer.pad_token_id), + ) + + if 'image' in instances[0]: + images = [instance['image'] for instance in instances] + # if all(x is not None and x.shape == images[0].shape for x in images): + # batch['images'] = torch.stack(images) + # else: + # batch['images'] = images + + batch['images'] = images + batch['image_sizes'] = [instance['image_size'] for instance in instances] + # print(f"DEBUG batch['image_sizes'] {batch['image_sizes']}") + + return batch + + +def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, + data_args) -> Dict: + """Make dataset and collator for supervised fine-tuning.""" + train_dataset = LazySupervisedDataset(tokenizer=tokenizer, + data_path=data_args.data_path, + data_args=data_args) + data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer) + return dict(train_dataset=train_dataset, + eval_dataset=None, + data_collator=data_collator) + + +def train(attn_implementation=None): + global local_rank + + parser = transformers.HfArgumentParser( + (ModelArguments, DataArguments, TrainingArguments)) + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + local_rank = training_args.local_rank + compute_dtype = (torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)) + + bnb_model_from_pretrained_args = {} + if training_args.bits in [4, 8]: + from transformers import BitsAndBytesConfig + bnb_model_from_pretrained_args.update(dict( + device_map={"": training_args.device}, + load_in_4bit=training_args.bits == 4, + load_in_8bit=training_args.bits == 8, + quantization_config=BitsAndBytesConfig( + load_in_4bit=training_args.bits == 4, + load_in_8bit=training_args.bits == 8, + llm_int8_skip_modules=["mm_projector"], + llm_int8_threshold=6.0, + llm_int8_has_fp16_weight=False, + bnb_4bit_compute_dtype=compute_dtype, + bnb_4bit_use_double_quant=training_args.double_quant, + bnb_4bit_quant_type=training_args.quant_type # {'fp4', 'nf4'} + ) + )) + + if model_args.vision_tower is not None: + if 'mpt' in model_args.model_name_or_path: + config = transformers.AutoConfig.from_pretrained(model_args.model_name_or_path, trust_remote_code=True) + config.attn_config['attn_impl'] = training_args.mpt_attn_impl + model = LlavaMptForCausalLM.from_pretrained( + model_args.model_name_or_path, + config=config, + cache_dir=training_args.cache_dir, + **bnb_model_from_pretrained_args + ) + else: + model = LlavaLlamaForCausalLM.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + attn_implementation=attn_implementation, + torch_dtype=(torch.bfloat16 if training_args.bf16 else None), + **bnb_model_from_pretrained_args + ) + else: + model = transformers.LlamaForCausalLM.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + attn_implementation=attn_implementation, + torch_dtype=(torch.bfloat16 if training_args.bf16 else None), + **bnb_model_from_pretrained_args + ) + model.config.use_cache = False + + if model_args.freeze_backbone: + model.model.requires_grad_(False) + + if training_args.bits in [4, 8]: + from peft import prepare_model_for_kbit_training + model.config.torch_dtype=(torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)) + model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing) + + if training_args.gradient_checkpointing: + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if training_args.lora_enable: + from peft import LoraConfig, get_peft_model + lora_config = LoraConfig( + r=training_args.lora_r, + lora_alpha=training_args.lora_alpha, + target_modules=find_all_linear_names(model), + lora_dropout=training_args.lora_dropout, + bias=training_args.lora_bias, + task_type="CAUSAL_LM", + ) + if training_args.bits == 16: + if training_args.bf16: + model.to(torch.bfloat16) + if training_args.fp16: + model.to(torch.float16) + rank0_print("Adding LoRA adapters...") + model = get_peft_model(model, lora_config) + + if 'mpt' in model_args.model_name_or_path: + tokenizer = transformers.AutoTokenizer.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + model_max_length=training_args.model_max_length, + padding_side="right" + ) + else: + tokenizer = transformers.AutoTokenizer.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + model_max_length=training_args.model_max_length, + padding_side="right", + use_fast=False, + ) + + if model_args.version == "v0": + if tokenizer.pad_token is None: + smart_tokenizer_and_embedding_resize( + special_tokens_dict=dict(pad_token="[PAD]"), + tokenizer=tokenizer, + model=model, + ) + elif model_args.version == "v0.5": + tokenizer.pad_token = tokenizer.unk_token + else: + tokenizer.pad_token = tokenizer.unk_token + if model_args.version in conversation_lib.conv_templates: + conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version] + else: + conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"] + + if model_args.vision_tower is not None: + model.get_model().initialize_vision_modules( + model_args=model_args, + fsdp=training_args.fsdp + ) + + vision_tower = model.get_vision_tower() + vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device) + + data_args.image_processor = vision_tower.image_processor + data_args.is_multimodal = True + + model.config.image_aspect_ratio = data_args.image_aspect_ratio + model.config.tokenizer_padding_side = tokenizer.padding_side + model.config.tokenizer_model_max_length = tokenizer.model_max_length + # print("DEBUGG!!!-----\'model.config.tokenizer_model_max_length:\'",model.config.tokenizer_model_max_length) + + model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter + if model_args.tune_mm_mlp_adapter: + model.requires_grad_(False) + for p in model.get_model().mm_projector.parameters(): + p.requires_grad = True + + model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter + if training_args.freeze_mm_mlp_adapter: + for p in model.get_model().mm_projector.parameters(): + p.requires_grad = False + + if training_args.bits in [4, 8]: + model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device) + + model.config.mm_use_im_start_end = data_args.mm_use_im_start_end = model_args.mm_use_im_start_end + model.config.mm_projector_lr = training_args.mm_projector_lr + training_args.use_im_start_end = model_args.mm_use_im_start_end + model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token + model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer) + + if training_args.bits in [4, 8]: + from peft.tuners.lora import LoraLayer + for name, module in model.named_modules(): + if isinstance(module, LoraLayer): + if training_args.bf16: + module = module.to(torch.bfloat16) + if 'norm' in name: + module = module.to(torch.float32) + if 'lm_head' in name or 'embed_tokens' in name: + if hasattr(module, 'weight'): + if training_args.bf16 and module.weight.dtype == torch.float32: + module = module.to(torch.bfloat16) + + data_module = make_supervised_data_module(tokenizer=tokenizer, + data_args=data_args) + trainer = LLaVATrainer(model=model, + tokenizer=tokenizer, + args=training_args, + **data_module) + + if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")): + trainer.train(resume_from_checkpoint=True) + else: + trainer.train() + trainer.save_state() + + model.config.use_cache = True + + # print("DEBUG---NAMED_PARAMETERS", model.named_parameters()) + + if training_args.lora_enable: + # print("DEBUG--- ENTER LORA_ENABLE") + + + # print("DEBUG---NONE-LORA-STATE-DICT", model.named_parameters()) + state_dict = get_peft_state_maybe_zero_3( + model.named_parameters(), training_args.lora_bias + ) + + # print("DEBUG---LORA-STATE-DICT",state_dict) + + + # raise Exception + + non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3( + model.named_parameters() + ) + + # print("DEBUG---NONE-LORA-STATE-DICT", non_lora_state_dict) + if training_args.local_rank == 0 or training_args.local_rank == -1: + model.config.save_pretrained(training_args.output_dir) + model.save_pretrained(training_args.output_dir, state_dict=state_dict) + torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, 'non_lora_trainables.bin')) + else: + # print("DEBUG--- ENTER ELSE") + safe_save_model_for_hf_trainer(trainer=trainer, + output_dir=training_args.output_dir) + + +if __name__ == "__main__": + train() diff --git a/llava/train/train_xformers.py b/llava/train/train_xformers.py new file mode 100644 index 0000000000000000000000000000000000000000..23a59bf4ee0f365de9fbf3838836b170058126d6 --- /dev/null +++ b/llava/train/train_xformers.py @@ -0,0 +1,13 @@ +# Make it more memory efficient by monkey patching the LLaMA model with xformers attention. + +# Need to call this before importing transformers. +from llava.train.llama_xformers_attn_monkey_patch import ( + replace_llama_attn_with_xformers_attn, +) + +replace_llama_attn_with_xformers_attn() + +from llava.train.train import train + +if __name__ == "__main__": + train() diff --git a/llava/utils.py b/llava/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4006cf917e26c365080b0844c56fab78c48457c0 --- /dev/null +++ b/llava/utils.py @@ -0,0 +1,126 @@ +import datetime +import logging +import logging.handlers +import os +import sys + +import requests + +from llava.constants import LOGDIR + +server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**" +moderation_msg = "YOUR INPUT VIOLATES OUR CONTENT MODERATION GUIDELINES. PLEASE TRY AGAIN." + +handler = None + + +def build_logger(logger_name, logger_filename): + global handler + + formatter = logging.Formatter( + fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + + # Set the format of root handlers + if not logging.getLogger().handlers: + logging.basicConfig(level=logging.INFO) + logging.getLogger().handlers[0].setFormatter(formatter) + + # Redirect stdout and stderr to loggers + stdout_logger = logging.getLogger("stdout") + stdout_logger.setLevel(logging.INFO) + sl = StreamToLogger(stdout_logger, logging.INFO) + sys.stdout = sl + + stderr_logger = logging.getLogger("stderr") + stderr_logger.setLevel(logging.ERROR) + sl = StreamToLogger(stderr_logger, logging.ERROR) + sys.stderr = sl + + # Get logger + logger = logging.getLogger(logger_name) + logger.setLevel(logging.INFO) + + # Add a file handler for all loggers + if handler is None: + os.makedirs(LOGDIR, exist_ok=True) + filename = os.path.join(LOGDIR, logger_filename) + handler = logging.handlers.TimedRotatingFileHandler( + filename, when='D', utc=True, encoding='UTF-8') + handler.setFormatter(formatter) + + for name, item in logging.root.manager.loggerDict.items(): + if isinstance(item, logging.Logger): + item.addHandler(handler) + + return logger + + +class StreamToLogger(object): + """ + Fake file-like stream object that redirects writes to a logger instance. + """ + def __init__(self, logger, log_level=logging.INFO): + self.terminal = sys.stdout + self.logger = logger + self.log_level = log_level + self.linebuf = '' + + def __getattr__(self, attr): + return getattr(self.terminal, attr) + + def write(self, buf): + temp_linebuf = self.linebuf + buf + self.linebuf = '' + for line in temp_linebuf.splitlines(True): + # From the io.TextIOWrapper docs: + # On output, if newline is None, any '\n' characters written + # are translated to the system default line separator. + # By default sys.stdout.write() expects '\n' newlines and then + # translates them so this is still cross platform. + if line[-1] == '\n': + self.logger.log(self.log_level, line.rstrip()) + else: + self.linebuf += line + + def flush(self): + if self.linebuf != '': + self.logger.log(self.log_level, self.linebuf.rstrip()) + self.linebuf = '' + + +def disable_torch_init(): + """ + Disable the redundant torch default initialization to accelerate model creation. + """ + import torch + setattr(torch.nn.Linear, "reset_parameters", lambda self: None) + setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None) + + +def violates_moderation(text): + """ + Check whether the text violates OpenAI moderation API. + """ + url = "https://api.openai.com/v1/moderations" + headers = {"Content-Type": "application/json", + "Authorization": "Bearer " + os.environ["OPENAI_API_KEY"]} + text = text.replace("\n", "") + data = "{" + '"input": ' + f'"{text}"' + "}" + data = data.encode("utf-8") + try: + ret = requests.post(url, headers=headers, data=data, timeout=5) + flagged = ret.json()["results"][0]["flagged"] + except requests.exceptions.RequestException as e: + flagged = False + except KeyError as e: + flagged = False + + return flagged + + +def pretty_print_semaphore(semaphore): + if semaphore is None: + return "None" + return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})" diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..a1e45cd40cb3d7126e4fa59beef51665c0941759 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,39 @@ +[build-system] +requires = ["setuptools>=61.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "uground_demo_test" +version = "3.1" +description = "Navigating the Digital World as Humans Do: Universal Visual Grounding for GUI Agents" +readme = "README.md" +requires-python = ">=3.8" +classifiers = [ + "Programming Language :: Python :: 3", + "License :: OSI Approved :: Apache Software License", +] +dependencies = [ + "torch==2.0.1", "torchvision==0.15.2", + "transformers==4.36.2", "tokenizers==0.15.0", "sentencepiece==0.1.99", "shortuuid", + "accelerate==0.21.0", "peft==0.4.0", "bitsandbytes==0.41.0", + "pydantic", "markdown2[all]", "numpy", "scikit-learn==1.2.2", + "gradio==4.16.0", "gradio_client==0.8.1", + "requests", "httpx==0.24.0", "uvicorn", "fastapi", + "einops==0.6.1", "einops-exts==0.0.4", "timm==0.6.13","protobuf" +] + + +[project.optional-dependencies] +train = ["deepspeed==0.12.6", "ninja", "wandb"] +build = ["build", "twine"] + + +[project.urls] +"Homepage" = "https://osu-nlp-group.github.io/UGround/" +"Bug Tracker" = "https://github.com/OSU-NLP-Group/UGround/issues" + +[tool.setuptools.packages.find] +exclude = ["assets*", "benchmark*", "docs", "dist*", "playground*", "scripts*", "tests*"] + +[tool.wheel] +exclude = ["assets*", "benchmark*", "docs", "dist*", "playground*", "scripts*", "tests*"] \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..b8904beda376944770c5dfe25e7ca1cb3998bb6d --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +uground-demo-test +protobuf \ No newline at end of file diff --git a/scripts/convert_sqa_to_llava.py b/scripts/convert_sqa_to_llava.py new file mode 100644 index 0000000000000000000000000000000000000000..26fe3002413a23b5029e540c8b338ebb14307bf6 --- /dev/null +++ b/scripts/convert_sqa_to_llava.py @@ -0,0 +1,88 @@ +import json +import os +import fire +import re +from convert_sqa_to_llava_base_prompt import build_prompt_chatbot + + +def convert_to_llava(base_dir, split, prompt_format="QCM-LEA"): + split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[split] + problems = json.load(open(os.path.join(base_dir, "problems.json"))) + + split_problems = build_prompt_chatbot( + problems, split_indices, prompt_format, + use_caption=False, is_test=False) + + target_format = [] + for prob_id, (input, output) in split_problems.items(): + if input.startswith('Question: '): + input = input.replace('Question: ', '') + if output.startswith('Answer: '): + output = output.replace('Answer: ', '') + + raw_prob_data = problems[prob_id] + if raw_prob_data['image'] is None: + target_format.append({ + "id": prob_id, + "conversations": [ + {'from': 'human', 'value': f"{input}"}, + {'from': 'gpt', 'value': f"{output}"}, + ], + }) + + else: + target_format.append({ + "id": prob_id, + "image": os.path.join(prob_id, raw_prob_data['image']), + "conversations": [ + {'from': 'human', 'value': f"{input}\n"}, + {'from': 'gpt', 'value': f"{output}"}, + ], + }) + + print(f'Number of samples: {len(target_format)}') + + with open(os.path.join(base_dir, f"llava_{split}_{prompt_format}.json"), "w") as f: + json.dump(target_format, f, indent=2) + + +def convert_to_jsonl(base_dir, split, prompt_format="QCM-LEPA"): + split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[split] + problems = json.load(open(os.path.join(base_dir, "problems.json"))) + + split_problems = build_prompt_chatbot( + problems, split_indices, prompt_format, + use_caption=False, is_test=False) + + writer = open(os.path.join(base_dir, f"scienceqa_{split}_{prompt_format}.jsonl"), "w") + for prob_id, (input, output) in split_problems.items(): + if input.startswith('Question: '): + input = input.replace('Question: ', '') + if output.startswith('Answer: '): + output = output.replace('Answer: ', '') + + raw_prob_data = problems[prob_id] + if raw_prob_data['image'] is None: + data = { + "id": prob_id, + "instruction": f"{input}", + "output": f"{output}", + } + + else: + data = { + "id": prob_id, + "image": os.path.join(prob_id, raw_prob_data['image']), + "instruction": f"{input}\n", + "output": f"{output}", + } + writer.write(json.dumps(data) + '\n') + writer.close() + + +def main(task, **kwargs): + globals()[task](**kwargs) + + +if __name__ == "__main__": + fire.Fire(main) diff --git a/scripts/convert_sqa_to_llava_base_prompt.py b/scripts/convert_sqa_to_llava_base_prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..b327fcc29eb44d7fe68be35da25bafa0e1d6feba --- /dev/null +++ b/scripts/convert_sqa_to_llava_base_prompt.py @@ -0,0 +1,334 @@ +def get_question_text(problem): + question = problem['question'] + return question + + +def get_context_text(problem, use_caption): + txt_context = problem['hint'] + img_context = problem['caption'] if use_caption else "" + context = " ".join([txt_context, img_context]).strip() + if context == "": + context = "N/A" + return context + + +def get_choice_text(probelm, options): + choices = probelm['choices'] + choice_list = [] + for i, c in enumerate(choices): + choice_list.append("({}) {}".format(options[i], c)) + choice_txt = " ".join(choice_list) + #print(choice_txt) + return choice_txt + + +def get_answer(problem, options): + return options[problem['answer']] + + +def get_lecture_text(problem): + # \\n: GPT-3 can generate the lecture with more tokens. + lecture = problem['lecture'].replace("\n", "\\n") + return lecture + + +def get_solution_text(problem): + # \\n: GPT-3 can generate the solution with more tokens + solution = problem['solution'].replace("\n", "\\n") + return solution + + +def create_one_example_chatbot(format, question, context, choice, answer, lecture, solution, test_example=True): + + input_format, output_format = format.split("-") + + ## Inputs + if input_format == "CQM": + input = f"Context: {context}\nQuestion: {question}\nOptions: {choice}\n" + elif input_format == "QCM": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\n" + # upper bound experiment + elif input_format == "QCML": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture}\n" + elif input_format == "QCME": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {solution}\n" + elif input_format == "QCMLE": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture} {solution}\n" + + elif input_format == "QCLM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture}\nOptions: {choice}\n" + elif input_format == "QCEM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {solution}\nOptions: {choice}\n" + elif input_format == "QCLEM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture} {solution}\nOptions: {choice}\n" + + # Outputs + if test_example: + output = "Answer:" + elif output_format == 'A': + output = f"Answer: The answer is {answer}." + + elif output_format == 'AL': + output = f"Answer: The answer is {answer}. BECAUSE: {solution}" + elif output_format == 'AE': + output = f"Answer: The answer is {answer}. BECAUSE: {lecture}" + elif output_format == 'ALE': + output = f"Answer: The answer is {answer}. BECAUSE: {lecture} {solution}" + elif output_format == 'AEL': + output = f"Answer: The answer is {answer}. BECAUSE: {solution} {lecture}" + + elif output_format == 'LA': + output = f"Answer: {lecture} The answer is {answer}." + elif output_format == 'EA': + output = f"Answer: {solution} The answer is {answer}." + elif output_format == 'LEA': + output = f"Answer: {lecture} {solution} The answer is {answer}." + elif output_format == 'ELA': + output = f"Answer: {solution} {lecture} The answer is {answer}." + elif output_format == 'LEPA': + output = '' + if len(lecture.strip()) > 0: + output += f"LECTURE: {lecture}\n" + if len(solution.strip()) > 0: + output += f"SOLUTION: {solution}\n" + output += '###\n' + output += f"ANSWER: {answer}." + + input = input.replace(" ", " ").strip() + output = output.replace(" ", " ").strip() + if input.endswith("BECAUSE:"): + input = input.replace("BECAUSE:", "").strip() + if output.endswith("BECAUSE:"): + output = output.replace("BECAUSE:", "").strip() + return input, output + + +def create_one_example(format, question, context, choice, answer, lecture, solution, test_example=True): + + input_format, output_format = format.split("-") + + ## Inputs + if input_format == "CQM": + input = f"Context: {context}\nQuestion: {question}\nOptions: {choice}\n" + elif input_format == "QCM": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\n" + # upper bound experiment + elif input_format == "QCML": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture}\n" + elif input_format == "QCME": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {solution}\n" + elif input_format == "QCMLE": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture} {solution}\n" + + elif input_format == "QCLM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture}\nOptions: {choice}\n" + elif input_format == "QCEM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {solution}\nOptions: {choice}\n" + elif input_format == "QCLEM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture} {solution}\nOptions: {choice}\n" + + # Outputs + if test_example: + output = "Answer:" + elif output_format == 'A': + output = f"Answer: The answer is {answer}." + + elif output_format == 'AL': + output = f"Answer: The answer is {answer}. BECAUSE: {solution}" + elif output_format == 'AE': + output = f"Answer: The answer is {answer}. BECAUSE: {lecture}" + elif output_format == 'ALE': + output = f"Answer: The answer is {answer}. BECAUSE: {lecture} {solution}" + elif output_format == 'AEL': + output = f"Answer: The answer is {answer}. BECAUSE: {solution} {lecture}" + + elif output_format == 'LA': + output = f"Answer: {lecture} The answer is {answer}." + elif output_format == 'EA': + output = f"Answer: {solution} The answer is {answer}." + elif output_format == 'LEA': + output = f"Answer: {lecture} {solution} The answer is {answer}." + elif output_format == 'ELA': + output = f"Answer: {solution} {lecture} The answer is {answer}." + + text = input + output + text = text.replace(" ", " ").strip() + if text.endswith("BECAUSE:"): + text = text.replace("BECAUSE:", "").strip() + return text + + + +def create_one_example_gpt4(format, question, context, choice, answer, lecture, solution, test_example=True): + + input_format, output_format = format.split("-") + + ## Inputs + if input_format == "CQM": + input = f"Context: {context}\nQuestion: {question}\nOptions: {choice}\n" + elif input_format == "QCM": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\n" + # upper bound experiment + elif input_format == "QCML": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture}\n" + elif input_format == "QCME": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {solution}\n" + elif input_format == "QCMLE": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture} {solution}\n" + + elif input_format == "QCLM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture}\nOptions: {choice}\n" + elif input_format == "QCEM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {solution}\nOptions: {choice}\n" + elif input_format == "QCLEM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture} {solution}\nOptions: {choice}\n" + + # Outputs + if test_example: + output = "Answer:" + elif output_format == 'A': + output = f"Answer: The answer is {answer}." + + elif output_format == 'AL': + output = f"Answer: The answer is {answer}. BECAUSE: {solution}" + elif output_format == 'AE': + output = f"Answer: The answer is {answer}. BECAUSE: {lecture}" + elif output_format == 'ALE': + output = f"Answer: The answer is {answer}. BECAUSE: {lecture} {solution}" + elif output_format == 'AEL': + output = f"Answer: The answer is {answer}. BECAUSE: {solution} {lecture}" + + elif output_format == 'LA': + output = f"Answer: {lecture} The answer is {answer}." + elif output_format == 'EA': + output = f"Answer: {solution} The answer is {answer}." + elif output_format == 'LEA': + output = f"Answer: {lecture} {solution} The answer is {answer}." + elif output_format == 'ELA': + output = f"Answer: {solution} {lecture} The answer is {answer}." + + input = input.replace(" ", " ").strip() + output = output.replace(" ", " ").strip() + if output.endswith("BECAUSE:"): + output = output.replace("BECAUSE:", "").strip() + + user_prompt = {"role": "user", "content": f"Can you explain {input}?"} + assistant_prompt = {"role": "assistant", "content": f"{output}"} + + return user_prompt, assistant_prompt + + +def build_prompt_chatbot(problems, shot_qids, prompt_format, use_caption=False, options=["A", "B", "C", "D", "E"], is_test=False): + examples = {} + + for qid in shot_qids: + question = get_question_text(problems[qid]) + context = get_context_text(problems[qid], use_caption) + choice = get_choice_text(problems[qid], options) + answer = get_answer(problems[qid], options) + lecture = get_lecture_text(problems[qid]).replace('\\n', '\n') + solution = get_solution_text(problems[qid]).replace('\\n', '\n') + + train_example = create_one_example_chatbot(prompt_format, + question, + context, + choice, + answer, + lecture, + solution, + test_example=is_test) + examples[qid] = train_example + return examples + + +def build_prompt(problems, shot_qids, test_qid, args): + + examples = [] + + # n-shot training examples + for qid in shot_qids: + question = get_question_text(problems[qid]) + context = get_context_text(problems[qid], args.use_caption) + choice = get_choice_text(problems[qid], args.options) + answer = get_answer(problems[qid], args.options) + lecture = get_lecture_text(problems[qid]) + solution = get_solution_text(problems[qid]) + + train_example = create_one_example(args.prompt_format, + question, + context, + choice, + answer, + lecture, + solution, + test_example=False) + examples.append(train_example) + + # test example + question = get_question_text(problems[test_qid]) + context = get_context_text(problems[test_qid], args.use_caption) + choice = get_choice_text(problems[test_qid], args.options) + answer = get_answer(problems[test_qid], args.options) + lecture = get_lecture_text(problems[test_qid]) + solution = get_solution_text(problems[test_qid]) + + test_example = create_one_example(args.prompt_format, + question, + context, + choice, + answer, + lecture, + solution, + test_example=True) + examples.append(test_example) + + # create the prompt input + prompt_input = '\n\n'.join(examples) + + return prompt_input + + +def build_prompt_gpt4(problems, shot_qids, test_qid, args): + + prompt_array = [{"role": "system", "content": "You are a helpful assistant."}] + + # n-shot training examples + for qid in shot_qids: + question = get_question_text(problems[qid]) + context = get_context_text(problems[qid], args.use_caption) + choice = get_choice_text(problems[qid], args.options) + answer = get_answer(problems[qid], args.options) + lecture = get_lecture_text(problems[qid]) + solution = get_solution_text(problems[qid]) + + user_prompt, assistant_prompt = create_one_example_gpt4(args.prompt_format, + question, + context, + choice, + answer, + lecture, + solution, + test_example=False) + prompt_array.append(user_prompt) + prompt_array.append(assistant_prompt) + + # test example + question = get_question_text(problems[test_qid]) + context = get_context_text(problems[test_qid], args.use_caption) + choice = get_choice_text(problems[test_qid], args.options) + answer = get_answer(problems[test_qid], args.options) + lecture = get_lecture_text(problems[test_qid]) + solution = get_solution_text(problems[test_qid]) + + user_prompt, assistant_prompt = create_one_example_gpt4(args.prompt_format, + question, + context, + choice, + answer, + lecture, + solution, + test_example=True) + prompt_array.append(user_prompt) + prompt_array.append(assistant_prompt) + + return prompt_array \ No newline at end of file diff --git a/scripts/finetune.sh b/scripts/finetune.sh new file mode 100644 index 0000000000000000000000000000000000000000..9314affd72bd06ab260c3e8b36fbf5a4974c995f --- /dev/null +++ b/scripts/finetune.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +# Uncomment and set the following variables correspondingly to run this script: + +################## VICUNA ################## +# PROMPT_VERSION=v1 +# MODEL_VERSION="vicuna-v1-3-7b" +################## VICUNA ################## + +################## LLaMA-2 ################## +# PROMPT_VERSION="llava_llama_2" +# MODEL_VERSION="llama-2-7b-chat" +################## LLaMA-2 ################## + +deepspeed llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path ./playground/data/llava_instruct_80k.json \ + --image_folder /path/to/coco/train2017 \ + --vision_tower openai/clip-vit-large-patch14 \ + --pretrain_mm_mlp_adapter ./checkpoints/llava-$MODEL_VERSION-pretrain/mm_projector.bin \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava-$MODEL_VERSION-finetune \ + --num_train_epochs 1 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --dataloader_num_workers 4 \ + --lazy_preprocess True \ + --report_to wandb diff --git a/scripts/finetune_full_schedule.sh b/scripts/finetune_full_schedule.sh new file mode 100644 index 0000000000000000000000000000000000000000..533f3f4097db3844846d4a843d765c6df1762ba0 --- /dev/null +++ b/scripts/finetune_full_schedule.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +# Uncomment and set the following variables correspondingly to run this script: + +################## VICUNA ################## +# PROMPT_VERSION=v1 +# MODEL_VERSION="vicuna-v1-3-7b" +################## VICUNA ################## + +################## LLaMA-2 ################## +# PROMPT_VERSION="llava_llama_2" +# MODEL_VERSION="llama-2-7b-chat" +################## LLaMA-2 ################## + +deepspeed llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path ./playground/data/llava_instruct_158k.json \ + --image_folder /path/to/coco/train2017 \ + --vision_tower openai/clip-vit-large-patch14 \ + --pretrain_mm_mlp_adapter ./checkpoints/llava-$MODEL_VERSION-pretrain/mm_projector.bin \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava-$MODEL_VERSION-finetune \ + --num_train_epochs 3 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --dataloader_num_workers 4 \ + --lazy_preprocess True \ + --report_to wandb diff --git a/scripts/finetune_lora.sh b/scripts/finetune_lora.sh new file mode 100644 index 0000000000000000000000000000000000000000..46242a6371e8c9680dcfec5c955c3610555a3146 --- /dev/null +++ b/scripts/finetune_lora.sh @@ -0,0 +1,47 @@ +#!/bin/bash + +# Uncomment and set the following variables correspondingly to run this script: + +################## VICUNA ################## +# PROMPT_VERSION=v1 +# MODEL_VERSION="vicuna-v1-3-7b" +################## VICUNA ################## + +################## LLaMA-2 ################## +# PROMPT_VERSION="llava_llama_2" +# MODEL_VERSION="llama-2-7b-chat" +################## LLaMA-2 ################## + +deepspeed llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --lora_enable True \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path ./playground/data/llava_instruct_80k.json \ + --image_folder /path/to/coco/train2017 \ + --vision_tower openai/clip-vit-large-patch14 \ + --pretrain_mm_mlp_adapter ./checkpoints/llava-$MODEL_VERSION-pretrain/mm_projector.bin \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava-$MODEL_VERSION-finetune_lora \ + --num_train_epochs 1 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --lazy_preprocess True \ + --dataloader_num_workers 4 \ + --report_to wandb diff --git a/scripts/finetune_qlora.sh b/scripts/finetune_qlora.sh new file mode 100644 index 0000000000000000000000000000000000000000..1af397d40c925aa18794ffc9650c7cb50f0430d7 --- /dev/null +++ b/scripts/finetune_qlora.sh @@ -0,0 +1,48 @@ +#!/bin/bash + +# Uncomment and set the following variables correspondingly to run this script: + +################## VICUNA ################## +# PROMPT_VERSION=v1 +# MODEL_VERSION="vicuna-v1-3-7b" +################## VICUNA ################## + +################## LLaMA-2 ################## +# PROMPT_VERSION="llava_llama_2" +# MODEL_VERSION="llama-2-7b-chat" +################## LLaMA-2 ################## + +deepspeed llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --lora_enable True \ + --bits 4 \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path ./playground/data/llava_instruct_80k.json \ + --image_folder /path/to/coco/train2017 \ + --vision_tower openai/clip-vit-large-patch14 \ + --pretrain_mm_mlp_adapter ./checkpoints/llava-$MODEL_VERSION-pretrain/mm_projector.bin \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava-$MODEL_VERSION-finetune_lora \ + --num_train_epochs 1 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --lazy_preprocess True \ + --dataloader_num_workers 4 \ + --report_to wandb diff --git a/scripts/finetune_sqa.sh b/scripts/finetune_sqa.sh new file mode 100644 index 0000000000000000000000000000000000000000..2c1590fdc7511370e8ccc285dcc9c053379b9134 --- /dev/null +++ b/scripts/finetune_sqa.sh @@ -0,0 +1,34 @@ +#!/bin/bash + +deepspeed llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --model_name_or_path lmsys/vicuna-13b-v1.3 \ + --version $PROMPT_VERSION \ + --data_path /Data/ScienceQA/data/scienceqa/llava_train_QCM-LEA.json \ + --image_folder /Data/ScienceQA/data/scienceqa/images/train \ + --vision_tower openai/clip-vit-large-patch14 \ + --pretrain_mm_mlp_adapter ./checkpoints/huggingface/liuhaotian/llava-pretrain-vicuna-13b-v1.3/mm_projector.bin \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava-vicuna-13b-v1.3-pretrain_lcs558k_plain-ScienceQA_QCM_LEA-12e \ + --num_train_epochs 12 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --dataloader_num_workers 4 \ + --lazy_preprocess True \ + --report_to wandb diff --git a/scripts/merge_lora_weights.py b/scripts/merge_lora_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..3b39cc7beb12301379af7daebbb5553fa92093ea --- /dev/null +++ b/scripts/merge_lora_weights.py @@ -0,0 +1,22 @@ +import argparse +from llava.model.builder import load_pretrained_model +from llava.mm_utils import get_model_name_from_path + + +def merge_lora(args): + model_name = get_model_name_from_path(args.model_path) + tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, device_map='cpu') + + model.save_pretrained(args.save_model_path) + tokenizer.save_pretrained(args.save_model_path) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--model-path", type=str, required=True) + parser.add_argument("--model-base", type=str, required=True) + parser.add_argument("--save-model-path", type=str, required=True) + + args = parser.parse_args() + + merge_lora(args) diff --git a/scripts/pretrain.sh b/scripts/pretrain.sh new file mode 100644 index 0000000000000000000000000000000000000000..5326e4cc47b78fef423a76823b66982fb66227b2 --- /dev/null +++ b/scripts/pretrain.sh @@ -0,0 +1,44 @@ +#!/bin/bash + +# Uncomment and set the following variables correspondingly to run this script: + +# MODEL_VERSION=vicuna-v1-3-7b +# MODEL_VERSION=llama-2-7b-chat + +########### DO NOT CHANGE ########### +########### USE THIS FOR BOTH ########### +PROMPT_VERSION=plain +########### DO NOT CHANGE ########### + +deepspeed llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path /path/to/pretrain_data.json \ + --image_folder /path/to/images \ + --vision_tower openai/clip-vit-large-patch14 \ + --tune_mm_mlp_adapter True \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava-$MODEL_VERSION-pretrain \ + --num_train_epochs 1 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 24000 \ + --save_total_limit 1 \ + --learning_rate 2e-3 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --dataloader_num_workers 4 \ + --lazy_preprocess True \ + --report_to wandb diff --git a/scripts/sqa_eval_batch.sh b/scripts/sqa_eval_batch.sh new file mode 100644 index 0000000000000000000000000000000000000000..adbf46ef7a6e86181b5927002597ef786add5bde --- /dev/null +++ b/scripts/sqa_eval_batch.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +CHUNKS=8 +for IDX in {0..7}; do + CUDA_VISIBLE_DEVICES=$IDX python -m llava.eval.model_vqa_science \ + --model-path liuhaotian/llava-lcs558k-scienceqa-vicuna-13b-v1.3 \ + --question-file ~/haotian/datasets/ScienceQA/data/scienceqa/llava_test_QCM-LEA.json \ + --image-folder ~/haotian/datasets/ScienceQA/data/scienceqa/images/test \ + --answers-file ./test_llava-13b-chunk$CHUNKS_$IDX.jsonl \ + --num-chunks $CHUNKS \ + --chunk-idx $IDX \ + --conv-mode llava_v1 & +done diff --git a/scripts/sqa_eval_gather.sh b/scripts/sqa_eval_gather.sh new file mode 100644 index 0000000000000000000000000000000000000000..525bd43b850e9f6a923158abd23bca6f8d15650e --- /dev/null +++ b/scripts/sqa_eval_gather.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +CHUNKS=8 +output_file="test_llava-13b.jsonl" + +# Clear out the output file if it exists. +> "$output_file" + +# Loop through the indices and concatenate each file. +for idx in $(seq 0 $((CHUNKS-1))); do + cat "./test_llava-13b-chunk${idx}.jsonl" >> "$output_file" +done + +python llava/eval/eval_science_qa.py \ + --base-dir ~/haotian/datasets/ScienceQA/data/scienceqa \ + --result-file ./test_llava-13b.jsonl \ + --output-file ./test_llava-13b_output.json \ + --output-result ./test_llava-13b_result.json