diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..c7d9f3332a950355d5a77d85000f05e6f45435ea 100644 --- a/.gitattributes +++ b/.gitattributes @@ -25,7 +25,6 @@ *.safetensors filter=lfs diff=lfs merge=lfs -text saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.tar.* filter=lfs diff=lfs merge=lfs -text -*.tar filter=lfs diff=lfs merge=lfs -text *.tflite filter=lfs diff=lfs merge=lfs -text *.tgz filter=lfs diff=lfs merge=lfs -text *.wasm filter=lfs diff=lfs merge=lfs -text diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..25ae4110625608b553d170b6bb5c439215503afe --- /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 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. diff --git a/README.md b/README.md index aad67300737b18bb2803fa14d203d9251aac26b4..e139db58b05e45d15a6763683e7d9b6587389c09 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ --- -title: Test -emoji: 📊 +title: test colorFrom: yellow colorTo: yellow sdk: gradio -sdk_version: 5.9.1 +sdk_version: 3.41.2 app_file: app.py pinned: false +license: apache-2.0 --- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/app.py b/app.py new file mode 100644 index 0000000000000000000000000000000000000000..d4bb1f140028f8d79d99dce983e4fd15522be605 --- /dev/null +++ b/app.py @@ -0,0 +1 @@ +generate.py \ No newline at end of file diff --git a/generate.py b/generate.py new file mode 100644 index 0000000000000000000000000000000000000000..c2c333e6a29beb449674746cd2f333f55c3fe34b --- /dev/null +++ b/generate.py @@ -0,0 +1,16 @@ +import os +import sys + +if os.path.dirname(os.path.abspath(__file__)) not in sys.path: + sys.path.append(os.path.dirname(os.path.abspath(__file__))) + +from src.gen import main +from src.utils import H2O_Fire + + +def entrypoint_main(): + H2O_Fire(main) + + +if __name__ == "__main__": + entrypoint_main() diff --git a/gradio_utils/__init__.py b/gradio_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gradio_utils/__pycache__/__init__.cpython-310.pyc b/gradio_utils/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47a84de0e2a5040e96b0477dd6652fa3c45175bb Binary files /dev/null and b/gradio_utils/__pycache__/__init__.cpython-310.pyc differ diff --git a/gradio_utils/__pycache__/css.cpython-310.pyc b/gradio_utils/__pycache__/css.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..639b737f0fa08967d7d53f76176ddbecf696dee8 Binary files /dev/null and b/gradio_utils/__pycache__/css.cpython-310.pyc differ diff --git a/gradio_utils/__pycache__/grclient.cpython-310.pyc b/gradio_utils/__pycache__/grclient.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fae2390da62d66ce5a73f3b207536f3f25ebf8ab Binary files /dev/null and b/gradio_utils/__pycache__/grclient.cpython-310.pyc differ diff --git a/gradio_utils/__pycache__/prompt_form.cpython-310.pyc b/gradio_utils/__pycache__/prompt_form.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2113410dcc6a8bfb6fb1922bfc9df2d28678659 Binary files /dev/null and b/gradio_utils/__pycache__/prompt_form.cpython-310.pyc differ diff --git a/gradio_utils/css.py b/gradio_utils/css.py new file mode 100644 index 0000000000000000000000000000000000000000..6f3d0dd56bfd4287034afd0b23751e3abd59a143 --- /dev/null +++ b/gradio_utils/css.py @@ -0,0 +1,148 @@ +def get_css(kwargs) -> str: + if kwargs['h2ocolors']: + css_code = """footer {visibility: hidden;} + body{background:linear-gradient(#f5f5f5,#e5e5e5);} + body.dark{background:linear-gradient(#000000,#0d0d0d);} + """ + else: + css_code = """footer {visibility: hidden}""" + + css_code += make_css_base() + return css_code + + +def make_css_base() -> str: + return """ + #col_container {margin-left: auto; margin-right: auto; text-align: left;} + + @import url('https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@400;600&display=swap'); + + body.dark{#warning {background-color: #555555};} + + #sidebar { + order: 1; + + @media (max-width: 463px) { + order: 2; + } + } + + #col-tabs { + order: 2; + + @media (max-width: 463px) { + order: 1; + } + } + + #small_btn { + margin: 0.6em 0em 0.55em 0; + max-width: 20em; + min-width: 5em !important; + height: 5em; + font-size: 14px !important; + } + + #prompt-form { + border: 1px solid var(--primary-500) !important; + } + + #prompt-form.block { + border-radius: var(--block-radius) !important; + } + + #prompt-form textarea { + border: 1px solid rgb(209, 213, 219); + } + + #prompt-form label > div { + margin-top: 4px; + } + + button.primary:hover { + background-color: var(--primary-600) !important; + transition: .2s; + } + + #prompt-form-area { + margin-bottom: 2.5rem; + } + .chatsmall chatbot {font-size: 10px !important} + + .gradio-container { + max-width: none !important; + } + + div.message { + padding: var(--text-lg) !important; + } + + div.message.user > div.icon-button { + top: unset; + bottom: 0; + } + + div.message.bot > div.icon-button { + top: unset; + bottom: 0; + } + + #prompt-form-row { + position: relative; + } + + #attach-button { + position: absolute; + top: 45px; + right: 20px; + + display: flex; + justify-content: center; + border: 1px solid var(--primary-500) !important; + + @media (max-width: 463px) { + width: 56px; + } + } + + #attach-button > img { + margin-right: 0; + } + + #prompt-form > label > textarea { + padding-right: 104px; + + @media (max-width: 463px) { + min-height: 94px; + padding-right: 70px; + } + } + + #visible-models > label > div.wrap > div.wrap-inner > div.secondary-wrap > div.remove-all { + display: none !important; + } + + #visible-models > label > div.wrap > div.wrap-inner > div.token { + display: none !important; + } + + #visible-models > label > div.wrap > div.wrap-inner > div.secondary-wrap::before { + content: "Select"; + padding: 0 4px; + margin-right: 2px; + } + + #langchain_agents > label > div.wrap > div.wrap-inner > div.secondary-wrap > div.remove-all { + display: none !important; + } + + #langchain_agents > label > div.wrap > div.wrap-inner > div.token { + display: none !important; + } + + #langchain_agents > label > div.wrap > div.wrap-inner > div.secondary-wrap::before { + content: "Select"; + padding: 0 4px; + margin-right: 2px; + } + """ diff --git a/gradio_utils/grclient.py b/gradio_utils/grclient.py new file mode 100644 index 0000000000000000000000000000000000000000..8346a61cad99d492f8a10de17851454488364b83 --- /dev/null +++ b/gradio_utils/grclient.py @@ -0,0 +1,82 @@ +import traceback +from typing import Callable +import os + +from gradio_client.client import Job + +os.environ['HF_HUB_DISABLE_TELEMETRY'] = '1' + +from gradio_client import Client + + +class GradioClient(Client): + """ + Parent class of gradio client + To handle automatically refreshing client if detect gradio server changed + """ + + def __init__(self, *args, **kwargs): + self.args = args + self.kwargs = kwargs + super().__init__(*args, **kwargs) + self.server_hash = self.get_server_hash() + + def get_server_hash(self): + """ + Get server hash using super without any refresh action triggered + Returns: git hash of gradio server + """ + return super().submit(api_name='/system_hash').result() + + def refresh_client_if_should(self): + # get current hash in order to update api_name -> fn_index map in case gradio server changed + # FIXME: Could add cli api as hash + server_hash = self.get_server_hash() + if self.server_hash != server_hash: + self.refresh_client() + self.server_hash = server_hash + else: + self.reset_session() + + def refresh_client(self): + """ + Ensure every client call is independent + Also ensure map between api_name and fn_index is updated in case server changed (e.g. restarted with new code) + Returns: + """ + # need session hash to be new every time, to avoid "generator already executing" + self.reset_session() + + client = Client(*self.args, **self.kwargs) + for k, v in client.__dict__.items(): + setattr(self, k, v) + + def submit( + self, + *args, + api_name: str | None = None, + fn_index: int | None = None, + result_callbacks: Callable | list[Callable] | None = None, + ) -> Job: + # Note predict calls submit + try: + self.refresh_client_if_should() + job = super().submit(*args, api_name=api_name, fn_index=fn_index) + except Exception as e: + print("Hit e=%s" % str(e), flush=True) + # force reconfig in case only that + self.refresh_client() + job = super().submit(*args, api_name=api_name, fn_index=fn_index) + + # see if immediately failed + e = job.future._exception + if e is not None: + print("GR job failed: %s %s" % (str(e), ''.join(traceback.format_tb(e.__traceback__))), flush=True) + # force reconfig in case only that + self.refresh_client() + job = super().submit(*args, api_name=api_name, fn_index=fn_index) + e2 = job.future._exception + if e2 is not None: + print("GR job failed again: %s\n%s" % (str(e2), ''.join(traceback.format_tb(e2.__traceback__))), flush=True) + + return job diff --git a/gradio_utils/prompt_form.py b/gradio_utils/prompt_form.py new file mode 100644 index 0000000000000000000000000000000000000000..d79b51833d207c867e5ceb1040169193bed4bf9a --- /dev/null +++ b/gradio_utils/prompt_form.py @@ -0,0 +1,108 @@ +import os +import math + +import gradio as gr + + +def make_chatbots(output_label0, output_label0_model2, **kwargs): + visible_models = kwargs['visible_models'] + all_models = kwargs['all_models'] + + text_outputs = [] + chat_kwargs = [] + for model_state_locki, model_state_lock in enumerate(kwargs['model_states']): + if os.environ.get('DEBUG_MODEL_LOCK'): + model_name = model_state_lock["base_model"] + " : " + model_state_lock["inference_server"] + else: + model_name = model_state_lock["base_model"] + output_label = f'h2oGPT [{model_name}]' + min_width = 250 if kwargs['gradio_size'] in ['small', 'large', 'medium'] else 160 + chat_kwargs.append(dict(label=output_label, elem_classes='chatsmall', + height=kwargs['height'] or 400, min_width=min_width, + show_copy_button=kwargs['show_copy_button'], + visible=kwargs['model_lock'] and (visible_models is None or + model_state_locki in visible_models or + all_models[model_state_locki] in visible_models + ))) + + # base view on initial visible choice + if visible_models: + len_visible = len(visible_models) + else: + len_visible = len(kwargs['model_states']) + if kwargs['model_lock_columns'] == -1: + kwargs['model_lock_columns'] = len_visible + if kwargs['model_lock_columns'] is None: + kwargs['model_lock_columns'] = 3 + + ncols = kwargs['model_lock_columns'] + if kwargs['model_states'] == 0: + nrows = 0 + else: + nrows = math.ceil(len_visible / kwargs['model_lock_columns']) + + if kwargs['model_lock_columns'] == 0: + # not using model_lock + pass + elif nrows <= 1: + with gr.Row(): + for chat_kwargs1, model_state_lock in zip(chat_kwargs, kwargs['model_states']): + text_outputs.append(gr.Chatbot(**chat_kwargs1)) + elif nrows == kwargs['model_states']: + with gr.Row(): + for chat_kwargs1, model_state_lock in zip(chat_kwargs, kwargs['model_states']): + text_outputs.append(gr.Chatbot(**chat_kwargs1)) + elif nrows == 2: + with gr.Row(): + for mii, (chat_kwargs1, model_state_lock) in enumerate(zip(chat_kwargs, kwargs['model_states'])): + if mii >= len_visible / 2: + continue + text_outputs.append(gr.Chatbot(**chat_kwargs1)) + with gr.Row(): + for mii, (chat_kwargs1, model_state_lock) in enumerate(zip(chat_kwargs, kwargs['model_states'])): + if mii < len_visible / 2: + continue + text_outputs.append(gr.Chatbot(**chat_kwargs1)) + elif nrows == 3: + with gr.Row(): + for mii, (chat_kwargs1, model_state_lock) in enumerate(zip(chat_kwargs, kwargs['model_states'])): + if mii >= 1 * len_visible / 3: + continue + text_outputs.append(gr.Chatbot(**chat_kwargs1)) + with gr.Row(): + for mii, (chat_kwargs1, model_state_lock) in enumerate(zip(chat_kwargs, kwargs['model_states'])): + if mii < 1 * len_visible / 3 or mii >= 2 * len_visible / 3: + continue + text_outputs.append(gr.Chatbot(**chat_kwargs1)) + with gr.Row(): + for mii, (chat_kwargs1, model_state_lock) in enumerate(zip(chat_kwargs, kwargs['model_states'])): + if mii < 2 * len_visible / 3: + continue + text_outputs.append(gr.Chatbot(**chat_kwargs1)) + elif nrows >= 4: + with gr.Row(): + for mii, (chat_kwargs1, model_state_lock) in enumerate(zip(chat_kwargs, kwargs['model_states'])): + if mii >= 1 * len_visible / 4: + continue + text_outputs.append(gr.Chatbot(**chat_kwargs1)) + with gr.Row(): + for mii, (chat_kwargs1, model_state_lock) in enumerate(zip(chat_kwargs, kwargs['model_states'])): + if mii < 1 * len_visible / 4 or mii >= 2 * len_visible / 4: + continue + text_outputs.append(gr.Chatbot(**chat_kwargs1)) + with gr.Row(): + for mii, (chat_kwargs1, model_state_lock) in enumerate(zip(chat_kwargs, kwargs['model_states'])): + if mii < 2 * len_visible / 4 or mii >= 3 * len_visible / 4: + continue + text_outputs.append(gr.Chatbot(**chat_kwargs1)) + with gr.Row(): + for mii, (chat_kwargs1, model_state_lock) in enumerate(zip(chat_kwargs, kwargs['model_states'])): + if mii < 3 * len_visible / 4: + continue + text_outputs.append(gr.Chatbot(**chat_kwargs1)) + + with gr.Row(): + text_output = gr.Chatbot(label=output_label0, visible=not kwargs['model_lock'], height=kwargs['height'] or 400) + text_output2 = gr.Chatbot(label=output_label0_model2, + visible=False and not kwargs['model_lock'], height=kwargs['height'] or 400) + return text_output, text_output2, text_outputs diff --git a/h2o-logo.svg b/h2o-logo.svg new file mode 100644 index 0000000000000000000000000000000000000000..d6b04435700ffae6284031d15b2220ea53bdce7f --- /dev/null +++ b/h2o-logo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/iterators/__init__.py b/iterators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d800eac15a042c02c0d8b31f086db83ade229a53 --- /dev/null +++ b/iterators/__init__.py @@ -0,0 +1,4 @@ +from .timeout_iterator import TimeoutIterator, AsyncTimeoutIterator +from .iterator_pipe import IteratorPipe, AsyncIteratorPipe + +__all__ = ["TimeoutIterator", "AsyncTimeoutIterator", "IteratorPipe", "AsyncIteratorPipe"] \ No newline at end of file diff --git a/iterators/__pycache__/__init__.cpython-310.pyc b/iterators/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92a8d3cef6c28e4df6e8911b2f5ce838445b618c Binary files /dev/null and b/iterators/__pycache__/__init__.cpython-310.pyc differ diff --git a/iterators/__pycache__/iterator_pipe.cpython-310.pyc b/iterators/__pycache__/iterator_pipe.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3aa9bfb7ba8fe0fbd81f3ea4cba3062fc2508fff Binary files /dev/null and b/iterators/__pycache__/iterator_pipe.cpython-310.pyc differ diff --git a/iterators/__pycache__/timeout_iterator.cpython-310.pyc b/iterators/__pycache__/timeout_iterator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..164f771ea2224175fd7c5f05bace6e412730355c Binary files /dev/null and b/iterators/__pycache__/timeout_iterator.cpython-310.pyc differ diff --git a/iterators/iterator_pipe.py b/iterators/iterator_pipe.py new file mode 100644 index 0000000000000000000000000000000000000000..90883b08ee6c5fbb7a575a7f1176f124b4d66134 --- /dev/null +++ b/iterators/iterator_pipe.py @@ -0,0 +1,93 @@ +import queue +import asyncio + + +class IteratorPipe: + """ + Iterator Pipe creates an iterator that can be fed in data from another block of code or thread of execution + """ + + def __init__(self, sentinel=object()): + self._q = queue.Queue() + self._sentinel = sentinel + self._sentinel_pushed = False + self._closed = False + + def __iter__(self): + return self + + def __next__(self): + if self._closed: + raise StopIteration + + data = self._q.get(block=True) + if data is self._sentinel: + self._closed = True + raise StopIteration + + return data + + def put(self, data) -> bool: + """ + Pushes next item to Iterator and returns True + If iterator has been closed via close(), doesn't push anything and returns False + """ + if self._sentinel_pushed: + return False + + self._q.put(data) + return True + + def close(self): + """ + Close is idempotent. Calling close multiple times is safe + Iterator will raise StopIteration only after all elements pushed before close have been iterated + """ + # make close idempotent + if not self._sentinel_pushed: + self._sentinel_pushed = True + self._q.put(self._sentinel) + + +class AsyncIteratorPipe: + + def __init__(self, sentinel=object()): + self._q = asyncio.Queue() + self._sentinel = sentinel + self._sentinel_pushed = False + self._closed = False + + def __aiter__(self): + return self + + async def __anext__(self): + if self._closed: + raise StopAsyncIteration + + data = await self._q.get() + if data is self._sentinel: + self._closed = True + raise StopAsyncIteration + + return data + + async def put(self, data) -> bool: + """ + Pushes next item to Iterator and returns True + If iterator has been closed via close(), doesn't push anything and returns False + """ + if self._sentinel_pushed: + return False + + await self._q.put(data) + return True + + async def close(self): + """ + Close is idempotent. Calling close multiple times is safe + Iterator will raise StopIteration only after all elements pushed before close have been iterated + """ + # make close idempotent + if not self._sentinel_pushed: + self._sentinel_pushed = True + await self._q.put(self._sentinel) diff --git a/iterators/timeout_iterator.py b/iterators/timeout_iterator.py new file mode 100644 index 0000000000000000000000000000000000000000..d6f760e4b67448538dc95328a58c1eb1b1958471 --- /dev/null +++ b/iterators/timeout_iterator.py @@ -0,0 +1,170 @@ +import queue +import asyncio +import threading +import traceback + + +class TimeoutIterator: + """ + Wrapper class to add timeout feature to synchronous iterators + - timeout: timeout for next(). Default=ZERO_TIMEOUT i.e. no timeout or blocking calls to next. Updated using set_timeout() + - sentinel: the object returned by iterator when timeout happens + - reset_on_next: if set to True, timeout is reset to the value of ZERO_TIMEOUT on each iteration + + TimeoutIterator uses a thread internally. + The thread stops once the iterator exhausts or raises an exception during iteration. + + Any exceptions raised within the wrapped iterator are propagated as it is. + Exception is raised when all elements generated by the actual iterator before exception have been consumed + Timeout can be set dynamically before going for iteration + """ + ZERO_TIMEOUT = 0.0 + + def __init__(self, iterator, timeout=0.0, sentinel=object(), reset_on_next=False, raise_on_exception=True): + self._iterator = iterator + self._timeout = timeout + self._sentinel = sentinel + self._reset_on_next = reset_on_next + self._raise_on_exception = raise_on_exception + + self._interrupt = False + self._done = False + self._buffer = queue.Queue() + self._thread = threading.Thread(target=self.__lookahead) + self._thread.start() + + def get_sentinel(self): + return self._sentinel + + def set_reset_on_next(self, reset_on_next): + self._reset_on_next = reset_on_next + + def set_timeout(self, timeout: float): + """ + Set timeout for next iteration + """ + self._timeout = timeout + + def interrupt(self): + """ + interrupt and stop the underlying thread. + the thread actually dies only after interrupt has been set and + the underlying iterator yields a value after that. + """ + self._interrupt = True + + def __iter__(self): + return self + + def __next__(self): + """ + yield the result from iterator + if timeout > 0: + yield data if available. + otherwise yield sentinal + """ + if self._done: + raise StopIteration + + data = self._sentinel + try: + if self._timeout > self.ZERO_TIMEOUT: + data = self._buffer.get(timeout=self._timeout) + else: + data = self._buffer.get() + except queue.Empty: + pass + finally: + # see if timeout needs to be reset + if self._reset_on_next: + self._timeout = self.ZERO_TIMEOUT + + # propagate any exceptions including StopIteration + if isinstance(data, BaseException): + self._done = True + if isinstance(data, StopIteration): + raise data + ex = ''.join(traceback.format_tb(data.__traceback__)) + print("Generation Failed: %s %s" % (str(data), str(ex)), flush=True) + if self._raise_on_exception: + raise data + else: + return data + + return data + + def __lookahead(self): + try: + while True: + self._buffer.put(next(self._iterator)) + if self._interrupt: + raise StopIteration() + except BaseException as e: + self._buffer.put(e) + + +class AsyncTimeoutIterator: + """ + Async version of TimeoutIterator. See method documentation of TimeoutIterator + """ + ZERO_TIMEOUT = 0.0 + + def __init__(self, iterator, timeout=0.0, sentinel=object(), reset_on_next=False): + self._iterator = iterator + self._timeout = timeout + self._sentinel = sentinel + self._reset_on_next = reset_on_next + + self._interrupt = False + self._done = False + self._buffer = asyncio.Queue() + self._task = asyncio.get_event_loop().create_task(self.__lookahead()) + + def get_sentinel(self): + return self._sentinel + + def set_reset_on_next(self, reset_on_next): + self._reset_on_next = reset_on_next + + def set_timeout(self, timeout: float): + self._timeout = timeout + + def interrupt(self): + self._interrupt = True + + def __aiter__(self): + return self + + async def __anext__(self): + if self._done: + raise StopAsyncIteration + + data = self._sentinel + try: + if self._timeout > self.ZERO_TIMEOUT: + data = await asyncio.wait_for(self._buffer.get(), self._timeout) + else: + data = await self._buffer.get() + except asyncio.TimeoutError: + pass + finally: + # see if timeout needs to be reset + if self._reset_on_next: + self._timeout = self.ZERO_TIMEOUT + + # propagate any exceptions including StopIteration + if isinstance(data, BaseException): + self._done = True + raise data + + return data + + async def __lookahead(self): + try: + while True: + data = await self._iterator.__anext__() + await self._buffer.put(data) + if self._interrupt: + raise StopAsyncIteration() + except BaseException as e: + await self._buffer.put(e) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..c03bea0a5eae8082808aef77aa981b4ac92f5406 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,192 @@ +# for generate (gradio server) and finetune +datasets==2.13.0 +sentencepiece==0.1.99 +gradio==3.41.2 +huggingface_hub==0.16.4 +appdirs==1.4.4 +fire==0.5.0 +docutils==0.20.1 +torch==2.0.1; sys_platform != "darwin" and platform_machine != "arm64" +evaluate==0.4.0 +rouge_score==0.1.2 +sacrebleu==2.3.1 +scikit-learn==1.2.2 +# optional (need to uncomment code in gradio_runner.py for import of better_profanity) +# alt-profanity-check==1.2.2 +# better-profanity==0.7.0 +numpy==1.24.3 +pandas==2.0.2 +matplotlib==3.7.1 +loralib==0.1.1 +bitsandbytes==0.41.1 +accelerate==0.22.0 +peft==0.5.0 +transformers==4.33.1 +tokenizers==0.13.3 +APScheduler==3.10.1 + +# optional for generate +pynvml==11.5.0 +psutil==5.9.5 +boto3==1.26.101 +botocore==1.29.101 + +# optional for finetune +tensorboard==2.13.0 +neptune==1.2.0 + +# for gradio client +gradio_client==0.5.0 +beautifulsoup4==4.12.2 +markdown==3.4.3 + +# data and testing +pytest==7.2.2 +pytest-xdist==3.2.1 +nltk==3.8.1 +textstat==0.7.3 +# pandoc==2.3 +pypandoc==1.11; sys_platform == "darwin" and platform_machine == "arm64" +pypandoc_binary==1.11; platform_machine == "x86_64" +pypandoc_binary==1.11; sys_platform == "win32" +python-magic-bin==0.4.14; sys_platform == "win32" +openpyxl==3.1.2 +lm_dataformat==0.0.20 +bioc==2.0 + +# falcon +einops==0.6.1 +instructorembedding==1.0.1 + +# for gpt4all .env file, but avoid worrying about imports +python-dotenv==1.0.0 + +text-generation==0.6.0 +# for tokenization when don't have HF tokenizer +tiktoken==0.4.0 + +requests>=2.31.0 +urllib3>=1.26.16 +filelock>=3.12.2 +joblib>=1.3.1 +tqdm>=4.65.0 +tabulate>=0.9.0 +packaging>=23.1 +# optional for chat with PDF +langchain==0.0.300 +pypdf==3.14.0 +# avoid textract, requires old six +#textract==1.6.5 +pypdfium2==4.19.0 + +# for HF embeddings +sentence_transformers==2.2.2 + +# optional: for OpenAI endpoint or embeddings (requires key) +openai==0.27.8 +replicate==0.10.0 + +# local vector db +chromadb==0.4.10 + +# chroma migration +chroma-migrate==0.0.7 +duckdb==0.7.1 +https://h2o-release.s3.amazonaws.com/h2ogpt/chromamigdb-0.3.25-py3-none-any.whl +https://h2o-release.s3.amazonaws.com/h2ogpt/hnswmiglib-0.7.0.tgz + +# server vector db +#pymilvus==2.2.8 + +# weak url support, if can't install opencv etc. If comment-in this one, then comment-out unstructured[local-inference]==0.6.6 +# unstructured==0.8.1 + +# strong support for images +# Requires on Ubuntu: sudo apt-get install libmagic-dev poppler-utils tesseract-ocr libtesseract-dev libreoffice +unstructured[local-inference]==0.9.0 +#pdf2image==1.16.3 +#pytesseract==0.3.10 +pillow==9.5.0 +posthog==3.0.1 + +pdfminer.six==20221105 +urllib3 +requests_file + +#pdf2image==1.16.3 +#pytesseract==0.3.10 +tabulate==0.9.0 +# FYI pandoc already part of requirements.txt + +# JSONLoader, but makes some trouble for some users +# TRY: apt-get install autoconf libtool +# unclear what happens on windows/mac for now +jq==1.4.1; platform_machine == "x86_64" + +# to check licenses +# Run: pip-licenses|grep -v 'BSD\|Apache\|MIT' +pip-licenses==4.3.0 + +# weaviate vector db +weaviate-client==3.22.1 +# optional for chat with PDF +langchain==0.0.300 +pypdf==3.14.0 +# avoid textract, requires old six +#textract==1.6.5 +pypdfium2==4.19.0 + +# for HF embeddings +sentence_transformers==2.2.2 + +# optional: for OpenAI endpoint or embeddings (requires key) +openai==0.27.8 +replicate==0.10.0 + +# local vector db +chromadb==0.4.10 + +# chroma migration +chroma-migrate==0.0.7 +duckdb==0.7.1 +https://h2o-release.s3.amazonaws.com/h2ogpt/chromamigdb-0.3.25-py3-none-any.whl +https://h2o-release.s3.amazonaws.com/h2ogpt/hnswmiglib-0.7.0.tgz + +# server vector db +#pymilvus==2.2.8 + +# weak url support, if can't install opencv etc. If comment-in this one, then comment-out unstructured[local-inference]==0.6.6 +# unstructured==0.8.1 + +# strong support for images +# Requires on Ubuntu: sudo apt-get install libmagic-dev poppler-utils tesseract-ocr libtesseract-dev libreoffice +unstructured[local-inference]==0.9.0 +#pdf2image==1.16.3 +#pytesseract==0.3.10 +pillow==9.5.0 +posthog==3.0.1 + +pdfminer.six==20221105 +urllib3 +requests_file + +#pdf2image==1.16.3 +#pytesseract==0.3.10 +tabulate==0.9.0 +# FYI pandoc already part of requirements.txt + +# JSONLoader, but makes some trouble for some users +# TRY: apt-get install autoconf libtool +# unclear what happens on windows/mac for now +jq==1.4.1; platform_machine == "x86_64" + +# to check licenses +# Run: pip-licenses|grep -v 'BSD\|Apache\|MIT' +pip-licenses==4.3.0 + +# weaviate vector db +weaviate-client==3.22.1 +faiss-gpu==1.7.2 +arxiv==1.4.8 +pymupdf==1.23.1 # AGPL license +# extract-msg==0.41.1 # GPL3 diff --git a/src/LICENSE b/src/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..25ae4110625608b553d170b6bb5c439215503afe --- /dev/null +++ b/src/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 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. diff --git a/src/__pycache__/enums.cpython-310.pyc b/src/__pycache__/enums.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffac1acfa223c0daf26f5f716f88f5b8d5a41d79 Binary files /dev/null and b/src/__pycache__/enums.cpython-310.pyc differ diff --git a/src/__pycache__/evaluate_params.cpython-310.pyc b/src/__pycache__/evaluate_params.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3caa47e401cf6d7e1fbb2e4ade5b64321beeaf59 Binary files /dev/null and b/src/__pycache__/evaluate_params.cpython-310.pyc differ diff --git a/src/__pycache__/gen.cpython-310.pyc b/src/__pycache__/gen.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2680d3e393613030cbab18504f2215eb1a504998 Binary files /dev/null and b/src/__pycache__/gen.cpython-310.pyc differ diff --git a/src/__pycache__/gen.cpython-312.pyc b/src/__pycache__/gen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..940901e3dde75d8c305cafe24a476b741c70c63d Binary files /dev/null and b/src/__pycache__/gen.cpython-312.pyc differ diff --git a/src/__pycache__/gpt_langchain.cpython-310.pyc b/src/__pycache__/gpt_langchain.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aeb360b71666ade696f8ead96db5db773e8ad1f0 Binary files /dev/null and b/src/__pycache__/gpt_langchain.cpython-310.pyc differ diff --git a/src/__pycache__/loaders.cpython-310.pyc b/src/__pycache__/loaders.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d788eb21a3e8671261a408d61e7e5099204e5c74 Binary files /dev/null and b/src/__pycache__/loaders.cpython-310.pyc differ diff --git a/src/__pycache__/prompter.cpython-310.pyc b/src/__pycache__/prompter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f44cfbcdaf06c93b58134fe7b041a388508a3b4c Binary files /dev/null and b/src/__pycache__/prompter.cpython-310.pyc differ diff --git a/src/__pycache__/stopping.cpython-310.pyc b/src/__pycache__/stopping.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3098d692eb08ac6da3d90295267c6c91d8c66857 Binary files /dev/null and b/src/__pycache__/stopping.cpython-310.pyc differ diff --git a/src/__pycache__/utils.cpython-310.pyc b/src/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6af49bfe2373d734aa665d69e6a4a1f17a3ecbdb Binary files /dev/null and b/src/__pycache__/utils.cpython-310.pyc differ diff --git a/src/client_test.py b/src/client_test.py new file mode 100644 index 0000000000000000000000000000000000000000..fd9477b56e3244feaab53194565abb570cb7f274 --- /dev/null +++ b/src/client_test.py @@ -0,0 +1,484 @@ +""" +Client test. + +Run server: + +python generate.py --base_model=h2oai/h2ogpt-oig-oasst1-512-6_9b + +NOTE: For private models, add --use-auth_token=True + +NOTE: --use_gpu_id=True (default) must be used for multi-GPU in case see failures with cuda:x cuda:y mismatches. +Currently, this will force model to be on a single GPU. + +Then run this client as: + +python src/client_test.py + + + +For HF spaces: + +HOST="https://h2oai-h2ogpt-chatbot.hf.space" python src/client_test.py + +Result: + +Loaded as API: https://h2oai-h2ogpt-chatbot.hf.space ✔ +{'instruction_nochat': 'Who are you?', 'iinput_nochat': '', 'response': 'I am h2oGPT, a large language model developed by LAION.', 'sources': ''} + + +For demo: + +HOST="https://gpt.h2o.ai" python src/client_test.py + +Result: + +Loaded as API: https://gpt.h2o.ai ✔ +{'instruction_nochat': 'Who are you?', 'iinput_nochat': '', 'response': 'I am h2oGPT, a chatbot created by LAION.', 'sources': ''} + +NOTE: Raw output from API for nochat case is a string of a python dict and will remain so if other entries are added to dict: + +{'response': "I'm h2oGPT, a large language model by H2O.ai, the visionary leader in democratizing AI.", 'sources': ''} + + +""" +import ast +import time +import os +import markdown # pip install markdown +import pytest +from bs4 import BeautifulSoup # pip install beautifulsoup4 + +try: + from enums import DocumentSubset, LangChainAction +except: + from src.enums import DocumentSubset, LangChainAction + +from tests.utils import get_inf_server + +debug = False + +os.environ['HF_HUB_DISABLE_TELEMETRY'] = '1' + + +def get_client(serialize=True): + from gradio_client import Client + + client = Client(get_inf_server(), serialize=serialize) + if debug: + print(client.view_api(all_endpoints=True)) + return client + + +def get_args(prompt, prompt_type=None, chat=False, stream_output=False, + max_new_tokens=50, + top_k_docs=3, + langchain_mode='Disabled', + add_chat_history_to_context=True, + langchain_action=LangChainAction.QUERY.value, + langchain_agents=[], + prompt_dict=None, + version=None, + h2ogpt_key=None, + visible_models=None, + system_prompt='', # default of no system prompt tiggered by empty string + add_search_to_context=False, + chat_conversation=None, + text_context_list=None, + ): + from collections import OrderedDict + kwargs = OrderedDict(instruction=prompt if chat else '', # only for chat=True + iinput='', # only for chat=True + context='', + # streaming output is supported, loops over and outputs each generation in streaming mode + # but leave stream_output=False for simple input/output mode + stream_output=stream_output, + prompt_type=prompt_type, + prompt_dict=prompt_dict, + temperature=0.1, + top_p=0.75, + top_k=40, + num_beams=1, + max_new_tokens=max_new_tokens, + min_new_tokens=0, + early_stopping=False, + max_time=20, + repetition_penalty=1.0, + num_return_sequences=1, + do_sample=True, + chat=chat, + instruction_nochat=prompt if not chat else '', + iinput_nochat='', # only for chat=False + langchain_mode=langchain_mode, + add_chat_history_to_context=add_chat_history_to_context, + langchain_action=langchain_action, + langchain_agents=langchain_agents, + top_k_docs=top_k_docs, + chunk=True, + chunk_size=512, + document_subset=DocumentSubset.Relevant.name, + document_choice=[], + pre_prompt_query=None, + prompt_query=None, + pre_prompt_summary=None, + prompt_summary=None, + system_prompt=system_prompt, + image_loaders=None, + pdf_loaders=None, + url_loaders=None, + jq_schema=None, + visible_models=visible_models, + h2ogpt_key=h2ogpt_key, + add_search_to_context=add_search_to_context, + chat_conversation=chat_conversation, + text_context_list=text_context_list, + docs_ordering_type=None, + min_max_new_tokens=None, + ) + diff = 0 + if version is None: + # latest + version = 1 + if version == 0: + diff = 1 + if version >= 1: + kwargs.update(dict(system_prompt=system_prompt)) + diff = 0 + + from evaluate_params import eval_func_param_names + assert len(set(eval_func_param_names).difference(set(list(kwargs.keys())))) == diff + if chat: + # add chatbot output on end. Assumes serialize=False + kwargs.update(dict(chatbot=[])) + + return kwargs, list(kwargs.values()) + + +@pytest.mark.skip(reason="For manual use against some server, no server launched") +def test_client_basic(prompt_type='human_bot', version=None, visible_models=None, prompt='Who are you?', + h2ogpt_key=None): + return run_client_nochat(prompt=prompt, prompt_type=prompt_type, max_new_tokens=50, version=version, + visible_models=visible_models, h2ogpt_key=h2ogpt_key) + + +""" +time HOST=https://gpt-internal.h2o.ai PYTHONPATH=. pytest -n 20 src/client_test.py::test_client_basic_benchmark +32 seconds to answer 20 questions at once with 70B llama2 on 4x A100 80GB using TGI 0.9.3 +""" + + +@pytest.mark.skip(reason="For manual use against some server, no server launched") +@pytest.mark.parametrize("id", range(20)) +def test_client_basic_benchmark(id, prompt_type='human_bot', version=None): + return run_client_nochat(prompt=""" +/nfs4/llm/h2ogpt/h2ogpt/bin/python /home/arno/pycharm-2022.2.2/plugins/python/helpers/pycharm/_jb_pytest_runner.py --target src/client_test.py::test_client_basic +Testing started at 8:41 AM ... +Launching pytest with arguments src/client_test.py::test_client_basic --no-header --no-summary -q in /nfs4/llm/h2ogpt + +============================= test session starts ============================== +collecting ... +src/client_test.py:None (src/client_test.py) +ImportError while importing test module '/nfs4/llm/h2ogpt/src/client_test.py'. +Hint: make sure your test modules/packages have valid Python names. +Traceback: +h2ogpt/lib/python3.10/site-packages/_pytest/python.py:618: in _importtestmodule + mod = import_path(self.path, mode=importmode, root=self.config.rootpath) +h2ogpt/lib/python3.10/site-packages/_pytest/pathlib.py:533: in import_path + importlib.import_module(module_name) +/usr/lib/python3.10/importlib/__init__.py:126: in import_module + return _bootstrap._gcd_import(name[level:], package, level) +:1050: in _gcd_import + ??? +:1027: in _find_and_load + ??? +:1006: in _find_and_load_unlocked + ??? +:688: in _load_unlocked + ??? +h2ogpt/lib/python3.10/site-packages/_pytest/assertion/rewrite.py:168: in exec_module + exec(co, module.__dict__) +src/client_test.py:51: in + from enums import DocumentSubset, LangChainAction +E ModuleNotFoundError: No module named 'enums' + + +collected 0 items / 1 error + +=============================== 1 error in 0.14s =============================== +ERROR: not found: /nfs4/llm/h2ogpt/src/client_test.py::test_client_basic +(no name '/nfs4/llm/h2ogpt/src/client_test.py::test_client_basic' in any of []) + + +Process finished with exit code 4 + +What happened? +""", prompt_type=prompt_type, max_new_tokens=100, version=version) + + +def run_client_nochat(prompt, prompt_type, max_new_tokens, version=None, h2ogpt_key=None, visible_models=None): + kwargs, args = get_args(prompt, prompt_type, chat=False, max_new_tokens=max_new_tokens, version=version, + visible_models=visible_models, h2ogpt_key=h2ogpt_key) + + api_name = '/submit_nochat' + client = get_client(serialize=True) + res = client.predict( + *tuple(args), + api_name=api_name, + ) + print("Raw client result: %s" % res, flush=True) + res_dict = dict(prompt=kwargs['instruction_nochat'], iinput=kwargs['iinput_nochat'], + response=md_to_text(res)) + print(res_dict) + return res_dict, client + + +@pytest.mark.skip(reason="For manual use against some server, no server launched") +def test_client_basic_api(prompt_type='human_bot', version=None, h2ogpt_key=None): + return run_client_nochat_api(prompt='Who are you?', prompt_type=prompt_type, max_new_tokens=50, version=version, + h2ogpt_key=h2ogpt_key) + + +def run_client_nochat_api(prompt, prompt_type, max_new_tokens, version=None, h2ogpt_key=None): + kwargs, args = get_args(prompt, prompt_type, chat=False, max_new_tokens=max_new_tokens, version=version, + h2ogpt_key=h2ogpt_key) + + api_name = '/submit_nochat_api' # NOTE: like submit_nochat but stable API for string dict passing + client = get_client(serialize=True) + res = client.predict( + str(dict(kwargs)), + api_name=api_name, + ) + print("Raw client result: %s" % res, flush=True) + res_dict = dict(prompt=kwargs['instruction_nochat'], iinput=kwargs['iinput_nochat'], + response=md_to_text(ast.literal_eval(res)['response']), + sources=ast.literal_eval(res)['sources']) + print(res_dict) + return res_dict, client + + +@pytest.mark.skip(reason="For manual use against some server, no server launched") +def test_client_basic_api_lean(prompt_type='human_bot', version=None, h2ogpt_key=None): + return run_client_nochat_api_lean(prompt='Who are you?', prompt_type=prompt_type, max_new_tokens=50, + version=version, h2ogpt_key=h2ogpt_key) + + +def run_client_nochat_api_lean(prompt, prompt_type, max_new_tokens, version=None, h2ogpt_key=None): + kwargs = dict(instruction_nochat=prompt, h2ogpt_key=h2ogpt_key) + + api_name = '/submit_nochat_api' # NOTE: like submit_nochat but stable API for string dict passing + client = get_client(serialize=True) + res = client.predict( + str(dict(kwargs)), + api_name=api_name, + ) + print("Raw client result: %s" % res, flush=True) + res_dict = dict(prompt=kwargs['instruction_nochat'], + response=md_to_text(ast.literal_eval(res)['response']), + sources=ast.literal_eval(res)['sources'], + h2ogpt_key=h2ogpt_key) + print(res_dict) + return res_dict, client + + +@pytest.mark.skip(reason="For manual use against some server, no server launched") +def test_client_basic_api_lean_morestuff(prompt_type='human_bot', version=None, h2ogpt_key=None): + return run_client_nochat_api_lean_morestuff(prompt='Who are you?', prompt_type=prompt_type, max_new_tokens=50, + version=version, h2ogpt_key=h2ogpt_key) + + +def run_client_nochat_api_lean_morestuff(prompt, prompt_type='human_bot', max_new_tokens=512, version=None, + h2ogpt_key=None): + kwargs = dict( + instruction='', + iinput='', + context='', + stream_output=False, + prompt_type=prompt_type, + temperature=0.1, + top_p=0.75, + top_k=40, + num_beams=1, + max_new_tokens=1024, + min_new_tokens=0, + early_stopping=False, + max_time=20, + repetition_penalty=1.0, + num_return_sequences=1, + do_sample=True, + chat=False, + instruction_nochat=prompt, + iinput_nochat='', + langchain_mode='Disabled', + add_chat_history_to_context=True, + langchain_action=LangChainAction.QUERY.value, + langchain_agents=[], + top_k_docs=4, + document_subset=DocumentSubset.Relevant.name, + document_choice=[], + h2ogpt_key=h2ogpt_key, + add_search_to_context=False, + ) + + api_name = '/submit_nochat_api' # NOTE: like submit_nochat but stable API for string dict passing + client = get_client(serialize=True) + res = client.predict( + str(dict(kwargs)), + api_name=api_name, + ) + print("Raw client result: %s" % res, flush=True) + res_dict = dict(prompt=kwargs['instruction_nochat'], + response=md_to_text(ast.literal_eval(res)['response']), + sources=ast.literal_eval(res)['sources'], + h2ogpt_key=h2ogpt_key) + print(res_dict) + return res_dict, client + + +@pytest.mark.skip(reason="For manual use against some server, no server launched") +def test_client_chat(prompt_type='human_bot', version=None, h2ogpt_key=None): + return run_client_chat(prompt='Who are you?', prompt_type=prompt_type, stream_output=False, max_new_tokens=50, + langchain_mode='Disabled', + langchain_action=LangChainAction.QUERY.value, + langchain_agents=[], + version=version, + h2ogpt_key=h2ogpt_key) + + +@pytest.mark.skip(reason="For manual use against some server, no server launched") +def test_client_chat_stream(prompt_type='human_bot', version=None, h2ogpt_key=None): + return run_client_chat(prompt="Tell a very long kid's story about birds.", prompt_type=prompt_type, + stream_output=True, max_new_tokens=512, + langchain_mode='Disabled', + langchain_action=LangChainAction.QUERY.value, + langchain_agents=[], + version=version, + h2ogpt_key=h2ogpt_key) + + +def run_client_chat(prompt='', + stream_output=None, + max_new_tokens=128, + langchain_mode='Disabled', + langchain_action=LangChainAction.QUERY.value, + langchain_agents=[], + prompt_type=None, prompt_dict=None, + version=None, + h2ogpt_key=None): + client = get_client(serialize=False) + + kwargs, args = get_args(prompt, prompt_type, chat=True, stream_output=stream_output, + max_new_tokens=max_new_tokens, + langchain_mode=langchain_mode, + langchain_action=langchain_action, + langchain_agents=langchain_agents, + prompt_dict=prompt_dict, + version=version, + h2ogpt_key=h2ogpt_key) + return run_client(client, prompt, args, kwargs) + + +def run_client(client, prompt, args, kwargs, do_md_to_text=True, verbose=False): + assert kwargs['chat'], "Chat mode only" + res = client.predict(*tuple(args), api_name='/instruction') + args[-1] += [res[-1]] + + res_dict = kwargs + res_dict['prompt'] = prompt + if not kwargs['stream_output']: + res = client.predict(*tuple(args), api_name='/instruction_bot') + res_dict['response'] = res[0][-1][1] + print(md_to_text(res_dict['response'], do_md_to_text=do_md_to_text)) + return res_dict, client + else: + job = client.submit(*tuple(args), api_name='/instruction_bot') + res1 = '' + while not job.done(): + outputs_list = job.communicator.job.outputs + if outputs_list: + res = job.communicator.job.outputs[-1] + res1 = res[0][-1][-1] + res1 = md_to_text(res1, do_md_to_text=do_md_to_text) + print(res1) + time.sleep(0.1) + full_outputs = job.outputs() + if verbose: + print('job.outputs: %s' % str(full_outputs)) + # ensure get ending to avoid race + # -1 means last response if streaming + # 0 means get text_output, ignore exception_text + # 0 means get list within text_output that looks like [[prompt], [answer]] + # 1 means get bot answer, so will have last bot answer + res_dict['response'] = md_to_text(full_outputs[-1][0][0][1], do_md_to_text=do_md_to_text) + return res_dict, client + + +@pytest.mark.skip(reason="For manual use against some server, no server launched") +def test_client_nochat_stream(prompt_type='human_bot', version=None, h2ogpt_key=None): + return run_client_nochat_gen(prompt="Tell a very long kid's story about birds.", prompt_type=prompt_type, + stream_output=True, max_new_tokens=512, + langchain_mode='Disabled', + langchain_action=LangChainAction.QUERY.value, + langchain_agents=[], + version=version, + h2ogpt_key=h2ogpt_key) + + +def run_client_nochat_gen(prompt, prompt_type, stream_output, max_new_tokens, + langchain_mode, langchain_action, langchain_agents, version=None, + h2ogpt_key=None): + client = get_client(serialize=False) + + kwargs, args = get_args(prompt, prompt_type, chat=False, stream_output=stream_output, + max_new_tokens=max_new_tokens, langchain_mode=langchain_mode, + langchain_action=langchain_action, langchain_agents=langchain_agents, + version=version, h2ogpt_key=h2ogpt_key) + return run_client_gen(client, prompt, args, kwargs) + + +def run_client_gen(client, prompt, args, kwargs, do_md_to_text=True, verbose=False): + res_dict = kwargs + res_dict['prompt'] = prompt + if not kwargs['stream_output']: + res = client.predict(str(dict(kwargs)), api_name='/submit_nochat_api') + res_dict.update(ast.literal_eval(res)) + print(md_to_text(res_dict['response'], do_md_to_text=do_md_to_text)) + return res_dict, client + else: + job = client.submit(str(dict(kwargs)), api_name='/submit_nochat_api') + while not job.done(): + outputs_list = job.communicator.job.outputs + if outputs_list: + res = job.communicator.job.outputs[-1] + res_dict = ast.literal_eval(res) + print('Stream: %s' % res_dict['response']) + time.sleep(0.1) + res_list = job.outputs() + assert len(res_list) > 0, "No response, check server" + res = res_list[-1] + res_dict = ast.literal_eval(res) + print('Final: %s' % res_dict['response']) + return res_dict, client + + +def md_to_text(md, do_md_to_text=True): + if not do_md_to_text: + return md + assert md is not None, "Markdown is None" + html = markdown.markdown(md) + soup = BeautifulSoup(html, features='html.parser') + return soup.get_text() + + +def run_client_many(prompt_type='human_bot', version=None, h2ogpt_key=None): + kwargs = dict(prompt_type=prompt_type, version=version, h2ogpt_key=h2ogpt_key) + ret1, _ = test_client_chat(**kwargs) + ret2, _ = test_client_chat_stream(**kwargs) + ret3, _ = test_client_nochat_stream(**kwargs) + ret4, _ = test_client_basic(**kwargs) + ret5, _ = test_client_basic_api(**kwargs) + ret6, _ = test_client_basic_api_lean(**kwargs) + ret7, _ = test_client_basic_api_lean_morestuff(**kwargs) + return ret1, ret2, ret3, ret4, ret5, ret6, ret7 + + +if __name__ == '__main__': + run_client_many() diff --git a/src/create_data.py b/src/create_data.py new file mode 100644 index 0000000000000000000000000000000000000000..52e6257319bdee820989df334e14122cf58b68cc --- /dev/null +++ b/src/create_data.py @@ -0,0 +1,1847 @@ +""" +Dataset creation tools. + +Keep to-level imports clean of non-trivial imports for specific tools, +because this file is imported for various purposes +""" + +import ast +import concurrent.futures +import contextlib +import hashlib +import json +import os +import shutil +import signal +import sys +import traceback +from concurrent.futures import ProcessPoolExecutor + +import psutil +import pytest +import pandas as pd +import numpy as np +from tqdm import tqdm + +from utils import flatten_list, remove + + +def parse_rst_file(filepath): + with open(filepath, 'r') as f: + input_data = f.read() + settings_overrides = {'initial_header_level': 2} + from docutils import core + document = core.publish_doctree( + source=input_data, + source_path=filepath, + settings_overrides=settings_overrides, + ) + qa_pairs = [] + current_section = None + current_question = "" + current_answer = "" + for node in document.traverse(): + if node.__class__.__name__ == 'section': + current_section = "" + elif current_section is not None: + if node.__class__.__name__ == 'Text': + if node.astext()[-1] == "?": + if current_question: + qa_pairs.append((current_question, current_answer)) + current_question = node.astext() + current_answer = "" + else: + current_answer += node.astext() + if current_answer: + qa_pairs.append((current_question, current_answer)) + return {k: v for k, v in qa_pairs} + + +def test_scrape_dai_docs(): + home = os.path.expanduser('~') + file = os.path.join(home, 'h2oai/docs/faq.rst') + qa_pairs = parse_rst_file(file) + prompt_type = 'human_bot' + from prompter import prompt_types + assert prompt_type in prompt_types + save_thing = [{"instruction": k, "output": v, 'prompt_type': prompt_type} for k, v in qa_pairs.items()] + output_file = "dai_faq.json" + with open(output_file, "wt") as f: + f.write(json.dumps(save_thing, indent=2)) + + +def test_scrape_dai_docs_all(): + """ + pytest create_data.py::test_scrape_dai_docs_all + """ + import glob + import nltk + nltk.download('punkt') + dd = {} + np.random.seed(1234) + home = os.path.expanduser('~') + files = list(glob.glob(os.path.join(home, "h2oai/docs/**/*rst"))) + np.random.shuffle(files) + val_count = int(0.05 * len(files)) + train_files = files[val_count:] + valid_files = files[:val_count] + things = [ + ("dai_docs.train.json", train_files), + ("dai_docs.valid.json", valid_files) + ] + for LEN in [100, 200, 500]: + for output_file, ff in things: + if output_file not in dd: + dd[output_file] = [] + for f in ff: + with open(f) as input: + blob = input.read() + blob = blob.replace("~~", "") + blob = blob.replace("==", "") + blob = blob.replace("''", "") + blob = blob.replace("--", "") + blob = blob.replace("**", "") + dd[output_file].extend(get_sentences(blob, length=LEN)) + for output_file, _ in things: + save_thing = [{"output": k.strip(), 'prompt_type': 'plain'} for k in dd[output_file]] + with open(output_file, "wt") as f: + f.write(json.dumps(save_thing, indent=2)) + + +def get_sentences(blob, length): + """ + break-up input text into sentences and then output list of sentences of about length in size + :param blob: + :param length: + :return: + """ + import nltk + nltk.download('punkt') + from nltk.tokenize import sent_tokenize + sentences = sent_tokenize(blob) + my_sentences = [] + my_string = "" + for sentence in sentences: + if len(my_string) + len(sentence) <= length: + if my_string: + my_string += " " + sentence + else: + my_string = sentence + else: + my_sentences.append(my_string) + my_string = "" + return my_sentences or [my_string] + + +def setup_dai_docs(path=None, dst="working_dir_docs", from_hf=False): + """ + Only supported if have access to source code or HF token for HF spaces and from_hf=True + :param path: + :param dst: + :param from_hf: + :return: + """ + + home = os.path.expanduser('~') + + if from_hf: + # assumes + from huggingface_hub import hf_hub_download + # True for case when locally already logged in with correct token, so don't have to set key + token = os.getenv('HUGGING_FACE_HUB_TOKEN', True) + path_to_zip_file = hf_hub_download('h2oai/dai_docs', 'dai_docs.zip', token=token, repo_type='dataset') + path = 'h2oai' + import zipfile + with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref: + zip_ref.extractall(path) + path = os.path.join(path, 'docs/**/*') + + if path is None: + if os.path.isdir(os.path.join(home, 'h2oai')): + path = os.path.join(home, "h2oai/docs/**/*") + else: + assert os.path.isdir(os.path.join(home, 'h2oai.superclean')), '%s does not exist' % path + path = os.path.join(home, "h2oai.superclean/docs/**/*") + import glob + files = list(glob.glob(path, recursive=True)) + + # pandoc can't find include files + + remove(dst) + os.makedirs(dst) + + # copy full tree, for absolute paths in rst + for fil in files: + if os.path.isfile(fil): + shutil.copy(fil, dst) + + # hack for relative path + scorers_dir = os.path.join(dst, 'scorers') + makedirs(scorers_dir) + for fil in glob.glob(os.path.join(dst, '*.frag')): + shutil.copy(fil, scorers_dir) + + return dst + + +def rst_to_outputs(files, min_len=30, max_len=2048 // 2 - 30): + # account for sequence length (context window) including prompt and input and output + + # os.system('pandoc -f rst -t plain ./expert_settings/nlp_settings.rst') + import pypandoc + basedir = os.path.abspath(os.getcwd()) + + outputs = [] + for fil in files: + os.chdir(basedir) + os.chdir(os.path.dirname(fil)) + fil = os.path.basename(fil) + print("Processing %s" % fil, flush=True) + # out_format can be one of: asciidoc, asciidoctor, beamer, biblatex, bibtex, commonmark, commonmark_x, + # context, csljson, docbook, docbook4, docbook5, docx, dokuwiki, + # dzslides, epub, epub2, epub3, fb2, gfm, haddock, html, html4, html5, icml, + # ipynb, jats, jats_archiving, jats_articleauthoring, jats_publishing, jira, + # json, latex, man, + # markdown, markdown_github, markdown_mmd, markdown_phpextra, markdown_strict, + # mediawiki, ms, muse, native, odt, opendocument, opml, org, pdf, plain, pptx, + # revealjs, rst, rtf, s5, slideous, slidy, tei, texinfo, textile, xwiki, zimwiki + out_format = 'plain' + # avoid extra new lines injected into text + extra_args = ['--wrap=preserve', '--resource path="%s" % dst'] + + plain_list = [] + try: + # valid for expert settings + input_rst = pypandoc.convert_file(fil, 'rst') + input_list = input_rst.split('\n``') + for input_subrst in input_list: + input_plain = pypandoc.convert_text(input_subrst, format='rst', to='plain') + plain_list.append([input_plain, fil]) + except Exception as e: + print("file exception: %s %s" % (fil, str(e)), flush=True) + + if not plain_list: + # if failed to process as pieces of rst, then + output = pypandoc.convert_file(fil, out_format, extra_args=extra_args, format='rst') + outputs1 = get_sentences(output, length=max_len) + for oi, output in enumerate(outputs1): + output = output.replace('\n\n', '\n') + plain_list.append([output, fil]) + outputs.extend(plain_list) + + # report: + # [print(len(x)) for x in outputs] + + # deal with blocks longer than context size (sequence length) of 2048 + new_outputs = [] + num_truncated = 0 + num_orig = len(outputs) + for output, fil in outputs: + if len(output) < max_len: + new_outputs.append([output, fil]) + continue + outputs1 = get_sentences(output, length=max_len) + for oi, output1 in enumerate(outputs1): + output1 = output1.replace('\n\n', '\n') + new_outputs.append([output1, fil]) + num_truncated += 1 + print('num_orig: %s num_truncated: %s' % (num_orig, num_truncated), flush=True) + + new_outputs = [[k.strip(), fil] for k, fil in new_outputs if len(k.strip()) > min_len] + + return new_outputs + + +def test_scrape_dai_docs_all_pandoc(): + """ + pytest -s -v create_data.py::test_scrape_dai_docs_all_pandoc + :return: + """ + + dst = setup_dai_docs() + + import glob + files = list(glob.glob(os.path.join(dst, '*rst'), recursive=True)) + + basedir = os.path.abspath(os.getcwd()) + new_outputs = rst_to_outputs(files) + os.chdir(basedir) + + remove(dst) + save_thing = [{"output": k.strip(), 'prompt_type': 'plain'} for k in new_outputs] + output_file = "dai_docs.train_cleaned.json" + with open(output_file, "wt") as f: + f.write(json.dumps(save_thing, indent=2)) + + +def test_config_to_json(): + """ + Needs to run from Driverless AI source directory. + E.g. (base) jon@gpu:~/h2oai$ pytest -s -v /data/jon/h2ogpt/create_data.py::test_config_to_json ; cp config.json /data/jon/h2ogpt/ + :return: + """ + try: + # Arrange + import json + from h2oaicore.systemutils import config + toml_list = [] + for k, v in config.get_meta_dict().items(): + title = (v.title + ": ") if v.title else '' + comment = v.comment or '' + if not (title or comment): + continue + toml_list.extend( + [ + { + 'prompt_type': 'plain', + 'instruction': f": What does {k} do?\n: {k.replace('_', ' ')} config.toml: {comment or title}\n:".replace( + "\n", ""), + }, + { + 'prompt_type': 'plain', + 'instruction': f": Explain {k}.\n: {k.replace('_', ' ')} config.toml: {comment or title}\n:".replace( + "\n", ""), + }, + { + 'prompt_type': 'plain', + 'instruction': f": How can I do this: {title}.\n: Set the {k.replace('_', ' ')} config.toml\n:".replace( + "\n", ""), + } if title and comment else None, + { + 'prompt_type': 'human_bot', + 'instruction': f'Explain the following expert setting for Driverless AI', + 'input': f"{k}", + 'output': f"{k.replace('_', ' ')} config.toml: {comment or title}".replace("\n", ""), + }, + { + 'prompt_type': 'human_bot', + 'instruction': f'Explain the following expert setting for Driverless AI', + 'input': f"{k}", + 'output': f"{k.replace('_', ' ')} config.toml: {title}{comment}".replace("\n", ""), + }, + { + 'prompt_type': 'human_bot', + 'instruction': f'Explain the following expert setting for Driverless AI', + 'input': f"{k.replace('_', ' ')}", + 'output': f"{k.replace('_', ' ')} config.toml: {title}{comment}".replace("\n", ""), + }, + { + 'prompt_type': 'human_bot', + 'instruction': f'Explain the following expert setting for Driverless AI', + 'input': f"{title}", + 'output': f"{k.replace('_', ' ')} config.toml: {title}{comment}".replace("\n", ""), + }, + { + 'prompt_type': 'human_bot', + 'instruction': f'Provide a short explanation of the expert setting {k}', + 'output': f"{k.replace('_', ' ')} config.toml: {comment or title}".replace("\n", ""), + }, + { + 'prompt_type': 'human_bot', + 'instruction': f'Provide a detailed explanation of the expert setting {k}', + 'output': f"{k.replace('_', ' ')} config.toml: {title}{comment}".replace("\n", ""), + }, + ] + ) + toml_list = [x for x in toml_list if x] + with open("config.json", "wt") as f: + f.write(json.dumps(toml_list, indent=2)) + except Exception as e: + print("Exception: %s" % str(e), flush=True) + + +def copy_tree(src, dst, follow_symlink=False): + makedirs(dst, exist_ok=True) + for (path, dirs, files) in os.walk(src, followlinks=follow_symlink): + new_path = path.replace(src, dst) + makedirs(new_path, exist_ok=True) + for file in files: + filename = os.path.join(path, file) + new_filename = os.path.join(new_path, file) + # print("%s -> %s" % (filename, new_filename)) + try: + atomic_copy(filename, new_filename) + except FileNotFoundError: + pass + + +def atomic_move(src, dst): + try: + shutil.move(src, dst) + except (shutil.Error, FileExistsError): + pass + remove(src) + + +def atomic_copy(src=None, dst=None, with_permissions=True): + if os.path.isfile(dst): + return + import uuid + my_uuid = uuid.uuid4() + dst_tmp = dst + str(my_uuid) + makedirs(os.path.dirname(dst), exist_ok=True) + if with_permissions: + shutil.copy(src, dst_tmp) + else: + shutil.copyfile(src, dst_tmp) + atomic_move(dst_tmp, dst) + remove(dst_tmp) + + +def makedirs(path, exist_ok=True): + """ + Avoid some inefficiency in os.makedirs() + :param path: + :param exist_ok: + :return: + """ + if os.path.isdir(path) and os.path.exists(path): + assert exist_ok, "Path already exists" + return path + os.makedirs(path, exist_ok=exist_ok) + + +## Download from https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered/resolve/main/ShareGPT_unfiltered_cleaned_split.json +## Turn into simple instruct prompt type. No context/previous conversations. +def test_prep_instruct_vicuna(): + from datasets import load_dataset + filename = 'ShareGPT_unfiltered_cleaned_split.json' + if not os.path.exists(filename): + os.system( + 'wget https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered/resolve/main/%s' % filename) + data = load_dataset("json", data_files={"train": filename})["train"] + training_rows = [] + for i in range(data.num_rows): + conversations = data[i]['conversations'] + assert isinstance(conversations, list), conversations + convo = "" + for j, conv in enumerate(conversations): + # Get ready for generate.py prompt_type=human_bot + # But train with prompt_type=plain + if conv['from'] == 'human': + FROM = ': ' + elif conv['from'] == 'gpt': + FROM = ': ' + convo += f"{FROM}" + conv['value'] + "\n" + if convo: + training_rows.append(dict(input=convo)) + with open(filename + ".generate_human_bot.train_plain.json", "wt") as f: + f.write(json.dumps(training_rows, indent=2)) + + +POSTFIX = ".generate_human_bot.train_plain.json" + +# https://bair.berkeley.edu/blog/2023/04/03/koala/ +OIG_DATASETS = [ + "unified_chip2.jsonl", + "unified_grade_school_math_instructions.jsonl", + "unified_poetry_2_song.jsonl", + "unified_plot_screenplay_books_dialog.jsonl", +] + +# hub issue: https://huggingface.co/datasets/laion/OIG/discussions/4 +ALL_OIG_DATASETS = ['unified_abstract_infill.jsonl', + 'unified_basic.jsonl', + 'unified_canadian_parliament.jsonl', + 'unified_chip2.jsonl', + 'unified_conv_finqa.jsonl', + 'unified_cuad.jsonl', + 'unified_essays.jsonl', + 'unified_flan.jsonl.gz', + 'unified_grade_school_math_instructions.jsonl', + 'unified_hc3_human.jsonl', + 'unified_image_prompts_instructions.jsonl', + 'unified_joke_explanations.jsonl', + 'unified_mathqa_flanv2_kojma_cot.jsonl', + 'unified_merged_code_xp3.jsonl', + 'unified_multi_news.jsonl', + 'unified_multi_sum.jsonl', + 'unified_ni.jsonl.gz', + 'unified_nq.jsonl', + 'unified_openai_summarize_tldr.jsonl', + 'unified_oscar_en_sample_dialog.jsonl', + 'unified_p3.jsonl.gz', + 'unified_plot_screenplay_books_dialog.jsonl', + 'unified_poetry_2_song.jsonl', + 'unified_poetry_instructions.jsonl', + 'unified_rallio_safety_and_prosocial.jsonl', + 'unified_rallio_soda_upgraded_2048.jsonl', + 'unified_soda_dialog.jsonl', + 'unified_sqlv1.jsonl', + 'unified_sqlv2.jsonl', + 'unified_squad_v2.jsonl', + 'unified_squad_v2_more_neg.jsonl', + 'unified_ul2_plus_oscar_en_sample_dialog.jsonl', + 'unified_unifiedskg_instructions.jsonl', + 'unified_unnatural_instructions.jsonl', + 'unified_xp3_sample.jsonl'] + +useful_oig_files = ['unified_rallio_safety_and_prosocial.jsonl.parquet', + 'unified_chip2.jsonl.parquet', + 'unified_cuad.jsonl.parquet', + 'unified_essays.jsonl.parquet', + 'unified_flan.jsonl.gz.parquet', + 'unified_grade_school_math_instructions.jsonl.parquet', + 'unified_hc3_human.jsonl.parquet', + 'unified_mathqa_flanv2_kojma_cot.jsonl.parquet', + 'unified_merged_code_xp3.jsonl.parquet', + 'unified_multi_news.jsonl.parquet', + # 'unified_multi_sum.jsonl.parquet' + 'unified_ni.jsonl.gz.parquet', + 'unified_openai_summarize_tldr.jsonl.parquet', + # 'unified_oscar_en_sample_dialog.jsonl.parquet', # create text containing these N words, not specific + 'unified_plot_screenplay_books_dialog.jsonl.parquet', + 'unified_soda_dialog.jsonl.parquet', + 'unified_unnatural_instructions.jsonl.parquet', + ] + + +@pytest.mark.parametrize("filename", OIG_DATASETS) +def test_get_small_sample_oig_data(filename): + if not os.path.exists(filename): + os.system('wget https://huggingface.co/datasets/laion/OIG/resolve/main/%s' % filename) + import json + rows = [] + with open(filename, "r") as f: + for line in f.readlines(): + row = json.loads(line) + rows.append(dict(input=row["text"])) + with open(filename + POSTFIX, "w") as f: + f.write(json.dumps(rows, indent=2)) + + +@pytest.mark.parametrize("filename", ALL_OIG_DATASETS) +def test_download_useful_data_as_parquet(filename): + dest_file = filename + '.parquet' + if dest_file not in useful_oig_files: + pytest.skip('file declared not useful') + if not os.path.exists(filename): + os.system('wget https://huggingface.co/datasets/laion/OIG/resolve/main/%s' % filename) + if not os.path.exists(dest_file): + df = pd.read_json(path_or_buf=filename, lines=True) + df.to_parquet(dest_file, index=False) + + +def test_merge_shuffle_small_sample_oig_data(): + np.random.seed(1234) + rows = [] + for filename in OIG_DATASETS: + with open(filename + POSTFIX, "r") as f: + rows.extend(json.loads(f.read())) + np.random.shuffle(rows) + with open("merged_shuffled_OIG_%s.json" % hashlib.sha256(str(OIG_DATASETS).encode()).hexdigest()[:10], "w") as f: + f.write(json.dumps(rows, indent=2)) + + +def test_join_jsons(): + files = ['config.json'] * 1 + \ + ['dai_docs.train_cleaned.json'] * 2 + \ + ['dai_faq.json'] * 3 + print(files) + lst = [] + [lst.extend(json.load(open(fil, 'rt'))) for fil in files] + print(len(lst)) + json.dump(lst, open("merged.json", "wt"), indent=2) + + +@pytest.mark.parametrize("filename", ['Anthropic/hh-rlhf']) +def test_make_rlhf_good_data(filename): + from datasets import load_dataset + rows = load_dataset(filename)["train"]["chosen"] + new_rows = [] + for row in rows: + if row[:2] == "\n\n": + row = row[2:] + row = row.replace("Human: ", ": ") + row = row.replace("Assistant: ", ": ") + new_rows.append(dict(input=row)) + with open(filename.replace("/", "_") + POSTFIX, "w") as f: + f.write(json.dumps(new_rows, indent=2)) + + +def test_show_prompts(): + files = ['config.json'] * 1 + \ + ['dai_docs.train_cleaned.json'] * 1 + \ + ['dai_faq.json'] * 1 + file_points = [json.load(open(fil, 'rt')) for fil in files] + from prompter import generate_prompt + for data_points in file_points: + for data_point in data_points: + print(generate_prompt(data_point, 'plain', '', False, False, False)[0]) + + +def test_get_open_datasets(): + # HF changed things so don't get raw list of all datasets, so not have to filter, but can't do negative filter + open_tags = ['license:Apache License 2.0', + 'license:mit', + 'license:apache', + 'license:apache2', + 'license:apache-2.0', + 'license:bsd', + 'license:bsd-2-clause', + 'license:bsd-3-clause', + 'license:bsd-3-clause-clear', + 'license:lgpl-2.1', + 'license:lgpl-3.0', + 'license:lgpl-lr', + 'license:lgpl', + 'license:openrail++', + 'license:openrail', + 'license:bigscience-bloom-rail-1.0', + # 'license:agpl-3.0', + 'license:other', + 'license:unknown', + # 'license:mpl-2.0', # ok, but would have to include original copyright, license, source, copies in distribution + # Attribution required: + 'license:odc-by', + 'license:cc-by-4.0', + 'license:cc-by-3.0', + 'license:cc-by-2.0', + 'license:cc-by-2.5', + # 'license:cc-by-sa-4.0', # would require same license + 'license:odbl', + 'license:pddl', + 'license:ms-pl', + 'license:zlib', + ] + # bad license: cc-by-nc-4.0 + + from huggingface_hub import list_datasets + datasets = flatten_list([[x for x in list_datasets(filter=y)] for y in open_tags]) + datasets += [x for x in list_datasets(author='openai')] + # check all: + all_license_tags = set(flatten_list([[y for y in x.tags if 'license' in y] for x in datasets])) + print(len(all_license_tags)) + open_datasets = [x for x in datasets if any([y in x.tags for y in open_tags]) or 'license:' not in str(x.tags)] + print('open_datasets', len(open_datasets)) + all_task_tags = set(flatten_list([[y for y in x.tags if 'task' in y] for x in open_datasets])) + print('all_task_tags', len(all_task_tags)) + excluded_tags = ['image', 'hate', 'tabular', 'table-', 'classification', 'retrieval', + 'translation', 'identification', 'object', 'mask', 'to-text', + 'face-detection', 'audio', 'voice', 'reinforcement', 'depth-est', + 'forecasting', 'parsing', 'visual', 'speech', 'multiple-choice', + 'slot-filling', 'irds/argsme', '-scoring', 'other', 'graph-ml', + 'feature-extraction', 'keyword-spotting', + 'coreference-resolution', 'segmentation', + 'word-sense-disambiguation', + 'lemmatization'] + task_tags = [x.replace('task_categories:', '').replace('task_ids:', '') + for x in all_task_tags if not any([y in x for y in + excluded_tags])] + print('task_tags', len(task_tags)) + # str(x.tags) to catch any pattern match to anything in list + open_tasked_datasets = [x for x in open_datasets if + any([y in str([x for x in x.tags if 'task' in x]) for y in task_tags]) and + not any([y in str([x for x in x.tags if 'task' in x]) for y in excluded_tags]) or + 'task_categories' not in str(x.tags) and 'task_ids' not in str(x.tags)] + open_tasked_datasets = [x for x in open_tasked_datasets if not x.disabled] + open_tasked_datasets = [x for x in open_tasked_datasets if not x.gated] + open_tasked_datasets = [x for x in open_tasked_datasets if not x.private] + print('open_tasked_datasets', len(open_tasked_datasets)) + sizes = list(set(flatten_list([[(y, x.id) for y in x.tags if 'size' in y] for x in open_tasked_datasets]))) + languages = list(set(flatten_list([[(y, x.id) for y in x.tags if 'language:' in y] for x in open_tasked_datasets]))) + open_english_tasked_datasets = [x for x in open_tasked_datasets if + 'language:' not in str(x.tags) or + 'language:en' in str(x.tags)] + small_open_english_tasked_datasets = [x for x in open_english_tasked_datasets if + 'n<1K' in str(x.tags) or + '1K summarization? + # load_dataset(open_tasked_datasets[0].id).data['train'].to_pandas() + ids = [x.id for x in small_open_english_tasked_datasets] + + # sanity checks + # https://bair.berkeley.edu/blog/2023/04/03/koala/ + assert 'alespalla/chatbot_instruction_prompts' in ids + assert 'laion/OIG' in ids + assert 'openai/webgpt_comparisons' in ids + assert 'openai/summarize_from_feedback' in ids + assert 'Anthropic/hh-rlhf' in ids + + # useful but not allowed for commercial purposes: + # https://huggingface.co/datasets/squad + + print('open_english_tasked_datasets: ', ids, flush=True) + + exclude_ids = ['allenai/nllb', # translation only + 'hf-internal-testing/fixtures_image_utils', # testing + 'allenai/c4', # search-url + 'agemagician/uniref50', # unknown + 'huggingface-course/documentation-images', # images + 'smilegate-ai/kor_unsmile', # korean + 'MohamedRashad/ChatGPT-prompts', # ChatGPT/LearnGPT/https://www.emergentmind.com/ + 'humarin/chatgpt-paraphrases', # Paraphrase using ChatGPT + 'Jeska/vaccinchat', # not useful + 'alespalla/chatbot_instruction_prompts', # mixes alpaca + 'allenai/prosocial-dialog', + # already exlucded, but wrongly in other datasets that say more permissive license + 'AlekseyKorshuk/persona-chat', # low quality + 'bavard/personachat_truecased', # low quality + 'adamlin/daily_dialog', # medium quality conversations + 'adamlin/FewShotWoz', # low quality + 'benjaminbeilharz/better_daily_dialog', # low quality + 'benjaminbeilharz/daily_dialog_w_turn_templates', # low + 'benjaminbeilharz/empathetic_dialogues_for_lm', # low + 'GEM-submissions/GEM__bart_base_schema_guided_dialog__1645547915', # NA + 'ia-bentebib/conv_ai_2_fr', # low fr + 'ia-bentebib/daily_dialog_fr', # low fr + 'ia-bentebib/dialog_re_fr', # low fr + 'ia-bentebib/empathetic_dialogues_fr', # low fr + 'roskoN/dailydialog', # low + 'VadorMazer/skyrimdialogstest', # low + 'bigbio/med_qa', # med specific Q/A + 'biu-nlp/qa_srl2018', # low quality Q/A + 'biu-nlp/qa_discourse', # low quality Q/A + 'iarfmoose/qa_evaluator', # low quality Q/A + 'jeopardy', # low quality Q/A -- no reasoning + 'narrativeqa', # low quality Q/A + 'nomic-ai/gpt4all_prompt_generations', # bad license + 'nomic-ai/gpt4all_prompt_generations_with_p3', # bad license + 'HuggingFaceH4/alpaca', # bad license + 'tatsu-lab/alpaca', # ToS breaking + 'yahma/alpaca-cleaned', # ToS breaking + 'Hello-SimpleAI/HC3', # bad license + 'glue', # no reasoning QA + 'sahil2801/CodeAlpaca-20k', # bad license + 'Short-Answer-Feedback/saf_communication_networks_english', # long Q, medium A + ] + small_open_english_tasked_datasets = [x for x in small_open_english_tasked_datasets if x.id not in exclude_ids] + # some ids clearly speech related + small_open_english_tasked_datasets = [x for x in small_open_english_tasked_datasets if 'speech' not in x.id] + # HF testing + small_open_english_tasked_datasets = [x for x in small_open_english_tasked_datasets if + 'hf-internal-testing' not in x.id] + small_open_english_tasked_datasets = [x for x in small_open_english_tasked_datasets if + 'chinese' not in x.id] + + sorted_small_open_english_tasked_datasets = sorted([(x.downloads, x) for x in small_open_english_tasked_datasets], + key=lambda x: x[0], reverse=True) + + # NOTES: + # Run like pytest -s -v create_data.py::test_get_open_datasets &> getdata9.log + # See what needs config passed and add: + # grep 'load_dataset(' getdata9.log|grep -v data_id|less -S + # grep "pip install" getdata9.log + # NOTE: Some datasets have default config, but others are there. Don't know how to access them. + + """ + https://huggingface.co/datasets/wikihow/blob/main/wikihow.py + https://github.com/mahnazkoupaee/WikiHow-Dataset + https://ucsb.box.com/s/ap23l8gafpezf4tq3wapr6u8241zz358 + https://ucsb.app.box.com/s/ap23l8gafpezf4tq3wapr6u8241zz358 + """ + + """ + # some ambiguous or non-commercial datasets + https://github.com/PhoebusSi/alpaca-CoT + """ + + timeout = 3 * 60 + # laion/OIG takes longer + for num_downloads, dataset in sorted_small_open_english_tasked_datasets: + data_id = dataset.id + func = do_one + args = (data_id, num_downloads) + kwargs = {} + with ProcessPoolExecutor(max_workers=1) as executor: + future = executor.submit(func, *args, **kwargs) + try: + future.result(timeout=timeout) + except concurrent.futures.TimeoutError: + print("\n\ndata_id %s timeout\n\n" % data_id, flush=True) + for child in psutil.Process(os.getpid()).children(recursive=True): + os.kill(child.pid, signal.SIGINT) + os.kill(child.pid, signal.SIGTERM) + os.kill(child.pid, signal.SIGKILL) + + +def do_one(data_id, num_downloads): + from datasets import load_dataset + out_file = "data_%s.parquet" % str(data_id.replace('/', '_')) + if os.path.isfile(out_file) and os.path.getsize(out_file) > 1024 ** 3: + return + try: + print("Loading data_id %s num_downloads: %s" % (data_id, num_downloads), flush=True) + avail_list = None + try: + data = load_dataset(data_id, 'foobar') + except Exception as e: + if 'Available: ' in str(e): + avail_list = ast.literal_eval(str(e).split('Available:')[1].strip()) + else: + avail_list = None + if avail_list is None: + avail_list = [None] + print("%s avail_list: %s" % (data_id, avail_list), flush=True) + + for name in avail_list: + out_file = "data_%s_%s.parquet" % (str(data_id.replace('/', '_')), str(name)) + if os.path.isfile(out_file): + continue + data = load_dataset(data_id, name) + column_names_dict = data.column_names + column_names = column_names_dict[list(column_names_dict.keys())[0]] + print("Processing data_id %s num_downloads: %s columns: %s" % (data_id, num_downloads, column_names), + flush=True) + data_dict = data.data + col_dict = data.num_columns + first_col = list(col_dict.keys())[0] + if 'train' in data_dict: + df = data['train'].to_pandas() + else: + df = data[first_col].to_pandas() + # csv has issues with escaping chars, even for datasets I know I want + df.to_parquet(out_file, index=False) + except Exception as e: + t, v, tb = sys.exc_info() + ex = ''.join(traceback.format_exception(t, v, tb)) + print("Exception: %s %s" % (data_id, ex), flush=True) + + +def test_otherlic(): + from huggingface_hub import list_datasets + lic = ['license:odc-by', + 'license:cc-by-4.0', + 'license:cc-by-3.0', + 'license:cc-by-2.0', + 'license:cc-by-2.5', + 'license:cc-by-sa-4.0', + 'license:odbl', + 'license:pddl', + 'license:ms-pl', + 'license:zlib', + ] + datasets = flatten_list([[x for x in list_datasets(filter=y) if 'translation' not in str(x.tags)] for y in lic]) + print(len(datasets)) + + +# These useful datasets are determined based upon data sample, column types, and uniqueness compared to larger datasets like Pile +# grep columns getdata13.log|grep -v "\['image'\]"|sort|uniq|grep -v tokens|grep -v "'image'"|grep -v embedding|grep dialog +useful = ['Dahoas/instruct-human-assistant-prompt', + 'Dahoas/first-instruct-human-assistant-prompt', + 'knkarthick/dialogsum', # summary of conversation + 'McGill-NLP/FaithDial', # medium quality + 'Zaid/quac_expanded', # medium quality context + QA + '0-hero/OIG-small-chip2', # medium + 'alistvt/coqa-flat', # QA medium + 'AnonymousSub/MedQuAD_47441_Question_Answer_Pairs', # QA medium + 'Anthropic/hh-rlhf', # high quality # similar to Dahoas/full-hh-rlhf + 'arjunth2001/online_privacy_qna', # good quality QA + 'Dahoas/instruct_helpful_preferences', # medium quality instruct + 'Dahoas/rl-prompt-dataset', # medium chat + 'Dahoas/rm-static', # medium chat + 'Dahoas/static-hh', # medium chat # HuggingFaceH4/self_instruct + 'Dahoas/synthetic-instruct-gptj-pairwise', # medium chat + 'eli5', # QA if prompt ELI5 + 'gsm8k', # QA (various) + 'guanaco/guanaco', # prompt/response + 'kastan/rlhf-qa-comparisons', # good QA + 'kastan/rlhf-qa-conditional-generation-v2', # prompt answer + 'OllieStanley/humaneval-mbpp-codegen-qa', # code QA, but started from words, so better than other code QA + 'OllieStanley/humaneval-mbpp-testgen-qa', # code QA + 'Graverman/Instruct-to-Code', # code QA + 'openai/summarize_from_feedback', # summarize + 'relbert/analogy_questions', # analogy QA + 'yitingxie/rlhf-reward-datasets', # prompt, chosen, rejected. + 'yizhongw/self_instruct', # instruct (super natural & instruct) + 'HuggingFaceH4/asss', # QA, big A + 'kastan/rlhf-qa-conditional-generation-v2', # QA + 'cosmos_qa', # context QA + 'vishal-burman/c4-faqs', # QA but not so much reasoning, but alot of text + 'squadshifts', # QA from context + 'hotpot_qa', # QA from context + 'adversarial_qa', # QA from context + 'allenai/soda', # dialog -> narrative/summary + 'squad_v2', # context QA + 'squadshifts', # context QA + 'dferndz/cSQuAD1', # context QA + 'dferndz/cSQuAD2', # context QA + 'din0s/msmarco-nlgen', # context QA + 'domenicrosati/TruthfulQA', # common sense truthful QA -- trivia but good trivia + 'hotpot_qa', # context, QA + 'HuggingFaceH4/self-instruct-eval', # instruct QA, medium quality, some language reasoning + 'kastan/EE_QA_for_RLHF', # context QA + 'KK04/LogicInference_OA', # instruction logical QA + 'lmqg/qa_squadshifts_synthetic', # context QA + 'lmqg/qg_squad', # context QA + 'lmqg/qg_squadshifts', # context QA + 'lmqg/qg_subjqa', # context QA + 'pszemraj/HC3-textgen-qa', + # QA medium, has human responses -- humans tend to provide links instead of trying to answer + 'pythonist/newdata', # long context, QA, brief A + 'ropes', # long background, situation, question, A + 'wikitablequestions', # table -> QA + 'bigscience/p3', # context QA but short answers + ] + +code_useful = ['0n1xus/codexglue', + 'openai_humaneval', + 'koutch/staqc', + ] + +maybe_useful = ['AlekseyKorshuk/comedy-scripts', + 'openbookqa', # hard to parse, low reasoning + 'qed', # reasonable QA, but low reasoning + 'selqa', # candidate answers + 'HuggingFaceH4/instruction-pilot-outputs-filtered', + 'GBaker/MedQA-USMLE-4-options', # medical QA with long questions + 'npc-engine/light-batch-summarize-dialogue', # dialog summarize, kinda low specific quality + ] + +summary_useful = ['austin/rheum_abstracts', + 'CarperAI/openai_summarize_comparisons', # summarize chosen/rejected + 'CarperAI/openai_summarize_tldr', # summarize QA + 'ccdv/cnn_dailymail', # summarize news + 'ccdv/govreport-summarization', # summarize high quality + 'ccdv/pubmed-summarization', # summarize high quality + 'duorc', # plot -> QA + 'farleyknight/big_patent_5_percent', # desc -> abstract + 'multi_news', # summary + 'opinosis', + 'SophieTr/reddit_clean', + 'allenai/mup', # long text -> summary + 'allenai/multi_lexsum', # long text -> summary + 'big_patent', + 'allenai/wcep_dense_max', + 'awinml/costco_long_practice', + 'GEM/xsum', + 'ratishsp/newshead', + 'RussianNLP/wikiomnia', # russian + 'stacked-summaries/stacked-xsum-1024', + ] + +math_useful = [ + 'competition_math' +] + +skipped = ['c4', # maybe useful, used for flan, but skipped due to size + ] + +""" +To get training data from oig: +pytest test_oig test_grade_final test_finalize_to_json +""" + +human = ':' +bot = ':' + + +def test_assemble_and_detox(): + import re + from profanity_check import predict_prob + df_list = [] + for data in useful_oig_files: + print("Processing %s" % data, flush=True) + df = pd.read_parquet(data) + df = df.reset_index(drop=True) + # chop up into human/bot interactions of no more than 10kB per row + text_list = df[['text']].values.ravel().tolist() + new_text = [] + max_len = 2048 # uber cutoff + MAX_LEN = 2048 // 2 - 30 # max len per question/answer + for text in tqdm(text_list): + human_starts = [m.start() for m in re.finditer(': ', text)] + if len(human_starts) == 1: + human_starts = [0, len(text)] # always go into for loop below + blurb = '' + for i in range(len(human_starts) - 1): + interaction = text[human_starts[i]: human_starts[i + 1]][:max_len] + blurb += interaction + if len(blurb) >= MAX_LEN: + blurb = get_sentences(blurb, length=MAX_LEN)[0] + new_text.append(blurb + "\n:") + blurb = '' + if blurb: + blurb = get_sentences(blurb, length=MAX_LEN)[0] + new_text.append(blurb + "\n:") + + if len(new_text) > len(text_list): + print("Added %d new rows (before: %d)" % (len(new_text) - df.shape[0], df.shape[0])) + df = pd.DataFrame({"text": new_text, "source": [data] * len(new_text)}) + df = df.drop_duplicates(keep='first') + print(df['text'].apply(lambda x: len(x)).describe()) + assert df['text'].apply(lambda x: len(x)).max() <= 2 * max_len + + # faster than better_profanity, do early + df['profanity'] = predict_prob(df['text']) + before_rows = df.shape[0] + df = df[df['profanity'] < 0.25] # drop any low quality stuff + after_rows = df.shape[0] + print("Dropped %d rows out of %d due to alt-profanity-check" % (before_rows - after_rows, before_rows)) + df_list.append(df) + print("Done processing %s -> %s rows" % (data, df.shape[0]), flush=True) + print("So far have %d rows" % sum([len(x) for x in df_list])) + df_final = pd.concat(df_list) + df_final = df_final.sample(frac=1, random_state=1234).reset_index(drop=True) + df_final.to_parquet('h2oGPT.cleaned.human_bot.shorter.parquet', index=False) + + +def test_basic_cleaning(): + # from better_profanity import profanity + # https://pypi.org/project/alt-profanity-check/ + from profanity_check import predict + df_list = [] + for data in useful_oig_files: + # for data in useful_oig_files[:5]: + # for data in ['unified_openai_summarize_tldr.jsonl.parquet']: + print("Processing %s" % data, flush=True) + df = pd.read_parquet(data) + df = df.reset_index(drop=True) + # NOTE: Not correct if multiple human-bot interactions, but those dialogs even more desired + # avg_chars = len(df['text'][0])/(df['text'][0].count(human)+df['text'][0].count(bot)) + df['avg_words'] = df['text'].apply(lambda x: x.count(' ') / (x.count(human) + x.count(bot)) / 2.0) + df['avg_bot_words'] = df['text'].apply(lambda x: x.split(bot)[1].count(' ') / x.count(bot)) + # df['bad_words'] = df['text'].apply(lambda x: profanity.contains_profanity(x)) + # low_quality_patterns = ['Write the rest of this wikipedia article'] + res = predict(df['text']) + df['bad_words'] = res + df = df.reset_index(drop=True) + df = df[df['bad_words'] == 0] + df = df[['text', 'avg_words', 'avg_bot_words']] + df = df.drop_duplicates(keep='first') + print(df[df['avg_words'] == df['avg_words'].max()]['text'].values) + median_words = np.median(df['avg_words']) + min_words_per_entity = max(30, 0.8 * median_words) + max_words_per_entity = 2048 # too hard to learn from for now + df = df[df['avg_words'] > min_words_per_entity] + df = df[df['avg_words'] < max_words_per_entity] + + min_words_per_entity = max(20, 0.5 * median_words) # bot should say stuff for now + max_words_per_entity = 2048 # too hard to learn from for now + df = df[df['avg_bot_words'] > min_words_per_entity] + df = df[df['avg_bot_words'] < max_words_per_entity] + + df_list.append(df) + print("Done processing %s -> %s rows" % (data, df.shape[0]), flush=True) + df_final = pd.concat(df_list) + df_final.to_parquet('h2oGPT.cleaned.human_bot.parquet', index=False) + + +from joblib import Parallel, delayed, effective_n_jobs +from sklearn.utils import gen_even_slices +from sklearn.utils.validation import _num_samples + + +def parallel_apply(df, func, n_jobs=-1, **kwargs): + """ Pandas apply in parallel using joblib. + Uses sklearn.utils to partition input evenly. + + Args: + df: Pandas DataFrame, Series, or any other object that supports slicing and apply. + func: Callable to apply + n_jobs: Desired number of workers. Default value -1 means use all available cores. + **kwargs: Any additional parameters will be supplied to the apply function + + Returns: + Same as for normal Pandas DataFrame.apply() + + """ + + if effective_n_jobs(n_jobs) == 1: + return df.apply(func, **kwargs) + else: + ret = Parallel(n_jobs=n_jobs)( + delayed(type(df).apply)(df[s], func, **kwargs) + for s in gen_even_slices(_num_samples(df), effective_n_jobs(n_jobs))) + return pd.concat(ret) + + +def add_better_profanity_flag(df): + from better_profanity import profanity + df['better_profanity'] = parallel_apply( + df['text'], + lambda x: profanity.contains_profanity(x), + n_jobs=-1, + ) + return df + + +def add_textstat_grade(df): + import textstat + + def myfunc(x): + return textstat.flesch_kincaid_grade(x) # simple grade + + if False: + import dask.dataframe as dd + # 40 seconds for 1000 rows, but have 1,787,799 rows + ddata = dd.from_pandas(df, npartitions=120) + + df['flesch_grade'] = ddata['text'].apply(myfunc).compute() + if True: + # fast way + df['flesch_grade'] = parallel_apply(df['text'], myfunc, n_jobs=-1) + return df + + +def add_deberta_grade(df): + from transformers import AutoModelForSequenceClassification, AutoTokenizer + import torch + reward_name = "OpenAssistant/reward-model-deberta-v3-large-v2" + rank_model, tokenizer = AutoModelForSequenceClassification.from_pretrained( + reward_name), AutoTokenizer.from_pretrained(reward_name) + device = 'cuda' if torch.cuda.is_available() else 'cpu' + rank_model.to(device) + + def get_question(x): + return x.replace(': ', '').split(':')[0] + + def get_answer(x): + try: + answer = x.split(': ')[1].split(':')[0].replace(': ', '') + except: + answer = x.split(':')[1].split(':')[0].replace(':', '') + return answer + + df['question'] = parallel_apply(df['text'], get_question, n_jobs=-1) + df['answer'] = parallel_apply(df['text'], get_answer, n_jobs=-1) + + from datasets import Dataset + from transformers import pipeline + from transformers.pipelines.pt_utils import KeyPairDataset + import tqdm + + pipe = pipeline( + "text-classification", + model=reward_name, + device="cuda:0" if torch.cuda.is_available() else "cpu" + ) + start = 0 + batch_size = 64 * 16 + micro_batch = orig_micro_batch = 16 + end = 0 + import socket + checkpoint = "grades.%s.pkl" % socket.gethostname() + grades = [] + import pickle + if os.path.exists(checkpoint): + with open(checkpoint, "rb") as f: + start, grades = pickle.loads(f.read()) + last_oom = 0 + while end < df.shape[0]: + # manual batching to handle OOM more gracefully + end = min(start + batch_size, df.shape[0]) + if start == end: + break + dataset = Dataset.from_pandas(df.iloc[start:end, :]) + try: + grades.extend([ + x['score'] for x in tqdm.tqdm( + pipe(KeyPairDataset(dataset, "question", "answer"), batch_size=micro_batch) + ) + ]) + except torch.cuda.OutOfMemoryError: + last_oom = start + micro_batch = max(1, micro_batch // 2) + print("OOM - retrying with micro_batch=%d" % micro_batch) + continue + if last_oom == start: + micro_batch = orig_micro_batch + print("Returning to micro_batch=%d" % micro_batch) + assert len(grades) == end + start = end + with open(checkpoint, "wb") as f: + f.write(pickle.dumps((end, grades))) + print("%d/%d" % (end, df.shape[0])) + df['grade_deberta'] = grades + if os.path.exists(checkpoint): + os.remove(checkpoint) + return df + + +def test_chop_by_lengths(): + file = "h2oGPT.cleaned.human_bot.shorter.parquet" + df = pd.read_parquet(file).reset_index(drop=True) + df = count_human_bot_lengths(df) + df['rand'] = np.random.rand(df.shape[0]) + df['rand2'] = np.random.rand(df.shape[0]) + before_rows = df.shape[0] + # throw away short human/bot responses with higher likelihood + df = df[(df['len_human_mean'] > 20)] # never keep very short ones + df = df[(df['len_human_mean'] > 30) | (df['rand'] < 0.2)] + df = df[(df['len_human_mean'] > 50) | (df['rand'] < 0.5)] + df = df[(df['len_human_max'] < 10000)] # drop super long (basically only human) ones + df = df[(df['len_bot_mean'] > 20)] # never keep very short ones + df = df[(df['len_bot_mean'] > 30) | (df['rand2'] < 0.2)] + df = df[(df['len_bot_mean'] > 50) | (df['rand2'] < 0.5)] + df = df[(df['len_bot_max'] < 10000)] # drop super long (only bot) ones + assert df['text'].apply(lambda x: len(x)).max() < 20000 + df = df.drop(['rand', 'rand2'], axis=1) + after_rows = df.shape[0] + print("Chopped off %d out of %d rows due to length" % (before_rows - after_rows, before_rows)) + print(df.describe()) + df.to_parquet('h2oGPT.cleaned.chopped.human_bot.shorter.parquet', index=False) + + +def count_human_bot_lengths(df, human=None, bot=None): + import re + len_human_min = [] + len_human_max = [] + len_human_mean = [] + len_bot_min = [] + len_bot_max = [] + len_bot_mean = [] + human = human or ':' + bot = bot or ':' + for is_human in [True, False]: + what = human if is_human else bot + other = human if not is_human else bot + for i in range(df.shape[0]): + text = df.loc[i, 'text'] + assert isinstance(text, str) + starts = [m.start() for m in re.finditer(what, text)] + if len(starts) == 1: + starts = [starts[0], len(text)] # always go into for loop below + assert len(text) + list_what = [] + for ii in range(len(starts) - 1): + interaction = text[starts[ii]: starts[ii + 1]] + if other in interaction: + interaction = interaction[:interaction.find(other)] + interaction.strip() + list_what.append(interaction) + if not list_what: + list_what = [''] # handle corrupted data, very rare, leads to sizes 0 + if is_human: + len_human_min.append(min([len(x) for x in list_what])) + len_human_max.append(max([len(x) for x in list_what])) + len_human_mean.append(np.mean([len(x) for x in list_what])) + else: + len_bot_min.append(min([len(x) for x in list_what])) + len_bot_max.append(max([len(x) for x in list_what])) + len_bot_mean.append(np.mean([len(x) for x in list_what])) + df['len_human_min'] = len_human_min + df['len_human_max'] = len_human_max + df['len_human_mean'] = len_human_mean + df['len_bot_min'] = len_bot_min + df['len_bot_max'] = len_bot_max + df['len_bot_mean'] = len_bot_mean + np.random.seed(1234) + pd.set_option('display.max_columns', None) + print("Before chopping") + print(df.describe()) + return df + + +def test_grade(): + df = None + + file = "h2oGPT.cleaned.chopped.human_bot.shorter.parquet" + output_file = "h2oGPT.cleaned.graded1.human_bot.shorter.parquet" + if not os.path.exists(output_file): + if df is None: + df = pd.read_parquet(file).reset_index(drop=True) + df = add_textstat_grade(df) + min_grade = 10 + max_grade = 25 + df = df[df['flesch_grade'] >= min_grade] + df = df[df['flesch_grade'] <= max_grade] + print("After Flesch grade") + print(df.describe()) + df.to_parquet(output_file, index=False) + + file = output_file + output_file = "h2oGPT.cleaned.graded2.human_bot.shorter.parquet" + if not os.path.exists(output_file): + # slower than alt-profanity, do last, but do before deberta grading, since that's slower + if df is None: + df = pd.read_parquet(file).reset_index(drop=True) + df = add_better_profanity_flag(df) + before_rows = df.shape[0] + df = df[df['better_profanity'] == 0] + df = df.drop(['better_profanity'], axis=1) + after_rows = df.shape[0] + print("Dropped %d rows out of %d due to better_profanity" % (before_rows - after_rows, before_rows)) + print(df.describe()) + df.to_parquet(output_file, index=False) + + file = output_file + output_file = 'h2oGPT.cleaned.graded3.human_bot.shorter.parquet' + if not os.path.exists(output_file): + if df is None: + df = pd.read_parquet(file).reset_index(drop=True) + df = add_deberta_grade(df) + min_grade = 0.3 + max_grade = np.inf + before_rows = df.shape[0] + df = df[df['grade_deberta'] >= min_grade] + df = df[df['grade_deberta'] <= max_grade] + after_rows = df.shape[0] + print("Dropped %d rows out of %d due to deberta grade" % (before_rows - after_rows, before_rows)) + print("After DeBERTa grade") + print(df.describe()) + df.to_parquet(output_file, index=False) + + file = output_file + output_file = 'h2oGPT.cleaned.graded.human_bot.shorter.parquet' + if df is None: + df = pd.read_parquet(file).reset_index(drop=True) + df.to_parquet(output_file, index=False) + + +@pytest.mark.parametrize( + "fixup_personality, only_personality, deberta_grading", + [ + # [False, False, False], + # [True, True, False], + [True, False, False], + # [True, False, True], + ] +) +@pytest.mark.parametrize("prompt_type", ["llama2"]) +def test_add_open_assistant(fixup_personality, only_personality, deberta_grading, prompt_type, save_json=True): + """ + Flatten tree structure into one row per path from root to leaf + Also turn into human_bot prompting format: + : question\n: answer : question2\n: answer2 Etc. + Also saves a .json locally as side-effect + returns list of dicts, containing intput, prompt_type and source + """ + from datasets import load_dataset + data_file = "OpenAssistant/oasst1" + ds = load_dataset(data_file) + df = pd.concat([ds['train'].to_pandas(), ds['validation'].to_pandas()], axis=0) + rows = {} + message_ids = df['message_id'].values.tolist() + message_tree_ids = df['message_tree_id'].values.tolist() + parent_ids = df['parent_id'].values.tolist() + texts = df['text'].values.tolist() + roles = df['role'].values.tolist() + deleteds = df['deleted'].values.tolist() + for i in range(df.shape[0]): + # collect all trees + message_id = message_ids[i] + message_tree_id = message_tree_ids[i] + parent_id = parent_ids[i] + text = texts[i] + deleted = deleteds[i] + if deleted: + continue + if fixup_personality: + text = text.replace("Open Assistant", "h2oGPT") + text = text.replace("Open-Assistant", "h2oGPT") + text = text.replace("open-assistant", "h2oGPT") + text = text.replace("OpenAssistant", "h2oGPT") + text = text.replace("open assistant", "h2oGPT") + text = text.replace("Open Assistand", "h2oGPT") + text = text.replace("Open Assitant", "h2oGPT") + text = text.replace("Open Assistent", "h2oGPT") + text = text.replace("Open Assisstant", "h2oGPT") + text = text.replace("Open Assitent", "h2oGPT") + text = text.replace("Open Assitiant", "h2oGPT") + text = text.replace("Open Assistiant", "h2oGPT") + text = text.replace("Open Assitan ", "h2oGPT ") + text = text.replace("Open Assistan ", "h2oGPT ") + text = text.replace("Open Asistant", "h2oGPT") + text = text.replace("Open Assiant", "h2oGPT") + text = text.replace("Assistant", "h2oGPT") + text = text.replace("LAION AI", "H2O.ai") + text = text.replace("LAION-AI", "H2O.ai") + text = text.replace("LAION,", "H2O.ai,") + text = text.replace("LAION.ai", "H2O.ai") + text = text.replace("LAION.", "H2O.ai.") + text = text.replace("LAION", "H2O.ai") + + role = roles[i] + if prompt_type == "llama2": + new_data = ('[INST] ' if role == 'prompter' else ' [/INST] ') + text + if parent_id and role == 'prompter': + new_data = " " + new_data + elif prompt_type == "human_bot": + new_data = (': ' if role == 'prompter' else ': ') + text + else: + raise NotImplementedError("prompt_type not supported") + entry = dict(message_id=message_id, parent_id=parent_id, text=new_data) + if message_tree_id not in rows: + rows[message_tree_id] = [entry] + else: + rows[message_tree_id].append(entry) + + all_rows = [] + + for node_id in rows: + # order responses in tree, based on message/parent relationship + conversations = [] + + list_msgs = rows[node_id] + # find start + while len(list_msgs): + for i, leaf in enumerate(list_msgs): + found = False + parent_id = leaf['parent_id'] + if parent_id is None: + # conversation starter + conversations.append(leaf) + found = True + else: + for conv in conversations: + # find all conversations to add my message to + if parent_id in conv['message_id'] and parent_id != conv['message_id'][-len(parent_id):]: + # my message doesn't follow conversation + continue + if parent_id == conv['message_id'][-len(parent_id):]: + # my message follows conversation, but fork first, so another follow-on message can do same + conversations.append(conv.copy()) + if prompt_type == "llama2": + conv['text'] += f"""{leaf['text']}""" + elif prompt_type == "human_bot": + conv['text'] += f""" +{leaf['text']} +""" + else: + raise NotImplementedError + conv['message_id'] += leaf['message_id'] + found = True + break + if found: + # my content was used, so nuke from list + del list_msgs[i] + break + + # now reduce down to final conversations, find the longest chains of message ids + for i, conv in enumerate(conversations): + for j, conv2 in enumerate(conversations): + if i == j: + continue + if conv['message_id'] and conv2['message_id']: + assert conv['message_id'] != conv2['message_id'] + # delete the shorter conversation, if one contains the other + if conv['message_id'] in conv2['message_id']: + conv['message_id'] = None + if conv2['message_id'] in conv['message_id']: + conv2['message_id'] = None + conversations = [c for c in conversations if c['message_id']] + if only_personality: + if prompt_type == "human_bot": + all_rows.extend( + [dict(input=c['text'] + "\n:", output="", prompt_type='plain', source=data_file) for c in conversations if + 'h2oGPT' in c['text']]) + elif prompt_type == "llama2": + all_rows.extend( + [dict(input=c['text'] + + ("" if c['text'].rfind("[/INST]") > c['text'].rfind("[INST]") else " [/INST]"), + output="", prompt_type='plain', source=data_file) for c in conversations if + 'h2oGPT' in c['text']]) + else: + raise NotImplementedError + else: + if prompt_type == "human_bot": + all_rows.extend( + [dict(input=c['text'] + "\n:", output="", prompt_type='plain', source=data_file) for c in conversations + if + "What is H2O.ai" not in c['text']]) + elif prompt_type == "llama2": + all_rows.extend( + [dict(input=c['text'] + + (" " if c['text'].rfind("[/INST]") > c['text'].rfind("[INST]") else " [/INST]"), + output="", prompt_type='plain', source=data_file) for c in conversations if + "What is H2O.ai" not in c['text']]) + else: + raise NotImplementedError + + unhelpful = get_unhelpful_list() + all_rows = [x for x in all_rows if not any(u in x['input'] for u in unhelpful)] + personality = create_personality_data(prompt_type=prompt_type) + all_rows.extend(personality * 10) + np.random.seed(123) + np.random.shuffle(all_rows) + print(len(all_rows)) + if deberta_grading: + df = pd.DataFrame(all_rows) + df = df.rename(columns={'input': 'text'}) + df = add_deberta_grade(df) + df = df.rename(columns={'text': 'input'}) + drop = True + if drop: + min_grade = 0.3 + max_grade = np.inf + before_rows = df.shape[0] + df = df[df['grade_deberta'] >= min_grade] + df = df[df['grade_deberta'] <= max_grade] + after_rows = df.shape[0] + print("Dropped %d rows out of %d due to deberta grade" % (before_rows - after_rows, before_rows)) + print("After DeBERTa grade") + print(df.describe()) + all_rows = [] + for i in range(df.shape[0]): + all_rows.append( + dict( + input=df['input'].iloc[i], + output=df['output'].iloc[i], + source=df['source'].iloc[i], + prompt_type=df['prompt_type'].iloc[i], + grade_deberta=df['grade_deberta'].iloc[i], + ) + ) + if save_json: + data_file = data_file + \ + ("_h2ogpt" if fixup_personality else "") + \ + ("_only" if only_personality else "") + \ + ("_graded" if deberta_grading else "") + \ + ("_llama2_chat" if prompt_type == "llama2" else "") + for i in range(len(all_rows)): + all_rows[i]['id'] = i + with open(data_file.lower().replace("/", "_") + ".json", "w") as f: + f.write(json.dumps(all_rows, indent=2)) + return all_rows + + +def test_finalize_to_json(): + df = pd.read_parquet('h2oGPT.cleaned.graded.human_bot.shorter.parquet') + df = df.rename(columns={'text': 'input'}) + + print("Number of high-quality human_bot interactions: %s" % df.shape[0], flush=True) + + print("Adding open assistant data") + with open("openassistant_oasst1_h2ogpt_graded.json") as f: + open_assistant = json.loads(f.read()) + df = pd.concat([df, pd.DataFrame(open_assistant)], axis=0) + + def final_clean(df): + from better_profanity import profanity + profanity.load_censor_words_from_file("data/censor_words.txt") + df['profanity'] = parallel_apply( + df['input'], + lambda x: profanity.contains_profanity(x), + n_jobs=-1, + ) + return df[(df['profanity'] == 0)].reset_index(drop=True) + + print("Before cleaning: Number of final high-quality human_bot interactions: %s" % df.shape[0], flush=True) + df = final_clean(df) + print("After cleaning: Number of final high-quality human_bot interactions: %s" % df.shape[0], flush=True) + print(df.describe()) + print(df.shape) + row_list = [] + for i in range(df.shape[0]): + row_list.append( + dict( + input=df.loc[i, 'input'], + source=df.loc[i, 'source'], + prompt_type='plain', + ) + ) + np.random.seed(1234) + np.random.shuffle(row_list) + unhelpful = get_unhelpful_list() + row_list = [x for x in row_list if not any(u in x['input'] for u in unhelpful)] + for i in range(len(row_list)): + row_list[i]['id'] = i + row_list[i]['input'] = row_list[i]['input'].replace(" :", "\n:") + with open('h2ogpt-oig-oasst1-instruct-cleaned-v3.json', "w") as f: + f.write(json.dumps(row_list, indent=2)) + + +def create_personality_data(prompt_type="llama2"): + questions = [ + "What's your name?", + "What is your name?", + "What are you?", + "Who are you?", + "Do you have a name?", + "Who trained you?", + "Who created you?", + "Who made you?", + ] + answers = [ + "I'm h2oGPT, a large language model by H2O.ai.", + "I'm h2oGPT, a large language model by H2O.ai, the visionary leader in democratizing AI.", + "My name is h2oGPT. I'm a large language model by H2O.ai, the visionary leader in democratizing AI.", + "My name is h2oGPT. I'm a large language model trained by H2O.ai.", + "Hi! I'm h2oGPT, a large language model by H2O.ai.", + "Hi! I'm h2oGPT, a large language model by H2O.ai, the visionary leader in democratizing AI.", + ] + help = [ + "", + " How can I help you?", + " How may I assist you?", + " Nice to meet you.", + ] + import itertools + rows = [] + for pair in itertools.product(questions, answers, help): + rows.append( + dict(input=f"{pair[0]}", output=f"{pair[1]}{pair[2]}", prompt_type=prompt_type, source="H2O.ai") + ) + for q, a in [ + ("What is H2O.ai?", "H2O.ai is a technology company that aims to democratize AI and make it accessible to a broader audience by simplifying the process of creating and deploying machine learning models."), + ("What is h2o.ai?", "H2O.ai is a technology company that aims to democratize AI and make it accessible to a broader audience by simplifying the process of creating and deploying machine learning models."), + ("What is H2O?", "H2O.ai is a technology company that aims to democratize AI and make it accessible to a broader audience by simplifying the process of creating and deploying machine learning models."), + ("Who is h2o.ai?", "H2O.ai is a technology company that aims to democratize AI and make it accessible to a broader audience by simplifying the process of creating and deploying machine learning models."), + ("who is h2o.ai?", "H2O.ai is a technology company that aims to democratize AI and make it accessible to a broader audience by simplifying the process of creating and deploying machine learning models."), + ("who is h2o?", "H2O.ai is a technology company that aims to democratize AI and make it accessible to a broader audience by simplifying the process of creating and deploying machine learning models."), + ("what is H2O.ai?", "H2O.ai is the visionary leader in democratizing AI."), + ("who is H2O.ai?", "H2O.ai is the visionary leader in democratizing AI."), + ("who is H2O?", "H2O.ai is the visionary leader in democratizing AI."), + ("Who is h20?", "H2O.ai is the visionary leader in democratizing AI."), + ]: + rows.append(dict(input=q, output=a, prompt_type=prompt_type, source='H2O.ai')) + print(len(rows)) + with open("h2ogpt-personality.json", "w") as f: + f.write(json.dumps(rows, indent=2)) + return rows + + +def test_check_stats_data(): + filename = 'h2ogpt-oig-oasst1-instruct-cleaned-v3.json' + df = pd.read_json(filename) + + # get word stats + df['char_count'] = df['input'].apply(lambda x: len(x)) + import matplotlib.pyplot as plt + plt.figure(figsize=(10, 10)) + plt.hist(df['char_count'], bins=100) + chars_avg = np.mean(df['char_count']) + chars_median = np.median(df['char_count']) + plt.title("char_count avg: %s median: %s" % (chars_avg, chars_median)) + plt.savefig('chars_hist.png') + plt.close() + + # get tokenize stats for random sample of 1000 rows + from finetune import generate_and_tokenize_prompt + from loaders import get_loaders, get_tokenizer + from functools import partial + + llama_type = False + tokenizer_base_model = base_model = 'h2oai/h2ogpt-oasst1-512-20b' + model_loader, tokenizer_loader, conditional_type = ( + get_loaders(model_name=base_model, reward_type=False, llama_type=llama_type)) + local_files_only = False + resume_download = True + use_auth_token = False + tokenizer = get_tokenizer(tokenizer_loader, tokenizer_base_model, local_files_only, resume_download, use_auth_token) + prompt_type = 'plain' # trained with data already in human bot form + train_on_inputs = True + add_eos_token = False + cutoff_len = 512 # can choose 2048 + generate_and_tokenize_prompt_fun = partial(generate_and_tokenize_prompt, prompt_type=prompt_type, + train_on_inputs=train_on_inputs, add_eos_token=add_eos_token, + cutoff_len=cutoff_len, tokenizer=tokenizer) + from datasets import load_dataset + data = load_dataset("json", data_files={"train": filename}) + val_set_size = 0.90 + train_val = data["train"].train_test_split( + test_size=val_set_size, shuffle=True, seed=42 + ) + train_data = train_val["train"] + train_data = train_data.shuffle().map(generate_and_tokenize_prompt_fun, num_proc=os.cpu_count()) + + df_tokens = pd.DataFrame([len(x) for x in train_data['input_ids']], columns=['token_count']) + + plt.figure(figsize=(10, 10)) + plt.hist(df_tokens['token_count'], bins=100) + token_avg = np.mean(df_tokens['token_count']) + token_median = np.median(df_tokens['token_count']) + plt.title("token_count with cutoff=%s avg: %s median: %s" % (cutoff_len, token_avg, token_median)) + plt.savefig('token_hist_%s.png' % cutoff_len) + plt.close() + + +def get_unhelpful_list(): + # base versions + unhelpful = ["I'm sorry, I didn't quite understand your question, could you please rephrase it?", + "I'm sorry, but I don't understand your question. Could you please rephrase it?", + "I'm sorry, I don't quite understand your question", + "I'm sorry, I don't know", + "I'm sorry, but I don't know", + "I don't know anything", + "I do not know", + "I don't know", + "I don't know how", + "I do not know how", + "Can you please explain what you mean", + "please explain what you mean", + "please explain", + "I'm sorry, but I don't know how to tell a story. Can you please explain what you mean by", + "I'm sorry but I don't understand what you mean", + "I don't understand", + "I don't have the ability", + "I do not have the ability", + "I do not have", + "I am a language model,", + "I am a large language model,", + "I do not understand your question. Can you please try to make it clearer?", + "I'm sorry, but as an AI language model", + "I apologize, but I cannot rephrase text that I cannot understand. Your post is difficult to read and follow.", + "I apologize, but I am not h2oGPT. I am a language model developed by H2O.ai. How may I help you?", + "Sorry, but I am not an actual Linux shell, nor am I capable of emulating one. I am an open source chat assistant and would be glad t", + "I apologize, but I cannot perform the task you have requested.", + "I'm sorry, I cannot perform this task as I am an AI language model and do not have access", + "I'm sorry, I'm not sure what you're asking for here.", + "I'm not sure what you are asking", + "You need to provide more context", + ] + # reduced versions, with redundant parts, just to give context for where they came from + unhelpful += ["sorry, I didn't quite understand your question", + "I didn't quite understand your question", + "I didn't understand your question", + "I did not understand your question", + "I did not understand the question", + "could you please rephrase" + "could you rephrase" + "I do not understand your question.", + "I do not understand the question.", + "I do not understand that question.", + "Can you please try to make it clearer", + "Can you try to make it clearer", + "sorry, but as an AI language model", + "as an AI language model", + "I apologize, but I cannot", + "I cannot rephrase text", + "I cannot understand. Your post is difficult to read and follow." + "Your post is difficult to read and follow." + "I apologize, but I am", + "Sorry, but I am not ", + "nor am I capable", + "I am not capable of", + "I apologize, but I cannot perform the task you have requested", + "I cannot perform the task", + "I cannot complete the task", + "I'm sorry", + "I am sorry", + "do not have access", + "not sure what you're asking for", + "not sure what you are asking for", + "not sure what is being asked", + "I'm not sure what you are asking", + "not sure what you are asking", + "You need to provide more context", + "provide more context", + ] + unhelpful += ["As a large language model", + "cannot provide any information", + "As an artificial intelligence I do not have the capability", + "As an artificial intelligence I don't have the capability", + "As an artificial intelligence I can't", + "As an artificial intelligence I cannot", + "I am sorry but I do not understand", + "Can you please explain", + "(sorry couldn't resist)", + "(sorry could not resist)", + " :)", + " ;)", + " :-)", + " ;-)", + " lol ", + "Thanks so much!!!", + "Thank You :)!!!", + "Please try not to repeat", + "I am an AI language model", + "I'm a AI assistant that", + "I'm an AI assistant that", + "I am an AI assistant that", + "etc.", + "etc.etc.", + "etc. etc.", + "etc etc", + ] + return unhelpful + + +def test_check_unhelpful(): + # file = '/home/jon/Downloads/openassistant_oasst1_h2ogpt_graded.json' + file = '/home/jon/Downloads/openassistant_oasst1_h2ogpt_grades.json' + # file = 'h2ogpt-oig-oasst1-instruct-cleaned-v2.json' + + unhelpful = get_unhelpful_list() + # data = json.load(open(file, 'rt')) + df = pd.read_json(file) + + use_reward_score_threshold = False + use_bleu_threshold = False + use_sentence_sim = True + + from sacrebleu.metrics import BLEU + bleu = BLEU() + from nltk.translate.bleu_score import sentence_bleu + + def get_bleu(actual, expected_list): + # return bleu.sentence_score(actual, expected_list).score + return sentence_bleu(expected_list, actual) + + threshold = 0.0 + if use_reward_score_threshold: + df = df[df['grade_deberta'] > threshold] + + # back to as if original json load + data = df.to_dict(orient='records') + bads = {} + string_all = str(data) + for sub in unhelpful: + bads[sub] = string_all.count(sub) + bads = {k: v for k, v in bads.items() if v > 0} + import pprint + pp = pprint.PrettyPrinter(indent=4) + pp.pprint(bads) + + total_bads = sum(list(bads.values())) + print('total_bads: %s' % total_bads, flush=True) + + # check just bot + import re + convs = [[x.strip() for x in re.split(r'%s|%s' % (human, bot), y['input']) if x.strip()] for y in data] + humans = [[x for i, x in enumerate(y) if i % 2 == 0] for y in convs] + bots = [[x for i, x in enumerate(y) if i % 2 == 1] for y in convs] + + # FIXME: apply back to json etc., just see for now + bleu_threshold = 0.9 + if use_bleu_threshold: + bots = [[x for x in y if get_bleu(x, unhelpful) < bleu_threshold] for y in tqdm(bots)] + + cosine_sim_threshold = 0.8 + if use_sentence_sim: + # pip install sentence_transformers-2.2.2 + from sentence_transformers import SentenceTransformer + # sent_model = 'bert-base-nli-mean-tokens' + # sent_model = 'nli-distilroberta-base-v2' + sent_model = 'all-MiniLM-L6-v2' + model = SentenceTransformer(sent_model) + sentence_embeddings = model.encode(unhelpful) + from sklearn.metrics.pairwise import cosine_similarity + bots = [x for x in tqdm(bots) if + np.max(cosine_similarity(model.encode(x), sentence_embeddings)) < cosine_sim_threshold] + + bads_bots = {} + string_all = str(bots) + for sub in unhelpful: + bads_bots[sub] = string_all.count(sub) + bads_bots = {k: v for k, v in bads_bots.items() if v > 0} + import pprint + pp = pprint.PrettyPrinter(indent=4) + pp.pprint(bads_bots) + + total_bads_bots = sum(list(bads_bots.values())) + print('threshold: %g use_bleu_threshold: %g total_bads_bots: %s total_bots: %s total_humans: %s' % ( + threshold, use_bleu_threshold, total_bads_bots, len(bots), len(humans)), flush=True) + + # assert len(bads) == 0, bads + assert len(bads_bots) == 0, bads_bots + + +def test_fortune2000_personalized(): + row_list = [] + import glob + if not os.path.isdir("wikitext"): + raise RuntimeError("download https://github.com/h2oai/h2ogpt/files/11423008/wikitext.zip and unzip") + for file in glob.glob("wikitext/*.txt"): + with open(file, "r") as f: + blob = f.read() + N = 512 * 4 + row_list.extend([{'input': s, 'prompt_type': 'plain', 'source': "%s" % os.path.basename(file)} + for s in get_sentences(blob, N) if s]) + personality = create_personality_data() + import copy + for i in range(10): + row_list.extend(copy.deepcopy(personality)) + np.random.seed(123) + np.random.shuffle(row_list) + for i in range(len(row_list)): + row_list[i]['id'] = i + for i in range(len(row_list)): + assert row_list[i]['id'] == i + with open("h2ogpt-fortune2000-personalized.json", "w") as ff: + ff.write(json.dumps(row_list, indent=2)) diff --git a/src/db_utils.py b/src/db_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c2a1a5866e11f86d26ceb4c2f3141f469ae42c88 --- /dev/null +++ b/src/db_utils.py @@ -0,0 +1,54 @@ +import uuid + +from enums import LangChainMode + + +def set_userid(db1s, requests_state1, get_userid_auth): + db1 = db1s[LangChainMode.MY_DATA.value] + assert db1 is not None and len(db1) == length_db1() + if not db1[1]: + db1[1] = get_userid_auth(requests_state1) + if not db1[2]: + username1 = None + if 'username' in requests_state1: + username1 = requests_state1['username'] + db1[2] = username1 + + +def set_userid_direct(db1s, userid, username): + db1 = db1s[LangChainMode.MY_DATA.value] + db1[1] = userid + db1[2] = username + + +def get_userid_direct(db1s): + return db1s[LangChainMode.MY_DATA.value][1] if db1s is not None else '' + + +def get_username_direct(db1s): + return db1s[LangChainMode.MY_DATA.value][2] if db1s is not None else '' + + +def get_dbid(db1): + return db1[1] + + +def set_dbid(db1): + # can only call this after function called so for specific user, not in gr.State() that occurs during app init + assert db1 is not None and len(db1) == length_db1() + if db1[1] is None: + # uuid in db is used as user ID + db1[1] = str(uuid.uuid4()) + + +def length_db1(): + # For MyData: + # 0: db + # 1: userid and dbid + # 2: username + + # For others: + # 0: db + # 1: dbid + # 2: None + return 3 diff --git a/src/enums.py b/src/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..c6013be6c9e773834cfb23e8c6cd856839856782 --- /dev/null +++ b/src/enums.py @@ -0,0 +1,225 @@ +from enum import Enum + + +class PromptType(Enum): + custom = -1 + plain = 0 + instruct = 1 + quality = 2 + human_bot = 3 + dai_faq = 4 + summarize = 5 + simple_instruct = 6 + instruct_vicuna = 7 + instruct_with_end = 8 + human_bot_orig = 9 + prompt_answer = 10 + open_assistant = 11 + wizard_lm = 12 + wizard_mega = 13 + instruct_vicuna2 = 14 + instruct_vicuna3 = 15 + wizard2 = 16 + wizard3 = 17 + instruct_simple = 18 + wizard_vicuna = 19 + openai = 20 + openai_chat = 21 + gptj = 22 + prompt_answer_openllama = 23 + vicuna11 = 24 + mptinstruct = 25 + mptchat = 26 + falcon = 27 + guanaco = 28 + llama2 = 29 + beluga = 30 + wizard3nospace = 31 + one_shot = 32 + falcon_chat = 33 + + +class DocumentSubset(Enum): + Relevant = 0 + RelSources = 1 + TopKSources = 2 + + +non_query_commands = [ + DocumentSubset.RelSources.name, + DocumentSubset.TopKSources.name +] + + +class DocumentChoice(Enum): + ALL = 'All' + + +class LangChainMode(Enum): + """LangChain mode""" + + DISABLED = "Disabled" + LLM = "LLM" + WIKI = "wiki" + WIKI_FULL = "wiki_full" + USER_DATA = "UserData" + MY_DATA = "MyData" + GITHUB_H2OGPT = "github h2oGPT" + H2O_DAI_DOCS = "DriverlessAI docs" + + +class LangChainTypes(Enum): + SHARED = 'shared' + PERSONAL = 'personal' + EITHER = 'either' # used when user did not pass which one, so need to try both + + +# modes should not be removed from visible list or added by name +langchain_modes_intrinsic = [LangChainMode.DISABLED.value, + LangChainMode.LLM.value, + LangChainMode.MY_DATA.value] + +langchain_modes_non_db = [LangChainMode.DISABLED.value, + LangChainMode.LLM.value] + + +class LangChainAction(Enum): + """LangChain action""" + + QUERY = "Query" + # WIP: + # SUMMARIZE_MAP = "Summarize_map_reduce" + SUMMARIZE_MAP = "Summarize" + SUMMARIZE_ALL = "Summarize_all" + SUMMARIZE_REFINE = "Summarize_refine" + + +class LangChainAgent(Enum): + """LangChain agents""" + + SEARCH = "Search" + COLLECTION = "Collection" + PYTHON = "Python" + CSV = "CSV" + PANDAS = "Pandas" + JSON = 'JSON' + + +no_server_str = no_lora_str = no_model_str = '[None/Remove]' + +# from site-packages/langchain/llms/openai.py +# but needed since ChatOpenAI doesn't have this information +model_token_mapping = { + "gpt-4": 8192, + "gpt-4-0314": 8192, + "gpt-4-32k": 32768, + "gpt-4-32k-0314": 32768, + "gpt-3.5-turbo": 4096, + "gpt-3.5-turbo-16k": 16 * 1024, + "gpt-3.5-turbo-0301": 4096, + "text-ada-001": 2049, + "ada": 2049, + "text-babbage-001": 2040, + "babbage": 2049, + "text-curie-001": 2049, + "curie": 2049, + "davinci": 2049, + "text-davinci-003": 4097, + "text-davinci-002": 4097, + "code-davinci-002": 8001, + "code-davinci-001": 8001, + "code-cushman-002": 2048, + "code-cushman-001": 2048, +} + +font_size = 2 +head_acc = 40 # 40 for 6-way +source_prefix = "Sources [Score | Link]:" +source_postfix = "End Sources

" + +super_source_prefix = f"""

SourcesSources [Score | Link]:""" +super_source_postfix = f"""End Sources

""" + + +def t5_type(model_name): + return 't5' == model_name.lower() or \ + 't5-' in model_name.lower() or \ + 'flan-' in model_name.lower() or \ + 'fastchat-t5' in model_name.lower() + + +def get_langchain_prompts(pre_prompt_query, prompt_query, pre_prompt_summary, prompt_summary, + model_name, inference_server, model_path_llama): + if model_name and ('falcon' in model_name or + 'Llama-2'.lower() in model_name.lower() or + model_path_llama and 'llama-2' in model_path_llama.lower()) or \ + model_name in [None, '']: + # use when no model, like no --base_model + pre_prompt_query1 = "Pay attention and remember the information below, which will help to answer the question or imperative after the context ends.\n" + prompt_query1 = "According to only the information in the document sources provided within the context above, " + elif inference_server and inference_server.startswith('openai'): + pre_prompt_query1 = "Pay attention and remember the information below, which will help to answer the question or imperative after the context ends. If the answer cannot be primarily obtained from information within the context, then respond that the answer does not appear in the context of the documents.\n" + prompt_query1 = "According to (primarily) the information in the document sources provided within context above, " + else: + pre_prompt_query1 = "" + prompt_query1 = "" + + pre_prompt_summary1 = """In order to write a concise single-paragraph or bulleted list summary, pay attention to the following text\n""" + prompt_summary1 = "Using only the information in the document sources above, write a condensed and concise summary of key results (preferably as bullet points):\n" + + if pre_prompt_query is None: + pre_prompt_query = pre_prompt_query1 + if prompt_query is None: + prompt_query = prompt_query1 + if pre_prompt_summary is None: + pre_prompt_summary = pre_prompt_summary1 + if prompt_summary is None: + prompt_summary = prompt_summary1 + + return pre_prompt_query, prompt_query, pre_prompt_summary, prompt_summary + + +def gr_to_lg(image_loaders, + pdf_loaders, + url_loaders, + **kwargs, + ): + if image_loaders is None: + image_loaders = kwargs['image_loaders_options0'] + if pdf_loaders is None: + pdf_loaders = kwargs['pdf_loaders_options0'] + if url_loaders is None: + url_loaders = kwargs['url_loaders_options0'] + # translate: + # 'auto' wouldn't be used here + ret = dict( + # urls + use_unstructured='Unstructured' in url_loaders, + use_playwright='PlayWright' in url_loaders, + use_selenium='Selenium' in url_loaders, + + # pdfs + use_pymupdf='on' if 'PyMuPDF' in pdf_loaders else 'off', + use_unstructured_pdf='on' if 'Unstructured' in pdf_loaders else 'off', + use_pypdf='on' if 'PyPDF' in pdf_loaders else 'off', + enable_pdf_ocr='on' if 'OCR' in pdf_loaders else 'off', + enable_pdf_doctr='on' if 'DocTR' in pdf_loaders else 'off', + try_pdf_as_html='on' if 'TryHTML' in pdf_loaders else 'off', + + # images + enable_ocr='OCR' in image_loaders, + enable_doctr='DocTR' in image_loaders, + enable_pix2struct='Pix2Struct' in image_loaders, + enable_captions='Caption' in image_loaders or 'CaptionBlip2' in image_loaders, + ) + if 'CaptionBlip2' in image_loaders: + # just override, don't actually do both even if user chose both + captions_model = "Salesforce/blip2-flan-t5-xl" + else: + captions_model = kwargs['captions_model'] + return ret, captions_model + + +invalid_key_msg = 'Invalid Access Key, request access key from sales@h2o.ai or jon.mckinney@h2o.ai' + +docs_ordering_types = ['best_first', 'best_near_prompt', 'reverse_ucurve_sort'] diff --git a/src/evaluate_params.py b/src/evaluate_params.py new file mode 100644 index 0000000000000000000000000000000000000000..6f69d3f1bb648ab07c63a286326e37edf483f9db --- /dev/null +++ b/src/evaluate_params.py @@ -0,0 +1,71 @@ +input_args_list = ['model_state', 'my_db_state', 'selection_docs_state', 'requests_state'] + +no_default_param_names = [ + 'instruction', + 'iinput', + 'context', + 'instruction_nochat', + 'iinput_nochat', +] + +gen_hyper0 = ['num_beams', + 'max_new_tokens', + 'min_new_tokens', + 'early_stopping', + 'max_time', + 'repetition_penalty', + 'num_return_sequences', + 'do_sample', + ] +gen_hyper = ['temperature', + 'top_p', + 'top_k'] + gen_hyper0 +reader_names = ['image_loaders', 'pdf_loaders', 'url_loaders', 'jq_schema'] + +eval_func_param_names = ['instruction', + 'iinput', + 'context', + 'stream_output', + 'prompt_type', + 'prompt_dict'] + \ + gen_hyper + \ + ['chat', + 'instruction_nochat', + 'iinput_nochat', + 'langchain_mode', + 'add_chat_history_to_context', + 'langchain_action', + 'langchain_agents', + 'top_k_docs', + 'chunk', + 'chunk_size', + 'document_subset', + 'document_choice', + 'pre_prompt_query', + 'prompt_query', + 'pre_prompt_summary', + 'prompt_summary', + 'system_prompt', + ] + \ + reader_names + \ + ['visible_models', + 'h2ogpt_key', + 'add_search_to_context', + 'chat_conversation', + 'text_context_list', + 'docs_ordering_type', + 'min_max_new_tokens', + ] + +# form evaluate defaults for submit_nochat_api +eval_func_param_names_defaults = eval_func_param_names.copy() +for k in no_default_param_names: + if k in eval_func_param_names_defaults: + eval_func_param_names_defaults.remove(k) + +eval_extra_columns = ['prompt', 'response', 'score'] + +# override default_kwargs if user_kwargs None for args evaluate() uses that are not just in model_state +# ensure prompt_type consistent with prep_bot(), so nochat API works same way +# see how default_kwargs is set in gradio_runner.py +key_overrides = ['prompt_type', 'prompt_dict'] diff --git a/src/gen.py b/src/gen.py new file mode 100644 index 0000000000000000000000000000000000000000..d8602e7b0a56920a4afb7b4ac9c73e7449216729 --- /dev/null +++ b/src/gen.py @@ -0,0 +1,3831 @@ +import ast +import copy +import functools +import inspect +import queue +import sys +import os +import time +import traceback +import typing +import warnings +from datetime import datetime +import requests +from requests import ConnectTimeout, JSONDecodeError +from urllib3.exceptions import ConnectTimeoutError, MaxRetryError, ConnectionError +from requests.exceptions import ConnectionError as ConnectionError2 +from requests.exceptions import ReadTimeout as ReadTimeout2 + +if os.path.dirname(os.path.abspath(__file__)) not in sys.path: + sys.path.append(os.path.dirname(os.path.abspath(__file__))) + +os.environ['HF_HUB_DISABLE_TELEMETRY'] = '1' +os.environ['BITSANDBYTES_NOWELCOME'] = '1' +warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated') + +# more is not useful typically, don't let these go beyond limits and eat up resources +max_cores = max(1, os.cpu_count() // 2) +if os.getenv('NUMEXPR_MAX_THREADS') is None: + os.environ['NUMEXPR_MAX_THREADS'] = str(min(8, max_cores)) +if os.getenv('NUMEXPR_NUM_THREADS') is None: + os.environ['NUMEXPR_NUM_THREADS'] = str(min(8, max_cores)) +if os.getenv('OMP_NUM_THREADS') is None: + os.environ['OMP_NUM_THREADS'] = str(min(8, max_cores)) +if os.getenv('OPENBLAS_NUM_THREADS') is None: + os.environ['OPENBLAS_NUM_THREADS'] = str(min(8, max_cores)) +if os.getenv('DUCKDB_NUM_THREADS') is None: + os.environ['DUCKDB_NUM_THREADS'] = str(min(4, max_cores)) +if os.getenv('RAYON_RS_NUM_CPUS') is None: + os.environ['RAYON_RS_NUM_CPUS'] = str(min(8, max_cores)) +if os.getenv('RAYON_NUM_THREADS') is None: + os.environ['RAYON_NUM_THREADS'] = str(min(8, max_cores)) + +import numpy as np +from evaluate_params import eval_func_param_names, no_default_param_names, input_args_list +from enums import DocumentSubset, LangChainMode, no_lora_str, model_token_mapping, no_model_str, \ + LangChainAction, LangChainAgent, DocumentChoice, LangChainTypes, super_source_prefix, \ + super_source_postfix, t5_type, get_langchain_prompts, gr_to_lg, invalid_key_msg +from loaders import get_loaders +from utils import set_seed, clear_torch_cache, NullContext, wrapped_partial, EThread, get_githash, \ + import_matplotlib, get_device, makedirs, get_kwargs, start_faulthandler, get_hf_server, FakeTokenizer, \ + have_langchain, set_openai, cuda_vis_check, H2O_Fire, lg_to_gr, str_to_list, str_to_dict, get_token_count + +start_faulthandler() +import_matplotlib() + +SEED = 1236 +set_seed(SEED) + +from typing import Union + +import torch +from transformers import GenerationConfig, AutoModel, TextIteratorStreamer + +from prompter import Prompter, inv_prompt_type_to_model_lower, non_hf_types, PromptType, get_prompt, generate_prompt +from stopping import get_stopping + +langchain_actions = [x.value for x in list(LangChainAction)] + +langchain_agents_list = [x.value for x in list(LangChainAgent)] + + +def main( + load_8bit: bool = False, + load_4bit: bool = False, + low_bit_mode: int = 1, + load_half: bool = None, + load_gptq: str = '', + load_exllama: bool = False, + use_safetensors: bool = False, + revision: str = None, + use_gpu_id: bool = True, + base_model: str = '', + tokenizer_base_model: str = '', + lora_weights: str = "", + gpu_id: int = 0, + compile_model: bool = None, + use_cache: bool = None, + inference_server: str = "", + prompt_type: Union[int, str] = None, + prompt_dict: typing.Dict = None, + system_prompt: str = '', + + # llama and gpt4all settings + llamacpp_dict: typing.Dict = dict(n_gpu_layers=100, use_mlock=True, n_batch=1024, n_gqa=0), + model_path_llama: str = 'https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML/resolve/main/llama-2-7b-chat.ggmlv3.q8_0.bin', + # 'llama-2-7b-chat.ggmlv3.q8_0.bin', + model_name_gptj: str = 'ggml-gpt4all-j-v1.3-groovy.bin', + model_name_gpt4all_llama: str = 'ggml-wizardLM-7B.q4_2.bin', + model_name_exllama_if_no_config: str = 'TheBloke/Nous-Hermes-Llama2-GPTQ', + + model_lock: typing.List[typing.Dict[str, str]] = None, + model_lock_columns: int = None, + fail_if_cannot_connect: bool = False, + + # input to generation + temperature: float = None, + top_p: float = None, + top_k: int = None, + num_beams: int = None, + repetition_penalty: float = None, + num_return_sequences: int = None, + do_sample: bool = None, + max_new_tokens: int = None, + min_new_tokens: int = None, + early_stopping: Union[bool, str] = None, + max_time: float = None, + + memory_restriction_level: int = None, + debug: bool = False, + save_dir: str = None, + share: bool = False, + local_files_only: bool = False, + resume_download: bool = True, + use_auth_token: Union[str, bool] = False, + trust_remote_code: Union[str, bool] = True, + rope_scaling: dict = None, + max_seq_len: int = None, + offload_folder: str = "offline_folder", + + src_lang: str = "English", + tgt_lang: str = "Russian", + + prepare_offline_level: int = 0, + cli: bool = False, + cli_loop: bool = True, + gradio: bool = True, + gradio_offline_level: int = 0, + server_name: str = "0.0.0.0", + root_path: str = "", + chat: bool = True, + chat_conversation: typing.List[typing.Tuple[str, str]] = None, + text_context_list: typing.List[str] = None, + stream_output: bool = True, + async_output: bool = True, + num_async: int = 3, + show_examples: bool = None, + verbose: bool = False, + h2ocolors: bool = True, + dark: bool = False, # light tends to be best + height: int = 600, + show_lora: bool = True, + show_llama: bool = True, + show_gpt4all: bool = False, + login_mode_if_model0: bool = False, + block_gradio_exit: bool = True, + concurrency_count: int = 1, + api_open: bool = False, + allow_api: bool = True, + input_lines: int = 1, + gradio_size: str = None, + show_copy_button: bool = True, + large_file_count_mode: bool = False, + pre_load_embedding_model: bool = True, + + auth: Union[typing.List[typing.Tuple[str, str]], str] = None, + auth_filename: str = None, + auth_access: str = 'open', + auth_freeze: bool = False, + auth_message: str = None, + guest_name: str = "guest", + enforce_h2ogpt_api_key: bool = None, + h2ogpt_api_keys: Union[list, str] = [], + h2ogpt_key: str = None, + + max_max_time=None, + max_max_new_tokens=None, + + visible_models: list = None, + visible_visible_models: bool = True, + visible_submit_buttons: bool = True, + visible_side_bar: bool = True, + visible_doc_track: bool = True, + visible_chat_tab: bool = True, + visible_doc_selection_tab: bool = True, + visible_doc_view_tab: bool = True, + visible_chat_history_tab: bool = True, + visible_expert_tab: bool = True, + visible_models_tab: bool = True, + visible_system_tab: bool = True, + visible_tos_tab: bool = False, + visible_login_tab: bool = True, + visible_hosts_tab: bool = False, + chat_tables: bool = False, + visible_h2ogpt_header: bool = True, + max_raw_chunks: int = None, + + sanitize_user_prompt: bool = False, + sanitize_bot_response: bool = False, + + extra_model_options: typing.List[str] = [], + extra_lora_options: typing.List[str] = [], + extra_server_options: typing.List[str] = [], + + score_model: str = 'auto', + + eval_filename: str = None, + eval_prompts_only_num: int = 0, + eval_prompts_only_seed: int = 1234, + eval_as_output: bool = False, + + langchain_mode: str = None, + user_path: str = None, + langchain_modes: list = [LangChainMode.USER_DATA.value, LangChainMode.MY_DATA.value, LangChainMode.LLM.value, + LangChainMode.DISABLED.value], + langchain_mode_paths: dict = {LangChainMode.USER_DATA.value: None}, + langchain_mode_types: dict = {LangChainMode.USER_DATA.value: LangChainTypes.SHARED.value}, + detect_user_path_changes_every_query: bool = False, + + langchain_action: str = LangChainAction.QUERY.value, + langchain_agents: list = [], + force_langchain_evaluate: bool = False, + + visible_langchain_actions: list = [LangChainAction.QUERY.value, LangChainAction.SUMMARIZE_MAP.value], + visible_langchain_agents: list = langchain_agents_list.copy(), + + document_subset: str = DocumentSubset.Relevant.name, + document_choice: list = [DocumentChoice.ALL.value], + + use_llm_if_no_docs: bool = True, + load_db_if_exists: bool = True, + keep_sources_in_context: bool = False, + db_type: str = 'chroma', + use_openai_embedding: bool = False, + use_openai_model: bool = False, + hf_embedding_model: str = None, + migrate_embedding_model: str = False, + auto_migrate_db: bool = False, + cut_distance: float = 1.64, + answer_with_sources: bool = True, + append_sources_to_answer: bool = True, + show_accordions: bool = True, + top_k_docs_max_show: int = 10, + show_link_in_sources: bool = True, + pre_prompt_query: str = None, + prompt_query: str = None, + pre_prompt_summary: str = None, + prompt_summary: str = None, + add_chat_history_to_context: bool = True, + add_search_to_context: bool = False, + context: str = '', + iinput: str = '', + allow_upload_to_user_data: bool = True, + reload_langchain_state: bool = True, + allow_upload_to_my_data: bool = True, + enable_url_upload: bool = True, + enable_text_upload: bool = True, + enable_sources_list: bool = True, + chunk: bool = True, + chunk_size: int = 512, + top_k_docs: int = None, + docs_ordering_type: str = 'reverse_ucurve_sort', + min_max_new_tokens=256, + auto_reduce_chunks: bool = True, + max_chunks: int = 100, + headsize: int = 50, + n_jobs: int = -1, + + # urls + use_unstructured=True, + use_playwright=False, + use_selenium=False, + + # pdfs + use_pymupdf='auto', + use_unstructured_pdf='auto', + use_pypdf='auto', + enable_pdf_ocr='auto', + enable_pdf_doctr='auto', + try_pdf_as_html='auto', + + # images + enable_ocr=False, + enable_doctr=False, + enable_pix2struct=False, + enable_captions=True, + + pre_load_caption_model: bool = False, + caption_gpu: bool = True, + captions_model: str = "Salesforce/blip-image-captioning-base", + doctr_gpu: bool = True, + + # json + jq_schema='.[]', + + max_quality: bool = False, + + enable_heap_analytics: bool = True, + heap_app_id: str = "1680123994", +): + """ + + :param load_8bit: load model in 8-bit using bitsandbytes + :param load_4bit: load model in 4-bit using bitsandbytes + :param low_bit_mode: 0: no quantization config 1: change compute 2: nf4 3: double quant 4: 2 and 3 + See: https://huggingface.co/docs/transformers/main_classes/quantization + If using older bitsandbytes or transformers, 0 is required + :param load_half: load model in float16 (None means auto, which means True unless t5 based model) + otherwise specify bool + :param load_gptq: to load model with GPTQ, put model_basename here, e.g. gptq_model-4bit--1g + :param load_exllama: whether to use exllama (only applicable to LLaMa1/2 models with 16-bit or GPTQ + :param use_safetensors: to use safetensors version (assumes file/HF points to safe tensors version) + :param revision: Which HF revision to use + :param use_gpu_id: whether to control devices with gpu_id. If False, then spread across GPUs + :param base_model: model HF-type name. If use --base_model to preload model, cannot unload in gradio in models tab + :param tokenizer_base_model: tokenizer HF-type name. Usually not required, inferred from base_model. + :param lora_weights: LORA weights path/HF link + :param gpu_id: if use_gpu_id, then use gpu_id for cuda device ID, or auto mode if gpu_id != -1 + :param compile_model Whether to compile the model + :param use_cache: Whether to use caching in model (some models fail when multiple threads use) + :param inference_server: Consume base_model as type of model at this address + Address can be text-generation-server hosting that base_model + e.g. python generate.py --inference_server="http://192.168.1.46:6112" --base_model=h2oai/h2ogpt-oasst1-512-12b + + Or Address can be "openai_chat" or "openai" for OpenAI API + Or Address can be "openai_azure_chat" or "openai_azure" for Azure OpenAI API + e.g. python generate.py --inference_server="openai_chat" --base_model=gpt-3.5-turbo + e.g. python generate.py --inference_server="openai" --base_model=text-davinci-003 + e.g. python generate.py --inference_server="openai_azure_chat::::" --base_model=gpt-3.5-turbo + e.g. python generate.py --inference_server="openai_azure::::" --base_model=text-davinci-003 + Optionals (Replace with None or just leave empty but keep :) + of some deployment name + : e.g. ".openai.azure.com" for some without https:// + of some api, e.g. 2023-05-15 + e.g. 0613 + + Or Address can be for vLLM: + Use: "vllm:IP:port" for OpenAI-compliant vLLM endpoint + Note: vllm_chat not supported by vLLM project. + + Or Address can be replicate: + Use: + --inference_server=replicate: will use a Replicate server, requiring a Replicate key. + e.g. looks like "a16z-infra/llama13b-v2-chat:df7690f1994d94e96ad9d568eac121aecf50684a0b0963b25a41cc40061269e5" + + Or Address can be for AWS SageMaker: + Use: "sagemaker_chat:" for chat models that AWS sets up as dialog + Use: "sagemaker:" for foundation models that AWS only text as inputs + + :param prompt_type: type of prompt, usually matched to fine-tuned model or plain for foundational model + :param prompt_dict: If prompt_type=custom, then expects (some) items returned by get_prompt(..., return_dict=True) + :param system_prompt: Universal system prompt to use if model supports, like LLaMa2, regardless of prompt_type definition. + Useful for langchain case to control behavior, or OpenAI and Replicate. + If None, 'None', or 'auto', then for LLaMa or other models that internally have system_prompt, will use default for each model + If '', then no system prompt (no empty template given to model either, just no system part added at all) + If some string not in ['None', 'auto'], then use that as system prompt + Default is '', no system_prompt, because often it hurts performance/accuracy + + :param llamacpp_dict: + n_gpu_layers: for llama.cpp based models, number of GPU layers to offload (default is all by using large value) + use_mlock: when using `llama.cpp` based CPU models, for computers with low system RAM or slow CPUs, recommended False + n_batch: Can make smaller to 128 for slower low-memory CPU systems + n_gqa: Required to be 8 for LLaMa 70B + ... etc. anything that could be passed to llama.cpp or GPT4All models + e.g. python generate.py --base_model='llama' --prompt_type=llama2 --score_model=None --langchain_mode='UserData' --user_path=user_path --llamacpp_dict="{'n_gpu_layers':25,'n_batch':128}" + :param model_path_llama: model path or URL (for auto-download) + :param model_name_gptj: model path or URL (for auto-download) + :param model_name_gpt4all_llama: model path or URL (for auto-download) + :param model_name_exllama_if_no_config: exllama model's full path for model, tokenizer, generator for use when no HuggingFace config + + :param model_lock: Lock models to specific combinations, for ease of use and extending to many models + Only used if gradio = True + List of dicts, each dict has base_model, tokenizer_base_model, lora_weights, inference_server, prompt_type, and prompt_dict + If all models have same prompt_type, and prompt_dict, can still specify that once in CLI outside model_lock as default for dict + Can specify model_lock instead of those items on CLI + As with CLI itself, base_model can infer prompt_type and prompt_dict if in prompter.py. + Also, tokenizer_base_model and lora_weights are optional. + Also, inference_server is optional if loading model from local system. + All models provided will automatically appear in compare model mode + Model loading-unloading and related choices will be disabled. Model/lora/server adding will be disabled + :param model_lock_columns: How many columns to show if locking models (and so showing all at once) + If None, then defaults to up to 3 + if -1, then all goes into 1 row + Maximum value is 4 due to non-dynamic gradio rendering elements + :param fail_if_cannot_connect: if doing model locking (e.g. with many models), fail if True. Otherwise ignore. + Useful when many endpoints and want to just see what works, but still have to wait for timeout. + + :param temperature: generation temperature + :param top_p: generation top_p + :param top_k: generation top_k + :param num_beams: generation number of beams + :param repetition_penalty: generation repetition penalty + :param num_return_sequences: generation number of sequences (1 forced for chat) + :param do_sample: generation sample + :param max_new_tokens: generation max new tokens + :param min_new_tokens: generation min tokens + :param early_stopping: generation early stopping + :param max_time: maximum time to allow for generation + :param memory_restriction_level: 0 = no restriction to tokens or model, 1 = some restrictions on token 2 = HF like restriction 3 = very low memory case + :param debug: enable debug mode + :param save_dir: directory chat data is saved to + :param share: whether to share the gradio app with sharable URL + :param local_files_only: whether to only use local files instead of doing to HF for models + :param resume_download: whether to resume downloads from HF for models + :param use_auth_token: whether to use HF auth token (requires CLI did huggingface-cli login before) + :param trust_remote_code: whether to use trust any code needed for HF model + :param rope_scaling: + For HF transformers model: scaling for rope-based models, e.g. --rope_scaling="{'type':'dynamic', 'factor':4}" + For exllama model: --rope_scaling="{'alpha_value':4}" . This automatically scales max_seq_len for exllama + :param max_seq_len: Manually set maximum sequence length for the LLM + :param offload_folder: path for spilling model onto disk + :param src_lang: source languages to include if doing translation (None = all) + :param tgt_lang: target languages to include if doing translation (None = all) + + :param prepare_offline_level: + Whether to just prepare for offline use, do not go into cli, eval, or gradio run modes + 0 : no prep + 1: prepare just h2oGPT with exact same setup as passed to CLI and ensure all artifacts for h2oGPT alone added to ~/.cache/ + 2: prepare h2oGPT + all inference servers so h2oGPT+inference servers can use the ~/.cache/ + :param cli: whether to use CLI (non-gradio) interface. + :param cli_loop: whether to loop for CLI (False usually only for testing) + :param gradio: whether to enable gradio, or to enable benchmark mode + :param gradio_offline_level: > 0, then change fonts so full offline + == 1 means backend won't need internet for fonts, but front-end UI might if font not cached + == 2 means backend and frontend don't need internet to download any fonts. + Note: Some things always disabled include HF telemetry, gradio telemetry, chromadb posthog that involve uploading. + This option further disables google fonts for downloading, which is less intrusive than uploading, + but still required in air-gapped case. The fonts don't look as nice as google fonts, but ensure full offline behavior. + Also set --share=False to avoid sharing a gradio live link. + :param server_name: IP to use. In linux 0.0.0.0 is good choice so exposed to outside host, else for only local use 127.0.0.1. + For windows/MAC 0.0.0.0 or 127.0.0.1 will work, but may need to specify actual LAN IP address for other LAN clients to see. + :param root_path: The root path (or "mount point") of the application, + if it's not served from the root ("/") of the domain. Often used when the application is behind a reverse proxy + that forwards requests to the application. For example, if the application is served at "https://example.com/myapp", + the `root_path` should be set to "/myapp". + :param chat: whether to enable chat mode with chat history + :param chat_conversation: list of tuples of (human, bot) conversation pre-appended to existing chat when using instruct/chat models + Requires also add_chat_history_to_context = True + It does *not* require chat=True, so works with nochat_api etc. + :param text_context_list: List of strings to add to context for non-database version of document Q/A for faster handling via API etc. + Forces LangChain code path and uses as many entries in list as possible given max_seq_len, with first assumed to be most relevant and to go near prompt. + :param stream_output: whether to stream output + :param async_output: Whether to do asyncio handling + For summarization + Applicable to HF TGI server + Only if stream_output=False in CLI, UI, or API + :param num_async: Number of simultaneously allowed asyncio calls to make for async_output + Too many will overload inference server, too few will be too slow + :param show_examples: whether to show clickable examples in gradio + :param verbose: whether to show verbose prints + :param h2ocolors: whether to use H2O.ai theme + :param dark: whether to use dark mode for UI by default (still controlled in UI) + :param height: height of chat window + :param show_lora: whether to show LORA options in UI (expert so can be hard to understand) + :param show_llama: whether to show LLaMa.cpp/GPT4All options in UI (only likely useful if have weak GPUs) + :param show_gpt4all: whether to show GPT4All models in UI (not often useful, llama.cpp models best) + :param login_mode_if_model0: set to True to load --base_model after client logs in, to be able to free GPU memory when model is swapped + :param block_gradio_exit: whether to block gradio exit (used for testing) + :param concurrency_count: gradio concurrency count (1 is optimal for LLMs) + :param api_open: If False, don't let API calls skip gradio queue + :param allow_api: whether to allow API calls at all to gradio server + :param input_lines: how many input lines to show for chat box (>1 forces shift-enter for submit, else enter is submit) + :param gradio_size: Overall size of text and spaces: "xsmall", "small", "medium", "large". + Small useful for many chatbots in model_lock mode + :param show_copy_button: Whether to show copy button for chatbots + :param large_file_count_mode: Whether to force manual update to UI of drop-downs, good idea if millions of chunks or documents + :param pre_load_embedding_model: Whether to preload embedding model for shared use across DBs and users (multi-thread safe only) + + :param auth: gradio auth for launcher in form [(user1, pass1), (user2, pass2), ...] + e.g. --auth=[('jon','password')] with no spaces + e.g. --auth="[('jon', 'password)())(')]" so any special characters can be used + e.g. --auth=auth.json to specify persisted state file with name auth.json (auth_filename then not required) + e.g. --auth='' will use default auth.json as file name for persisted state file (auth_filename then not required) + e.g. --auth=None will use no auth, but still keep track of auth state, just not from logins + :param auth_filename: + Set auth filename, used only if --auth= was passed list of user/passwords + :param auth_access: + 'open': Allow new users to be added + 'closed': Stick to existing users + :param auth_freeze: whether freeze authentication based upon current file, no longer update file + :param auth_message: Message to show if having users login, fixed if passed, else dynamic internally + :param guest_name: guess name if using auth and have open access. + If '', then no guest allowed even if open access, then all databases for each user always persisted + :param enforce_h2ogpt_api_key: Whether to enforce h2oGPT token usage for API + :param h2ogpt_api_keys: list of tokens allowed for API access or file accessed on demand for json of list of keys + :param h2ogpt_key: E.g. can be set when accessing gradio h2oGPT server from local gradio h2oGPT server that acts as client to that inference server + + :param max_max_time: Maximum max_time for gradio slider + :param max_max_new_tokens: Maximum max_new_tokens for gradio slider + :param min_max_new_tokens: Minimum of max_new_tokens, when auto-scaling down to handle more docs/prompt, but still let generation have some tokens + + :param visible_models: Which models in model_lock list to show by default + Takes integers of position in model_lock (model_states) list or strings of base_model names + Ignored if model_lock not used + For nochat API, this is single item within a list for model by name or by index in model_lock + If None, then just use first model in model_lock list + If model_lock not set, use model selected by CLI --base_model etc. + + :param visible_visible_models: Whether visible models drop-down is visible in UI + :param visible_submit_buttons: whether submit buttons are visible when UI first comes up + :param visible_side_bar: whether left side bar is visible when UI first comes up + :param visible_doc_track: whether left side bar's document tracking is visible when UI first comes up + :param visible_chat_tab: "" for chat tab + :param visible_doc_selection_tab: "" for doc selection tab + :param visible_doc_view_tab: "" for doc view tab + :param visible_chat_history_tab: "" for chat history tab + :param visible_expert_tab: "" for expert tab + :param visible_models_tab: "" for models tab + :param visible_system_tab: "" for system tab + :param visible_tos_tab: "" for ToS tab + :param visible_login_tab: "" for Login tab + :param visible_hosts_tab: "" for hosts tab + :param chat_tables: Just show Chat as block without tab (useful if want only chat view) + :param visible_h2ogpt_header: Whether github stars, URL, logo, and QR code are visible + :param max_raw_chunks: Maximum number of chunks to show in UI when asking for raw DB text from documents/collection + + :param sanitize_user_prompt: whether to remove profanity from user input (slows down input processing) + Requires optional packages: + pip install alt-profanity-check==1.2.2 better-profanity==0.7.0 + :param sanitize_bot_response: whether to remove profanity and repeat lines from bot output (about 2x slower generation for long streaming cases due to better_profanity being slow) + :param extra_model_options: extra models to show in list in gradio + :param extra_lora_options: extra LORA to show in list in gradio + :param extra_server_options: extra servers to show in list in gradio + :param score_model: which model to score responses + None: no response scoring + 'auto': auto mode, '' (no model) for CPU or 1 GPU, 'OpenAssistant/reward-model-deberta-v3-large-v2' for >=2 GPUs, + because on CPU takes too much compute just for scoring response + :param eval_filename: json file to use for evaluation, if None is sharegpt + :param eval_prompts_only_num: for no gradio benchmark, if using eval_filename prompts for eval instead of examples + :param eval_prompts_only_seed: for no gradio benchmark, seed for eval_filename sampling + :param eval_as_output: for no gradio benchmark, whether to test eval_filename output itself + + :param langchain_mode: Data source to include. Choose "UserData" to only consume files from make_db.py. + None: auto mode, check if langchain package exists, at least do LLM if so, else Disabled + If not passed, then chosen to be first langchain_modes, else langchain_mode->Disabled is set if no langchain_modes either + WARNING: wiki_full requires extra data processing via read_wiki_full.py and requires really good workstation to generate db, unless already present. + :param user_path: user path to glob from to generate db for vector search, for 'UserData' langchain mode. + If already have db, any new/changed files are added automatically if path set, does not have to be same path used for prior db sources + :param langchain_modes: dbs to generate at launch to be ready for LLM + Apart from additional user-defined collections, can include ['wiki', 'wiki_full', 'UserData', 'MyData', 'github h2oGPT', 'DriverlessAI docs'] + But wiki_full is expensive and requires preparation + To allow personal space only live in session, add 'MyData' to list + Default: If only want to consume local files, e.g. prepared by make_db.py, only include ['UserData'] + If have own user modes, need to add these here or add in UI. + :param langchain_mode_paths: dict of langchain_mode keys and disk path values to use for source of documents + E.g. "{'UserData2': 'userpath2'}" + A disk path be None, e.g. --langchain_mode_paths="{'UserData2': None}" even if existing DB, to avoid new documents being added from that path, source links that are on disk still work. + If `--user_path` was passed, that path is used for 'UserData' instead of the value in this dict + :param langchain_mode_types: dict of langchain_mode keys and database types + E.g. python generate.py --base_model=llama --langchain_modes=['TestData'] --langchain_mode_types="{'TestData':'shared'}" + The type is attempted to be inferred if directory already exists, then don't have to pass this + :param detect_user_path_changes_every_query: whether to detect if any files changed or added every similarity search (by file hashes). + Expensive for large number of files, so not done by default. By default only detect changes during db loading. + + :param langchain_action: Mode langchain operations in on documents. + Query: Make query of document(s) + Summarize or Summarize_map_reduce: Summarize document(s) via map_reduce + Summarize_all: Summarize document(s) using entire document at once + Summarize_refine: Summarize document(s) using entire document, and try to refine before returning summary + :param langchain_agents: Which agents to use + 'search': Use Web Search as context for LLM response, e.g. SERP if have SERPAPI_API_KEY in env + :param force_langchain_evaluate: Whether to force langchain LLM use even if not doing langchain, mostly for testing. + + :param visible_langchain_actions: Which actions to allow + :param visible_langchain_agents: Which agents to allow + + :param document_subset: Default document choice when taking subset of collection + :param document_choice: Chosen document(s) by internal name, 'All' means use all docs + + :param use_llm_if_no_docs: Whether to use LLM even if no documents, when langchain_mode=UserData or MyData or custom + :param load_db_if_exists: Whether to load chroma db if exists or re-generate db + :param keep_sources_in_context: Whether to keep url sources in context, not helpful usually + :param db_type: 'faiss' for in-memory + 'chroma' (for chroma >= 0.4) + 'chroma_old' (for chroma < 0.4) -- recommended for large collections + 'weaviate' for persisted on disk + :param use_openai_embedding: Whether to use OpenAI embeddings for vector db + :param use_openai_model: Whether to use OpenAI model for use with vector db + :param hf_embedding_model: Which HF embedding model to use for vector db + Default is instructor-large with 768 parameters per embedding if have GPUs, else all-MiniLM-L6-v2 if no GPUs + Can also choose simpler model with 384 parameters per embedding: "sentence-transformers/all-MiniLM-L6-v2" + Can also choose even better embedding with 1024 parameters: 'hkunlp/instructor-xl' + We support automatically changing of embeddings for chroma, with a backup of db made if this is done + :param migrate_embedding_model: whether to use hf_embedding_model embedding even if database already had an embedding set. + used to migrate all embeddings to a new one, but will take time to re-embed. + Default (False) is to use the prior embedding for existing databases, and only use hf_embedding_model for new databases + If had old database without embedding saved, then hf_embedding_model is also used. + :param auto_migrate_db: whether to automatically migrate any chroma<0.4 database from duckdb -> sqlite version + :param cut_distance: Distance to cut off references with larger distances when showing references. + 1.64 is good to avoid dropping references for all-MiniLM-L6-v2, but instructor-large will always show excessive references. + For all-MiniLM-L6-v2, a value of 1.5 can push out even more references, or a large value of 100 can avoid any loss of references. + :param answer_with_sources: Whether to determine (and return) sources + :param append_sources_to_answer: Whether to place source information in chat response (ignored by LLM). Always disabled for API. + :param show_accordions: whether to show accordion for document references in chatbot UI + :param top_k_docs_max_show: Max number of docs to show in UI for sources + If web search is enabled, then this is modified to be max(top_k_docs_max_show, number of links used in search) + :param show_link_in_sources: Whether to show URL link to source document in references + :param pre_prompt_query: prompt before documents to query, if None then use internal defaults + :param prompt_query: prompt after documents to query, if None then use internal defaults + :param pre_prompt_summary: prompt before documents to summarize, if None then use internal defaults + :param prompt_summary: prompt after documents to summarize, if None then use internal defaults + For summarize, normal to have empty query (nothing added in ask anything in UI or empty string in API) + If pass query, template is "Focusing on %s, %s" % (query, prompt_summary) + If pass query and iinput, template is "Focusing on %s, %s, %s" % (query, iinput, prompt_summary) + :param add_chat_history_to_context: Include chat context when performing action + Not supported yet for openai_chat when using document collection instead of LLM + Also not supported when using CLI mode + :param add_search_to_context: Include web search in context as augmented prompt + :param context: Default context to use (for system pre-context in gradio UI) + context comes before chat_conversation and any document Q/A from text_context_list + :param iinput: Default input for instruction-based prompts + :param allow_upload_to_user_data: Whether to allow file uploads to update shared vector db (UserData or custom user dbs) + Ensure pass user_path for the files uploaded to be moved to this location for linking. + :param reload_langchain_state: Whether to reload langchain_modes.pkl file that contains any new user collections. + :param allow_upload_to_my_data: Whether to allow file uploads to update personal vector db + :param enable_url_upload: Whether to allow upload from URL + :param enable_text_upload: Whether to allow upload of text + :param enable_sources_list: Whether to allow list (or download for non-shared db) of list of sources for chosen db + :param chunk: Whether to chunk data (True unless know data is already optimally chunked) + :param chunk_size: Size of chunks, with typically top-4 passed to LLM, so needs to be in context length + :param top_k_docs: For langchain_action query: number of chunks to give LLM + -1 : auto-fills context up to max_seq_len + For langchain_action summarize: number of document parts, like pages for PDF. + There's no such thing as chunks for summarization. + -1 : auto-fills context up to max_seq_len + :param docs_ordering_type: + Type of ordering of docs. + 'best_first': Order by score so score is worst match near prompt + 'best_near_prompt' or 'reverse_sort' : reverse docs order so most relevant is closest to question. + Best choice for sufficiently smart model, and truncation occurs for oldest context, so best then too. + But smaller 6_9 models fail to use newest context and can get stuck on old information. + '' or None (i.e. default) or 'reverse_ucurve_sort' : Sort so most relevant is either near start or near end + Best to avoid "lost in middle" as well as avoid hallucinating off starting content that LLM focuses on alot. + :param auto_reduce_chunks: Whether to automatically reduce top_k_docs to fit context given prompt + :param max_chunks: If top_k_docs=-1, maximum number of chunks to allow + :param headsize: Maximum number of characters for head of document document for UI to show + :param n_jobs: Number of processors to use when consuming documents (-1 = all, is default) + + :param use_unstructured: Enable unstructured URL loader + :param use_playwright: Enable PlayWright URL loader + :param use_selenium: Enable Selenium URL loader + + :param use_pymupdf: enable PyMUPDF 'auto' means use first, use others if they are 'auto' if no result + :param use_unstructured_pdf: enable Unstructured PDF loader, 'auto' means use if pymupdf fails to get doc result + :param use_pypdf: enable PyPDF loader 'auto' means use if unstructured fails to get doc result + :param enable_pdf_ocr: 'auto' means only use OCR if normal text extraction fails. Useful for pure image-based PDFs with text. + if enable_pdf_doctr == 'on' then don't do. + 'on' means always do OCR as additional parsing of same documents + 'off' means don't do OCR (e.g. because it's slow even if 'auto' only would trigger if nothing else worked) + :param enable_pdf_doctr: Whether to support doctr on pdfs, 'auto' means use do if failed to get doc result so far + :param try_pdf_as_html: Try "PDF" as if HTML file, in case web link has .pdf extension but really is just HTML + + :param enable_ocr: Whether to support OCR on images + :param enable_doctr: Whether to support doctr on images (using OCR better than enable_ocr=True) + :param enable_pix2struct: Whether to support pix2struct on images for captions + :param enable_captions: Whether to support captions using BLIP for image files as documents, + then preloads that model if pre_load_caption_model=True + + :param pre_load_caption_model: Whether to preload caption model, or load after forking parallel doc loader + parallel loading disabled if preload and have images, to prevent deadlocking on cuda context + Recommended if using larger caption model + :param captions_model: Which model to use for captions. + captions_model: str = "Salesforce/blip-image-captioning-base", # continue capable + captions_model: str = "Salesforce/blip2-flan-t5-xl", # question/answer capable, 16GB state + captions_model: str = "Salesforce/blip2-flan-t5-xxl", # question/answer capable, 60GB state + Note: opt-based blip2 are not permissive license due to opt and Meta license restrictions + Disabled for CPU since BLIP requires CUDA + :param caption_gpu: If support caption, then use GPU if exists + + :param doctr_gpu: If support doctr, then use GPU if exists + + :param jq_schema: control json loader + By default '.[]' ingests everything in brute-force way, but better to match your schema + See: https://python.langchain.com/docs/modules/data_connection/document_loaders/json#using-jsonloader + + :param max_quality: Choose maximum quality ingestion with all available parsers + Pro: Catches document when some default parsers would fail + Pro: Enables DocTR that has much better OCR than Tesseract + Con: Fills DB with results from all parsers, so similarity search gives redundant results + + :param enable_heap_analytics: Toggle telemetry. + :param heap_app_id: App ID for Heap, change to your ID. + :return: + """ + if base_model is None: + base_model = '' + if tokenizer_base_model is None: + tokenizer_base_model = '' + if lora_weights is None: + lora_weights = '' + if inference_server is None: + inference_server = '' + + # listen to env if set + model_lock = os.getenv('model_lock', str(model_lock)) + model_lock = ast.literal_eval(model_lock) + + chat_conversation = str_to_list(chat_conversation) + text_context_list = str_to_list(text_context_list) + + llamacpp_dict = str_to_dict(llamacpp_dict) + # add others to single dict + llamacpp_dict['model_path_llama'] = model_path_llama + llamacpp_dict['model_name_gptj'] = model_name_gptj + llamacpp_dict['model_name_gpt4all_llama'] = model_name_gpt4all_llama + llamacpp_dict['model_name_exllama_if_no_config'] = model_name_exllama_if_no_config + # if user overrides but doesn't set these: + if 'n_batch' not in llamacpp_dict: + llamacpp_dict['n_batch'] = 128 + if 'n_gpu_layers' not in llamacpp_dict: + llamacpp_dict['n_gpu_layers'] = 100 + if 'n_gqa' not in llamacpp_dict: + llamacpp_dict['n_gqa'] = 0 + + if os.environ.get('SERPAPI_API_KEY') is None and LangChainAgent.SEARCH.value in visible_langchain_agents: + visible_langchain_agents.remove(LangChainAgent.SEARCH.value) + + if model_lock: + assert gradio, "model_lock only supported for gradio=True" + assert not cli, "model_lock only supported for cli=False" + assert not (not cli and not gradio), "model_lock only supported for eval (cli=gradio=False)" + assert not base_model, "Don't specify model_lock and base_model" + assert not tokenizer_base_model, "Don't specify model_lock and tokenizer_base_model" + assert not lora_weights, "Don't specify model_lock and lora_weights" + assert not inference_server, "Don't specify model_lock and inference_server" + # assert not prompt_type, "Don't specify model_lock and prompt_type" + # assert not prompt_dict, "Don't specify model_lock and prompt_dict" + + n_jobs = int(os.getenv('n_jobs', str(n_jobs))) + is_hf = bool(int(os.getenv("HUGGINGFACE_SPACES", '0'))) + is_gpth2oai = bool(int(os.getenv("GPT_H2O_AI", '0'))) + is_public = is_hf or is_gpth2oai # multi-user case with fixed model and disclaimer + if is_public: + visible_tos_tab = visible_hosts_tab = True + if enforce_h2ogpt_api_key is None: + enforce_h2ogpt_api_key = True + else: + if enforce_h2ogpt_api_key is None: + enforce_h2ogpt_api_key = False + if isinstance(h2ogpt_api_keys, str) and not os.path.isfile(h2ogpt_api_keys): + h2ogpt_api_keys = str_to_list(h2ogpt_api_keys) + if memory_restriction_level is None: + memory_restriction_level = 2 if is_hf else 0 # 2 assumes run on 24GB consumer GPU + else: + assert 0 <= memory_restriction_level <= 3, "Bad memory_restriction_level=%s" % memory_restriction_level + if n_jobs == -1: + # if -1, assume hypercores, don't use, force user to pass n_jobs to be specific if not standard cores + n_jobs = max(1, os.cpu_count() // 2) + if is_public and os.getenv('n_jobs') is None: + n_jobs = min(n_jobs, max(1, min(os.cpu_count() // 2, 8))) + admin_pass = os.getenv("ADMIN_PASS") + # will sometimes appear in UI or sometimes actual generation, but maybe better than empty result + # but becomes unrecoverable sometimes if raise, so just be silent for now + raise_generate_gpu_exceptions = True + + rope_scaling = str_to_dict(rope_scaling) + + if isinstance(auth, str): + if auth.strip().startswith('['): + auth = str_to_list(auth) + if isinstance(auth, str) and auth: + auth_filename = auth + if not auth_filename: + auth_filename = "auth.json" + assert isinstance(auth, (str, list, tuple, type(None))), "Unknown type %s for auth=%s" % (type(auth), auth) + + # allow set token directly + use_auth_token = os.environ.get("HUGGING_FACE_HUB_TOKEN", use_auth_token) + allow_upload_to_user_data = bool( + int(os.environ.get("allow_upload_to_user_data", str(int(allow_upload_to_user_data))))) + allow_upload_to_my_data = bool(int(os.environ.get("allow_upload_to_my_data", str(int(allow_upload_to_my_data))))) + height = int(os.environ.get("HEIGHT", height)) + h2ocolors = bool(int(os.getenv('h2ocolors', h2ocolors))) + + # allow enabling langchain via ENV + # FIRST PLACE where LangChain referenced, but no imports related to it + langchain_modes = ast.literal_eval(os.environ.get("langchain_modes", str(langchain_modes))) + if not isinstance(langchain_modes, list): + langchain_modes = [] + # always allow DISABLED + if LangChainMode.DISABLED.value not in langchain_modes: + langchain_modes.append(LangChainMode.DISABLED.value) + if not have_langchain: + # only allow disabled, not even LLM that is langchain related + langchain_mode = LangChainMode.DISABLED.value + langchain_modes = [langchain_mode] + + # update + langchain_mode_paths = str_to_dict(langchain_mode_paths) + langchain_mode_types = str_to_dict(langchain_mode_types) + for lmode in [LangChainMode.GITHUB_H2OGPT.value, + LangChainMode.H2O_DAI_DOCS.value, + LangChainMode.WIKI.value, + LangChainMode.WIKI_FULL.value, + ]: + if lmode not in langchain_mode_types: + langchain_mode_types[lmode] = 'shared' + if lmode not in langchain_mode_paths: + langchain_mode_types[lmode] = '' + if user_path: + user_path = makedirs(user_path, use_base=True) + langchain_mode_paths['UserData'] = user_path + langchain_mode_paths['UserData'] = LangChainTypes.SHARED.value + + if is_public: + allow_upload_to_user_data = False + if LangChainMode.USER_DATA.value in langchain_modes: + langchain_modes.remove(LangChainMode.USER_DATA.value) + if max_raw_chunks is None: + max_raw_chunks = 30 if is_public else 1000000 + + # in-place, for non-scratch dbs + if allow_upload_to_user_data: + # always listen to CLI-passed user_path if passed + if user_path: + langchain_mode_paths['UserData'] = user_path + + assert langchain_action in langchain_actions, "Invalid langchain_action %s not in %s" % ( + langchain_action, langchain_actions) + assert len( + set(langchain_agents).difference(langchain_agents_list)) == 0, "Invalid langchain_agents %s" % langchain_agents + + # auto-set langchain_mode + langchain_mode = os.environ.get("LANGCHAIN_MODE", langchain_mode) + if have_langchain and langchain_mode is None: + # start in chat mode, in case just want to chat and don't want to get "No documents to query" by default. + if LangChainMode.LLM.value in langchain_modes: + langchain_mode = LangChainMode.LLM.value + elif len(langchain_modes) >= 1: + # infer even if don't pass which langchain_mode, just langchain_modes. + langchain_mode = langchain_modes[0] + if allow_upload_to_user_data and not is_public and langchain_mode_paths['UserData']: + if verbose: + print("Auto set langchain_mode=%s. Could use UserData instead." % langchain_mode, flush=True) + elif allow_upload_to_my_data: + if verbose: + print("Auto set langchain_mode=%s. Could use MyData instead." + " To allow UserData to pull files from disk," + " set user_path or langchain_mode_paths, and ensure allow_upload_to_user_data=True" % langchain_mode, + flush=True) + else: + raise RuntimeError("Please pass --langchain_mode= out of %s" % langchain_modes) + if not have_langchain and langchain_mode not in [None, LangChainMode.DISABLED.value, LangChainMode.LLM.value]: + raise RuntimeError("Asked for LangChain mode but langchain python package cannot be found.") + if langchain_mode is None: + # if not set yet, disable + langchain_mode = LangChainMode.DISABLED.value + print("Auto set langchain_mode=%s Have langchain package: %s" % (langchain_mode, have_langchain), flush=True) + # go ahead and add + if langchain_mode not in langchain_modes: + langchain_modes.append(langchain_mode) + + if is_public: + allow_upload_to_user_data = False + input_lines = 1 # ensure set, for ease of use + temperature = 0.2 if temperature is None else temperature + top_p = 0.85 if top_p is None else top_p + top_k = 70 if top_k is None else top_k + if is_hf: + do_sample = True if do_sample is None else do_sample + top_k_docs = 3 if top_k_docs is None else top_k_docs + else: + # by default don't sample, too chatty + do_sample = False if do_sample is None else do_sample + top_k_docs = 4 if top_k_docs is None else top_k_docs + + if memory_restriction_level == 2: + if not base_model and not inference_server and not model_lock: + base_model = 'h2oai/h2ogpt-oasst1-512-12b' + # don't set load_8bit if passed base_model, doesn't always work so can't just override + load_8bit = True + load_4bit = False # FIXME - consider using 4-bit instead of 8-bit + elif not inference_server: + top_k_docs = 10 if top_k_docs is None else top_k_docs + if memory_restriction_level >= 2: + load_8bit = True + load_4bit = False # FIXME - consider using 4-bit instead of 8-bit + if hf_embedding_model is None: + hf_embedding_model = "sentence-transformers/all-MiniLM-L6-v2" + top_k_docs = 3 if top_k_docs is None else top_k_docs + if top_k_docs is None: + top_k_docs = 3 + if is_public: + if not max_time: + max_time = 60 * 2 + if not max_max_time: + max_max_time = max_time + if not max_new_tokens: + max_new_tokens = 256 + if not max_max_new_tokens: + max_max_new_tokens = 512 + else: + if not max_max_time: + max_max_time = 60 * 20 + if not max_max_new_tokens: + max_max_new_tokens = 1024 + if is_hf: + # must override share if in spaces + share = False + if not max_time: + max_time = 60 * 1 + if not max_max_time: + max_max_time = max_time + # HF accounted for later in get_max_max_new_tokens() + save_dir = os.getenv('SAVE_DIR', save_dir) + save_dir = makedirs(save_dir, exist_ok=True, tmp_ok=True, use_base=True) + score_model = os.getenv('SCORE_MODEL', score_model) + if str(score_model) == 'None': + score_model = '' + concurrency_count = int(os.getenv('CONCURRENCY_COUNT', concurrency_count)) + api_open = bool(int(os.getenv('API_OPEN', str(int(api_open))))) + allow_api = bool(int(os.getenv('ALLOW_API', str(int(allow_api))))) + + n_gpus = torch.cuda.device_count() if torch.cuda.is_available() else 0 + n_gpus, gpu_ids = cuda_vis_check(n_gpus) + + if load_half is None and t5_type(base_model): + load_half = False + print("load_half=%s auto-set for %s to avoid bad generation" % (load_half, base_model), flush=True) + + if n_gpus == 0 or get_device() == "mps": + # No CUDA GPUs usable + + if get_device() != "mps": + print("No GPUs detected", flush=True) + + enable_captions = False + gpu_id = None + load_8bit = False + load_4bit = False + low_bit_mode = 1 + if load_half is None: + # wouldn't work if specified True, but respect + load_half = False + load_gptq = '' + load_exllama = False + use_gpu_id = False + if get_device() == "cuda": + torch.backends.cudnn.benchmark = True + torch.backends.cudnn.enabled = False + torch.set_default_dtype(torch.float32) + if is_public and not inference_server and not model_lock: + # 12B uses ~94GB + # 6.9B uses ~47GB + base_model = 'h2oai/h2ogpt-oig-oasst1-512-6_9b' if not base_model else base_model + if hf_embedding_model is None: + # if no GPUs, use simpler embedding model to avoid cost in time + hf_embedding_model = "sentence-transformers/all-MiniLM-L6-v2" + if score_model == 'auto': + score_model = '' + else: + if load_half is None: + load_half = True + # CUDA GPUs visible + if score_model == 'auto': + if n_gpus >= 2: + # will by default place scoring model on last GPU + score_model = 'OpenAssistant/reward-model-deberta-v3-large-v2' + else: + score_model = '' + if hf_embedding_model is None: + # if still None, then set default + hf_embedding_model = 'hkunlp/instructor-large' + + # get defaults + if base_model: + model_lower = base_model.lower() + elif model_lock: + # have 0th model be thought of as normal model + assert len(model_lock) > 0 and model_lock[0]['base_model'] + model_lower = model_lock[0]['base_model'].lower() + else: + model_lower = '' + if not gradio: + # force, else not single response like want to look at + stream_output = False + # else prompt removal can mess up output + chat = False + # hard-coded defaults + first_para = False + text_limit = None + + if compile_model is None: + # too avoid noisy CLI + compile_model = not cli + + if offload_folder: + offload_folder = makedirs(offload_folder, exist_ok=True, tmp_ok=True, use_base=True) + + # defaults + caption_loader = None + doctr_loader = None + pix2struct_loader = None + + image_loaders_options0, image_loaders_options, \ + pdf_loaders_options0, pdf_loaders_options, \ + url_loaders_options0, url_loaders_options = lg_to_gr(**locals()) + jq_schema0 = jq_schema + # transcribe + image_loaders = image_loaders_options0 + pdf_loaders = pdf_loaders_options0 + url_loaders = url_loaders_options0 + + placeholder_instruction, placeholder_input, \ + stream_output, show_examples, \ + prompt_type, prompt_dict, \ + temperature, top_p, top_k, num_beams, \ + max_new_tokens, min_new_tokens, early_stopping, max_time, \ + repetition_penalty, num_return_sequences, \ + do_sample, \ + src_lang, tgt_lang, \ + examples, \ + task_info = \ + get_generate_params(model_lower, + chat, + stream_output, show_examples, + prompt_type, prompt_dict, + system_prompt, + pre_prompt_query, prompt_query, + pre_prompt_summary, prompt_summary, + temperature, top_p, top_k, num_beams, + max_new_tokens, min_new_tokens, early_stopping, max_time, + repetition_penalty, num_return_sequences, + do_sample, + top_k_docs, + chunk, + chunk_size, + image_loaders, + pdf_loaders, + url_loaders, + jq_schema, + docs_ordering_type, + min_max_new_tokens, + verbose, + ) + + git_hash = get_githash() if is_public or os.getenv('GET_GITHASH') else "GET_GITHASH" + locals_dict = locals() + locals_print = '\n'.join(['%s: %s' % (k, v) for k, v in locals_dict.items()]) + if verbose: + print(f"Generating model with params:\n{locals_print}", flush=True) + print("Command: %s\nHash: %s" % (str(' '.join(sys.argv)), git_hash), flush=True) + + if langchain_mode != LangChainMode.DISABLED.value: + # SECOND PLACE where LangChain referenced, but all imports are kept local so not required + from gpt_langchain import prep_langchain, get_some_dbs_from_hf, get_persist_directory + if is_hf: + get_some_dbs_from_hf() + dbs = {} + for langchain_mode1 in langchain_modes: + langchain_type = langchain_mode_types.get(langchain_mode1, LangChainTypes.EITHER.value) + if langchain_type == LangChainTypes.PERSONAL.value: + # shouldn't prepare per-user databases here + continue + persist_directory1, langchain_type = get_persist_directory(langchain_mode1, langchain_type=langchain_type) + langchain_mode_types[langchain_mode1] = langchain_type + if langchain_type == LangChainTypes.PERSONAL.value: + # shouldn't prepare per-user databases here + continue + try: + db = prep_langchain(persist_directory1, + load_db_if_exists, + db_type, use_openai_embedding, + langchain_mode1, langchain_mode_paths, langchain_mode_types, + hf_embedding_model, + migrate_embedding_model, + auto_migrate_db, + kwargs_make_db=locals(), + verbose=verbose) + finally: + # in case updated embeddings or created new embeddings + clear_torch_cache() + dbs[langchain_mode1] = db + # remove None db's so can just rely upon k in dbs for if hav db + dbs = {k: v for k, v in dbs.items() if v is not None} + else: + dbs = {} + # import control + if os.environ.get("TEST_LANGCHAIN_IMPORT"): + assert 'gpt_langchain' not in sys.modules, "Dev bug, import of langchain when should not have" + assert 'langchain' not in sys.modules, "Dev bug, import of langchain when should not have" + + other_model_state_defaults = dict(load_8bit=load_8bit, load_4bit=load_4bit, low_bit_mode=low_bit_mode, + load_half=load_half, + load_gptq=load_gptq, load_exllama=load_exllama, use_safetensors=use_safetensors, + revision=revision, use_gpu_id=use_gpu_id, gpu_id=gpu_id, + compile_model=compile_model, + use_cache=use_cache, + llamacpp_dict=llamacpp_dict, model_path_llama=model_path_llama, + model_name_gptj=model_name_gptj, + model_name_gpt4all_llama=model_name_gpt4all_llama, + model_name_exllama_if_no_config=model_name_exllama_if_no_config, + ) + model_state_none = dict(model=None, tokenizer=None, device=None, + base_model=None, tokenizer_base_model=None, lora_weights=None, + inference_server=None, prompt_type=None, prompt_dict=None, + visible_models=None, h2ogpt_key=None, + ) + model_state_none.update(other_model_state_defaults) + my_db_state0 = {LangChainMode.MY_DATA.value: [None, None, None]} + selection_docs_state0 = dict(langchain_modes=langchain_modes, + langchain_mode_paths=langchain_mode_paths, + langchain_mode_types=langchain_mode_types) + selection_docs_state = copy.deepcopy(selection_docs_state0) + + if cli or not gradio: + # initial state for query prompt + model_name = base_model + pre_prompt_query, prompt_query, pre_prompt_summary, prompt_summary = \ + get_langchain_prompts(pre_prompt_query, prompt_query, + pre_prompt_summary, prompt_summary, + model_name, inference_server, + model_path_llama) + + if cli: + from cli import run_cli + return run_cli(**get_kwargs(run_cli, exclude_names=['model_state0'], **locals())) + elif not gradio: + from eval import run_eval + return run_eval(**get_kwargs(run_eval, exclude_names=['model_state0'], **locals())) + elif gradio or prepare_offline_level > 0: + # imported here so don't require gradio to run generate + from gradio_runner import go_gradio + + # get default model + model_states = [] + model_list = [dict(base_model=base_model, tokenizer_base_model=tokenizer_base_model, lora_weights=lora_weights, + inference_server=inference_server, prompt_type=prompt_type, prompt_dict=prompt_dict, + visible_models=None, h2ogpt_key=None)] + model_list[0].update(other_model_state_defaults) + # FIXME: hyper per model, not about model loading + # for k in gen_hyper: + # model_list[k] = locals()[k] + + model_list0 = copy.deepcopy(model_list) # just strings, safe to deepcopy + model_state0 = model_state_none.copy() + assert len(model_state_none) == len(model_state0) + if model_lock: + model_list = model_lock + # do reverse, so first is default base_model etc., so some logic works in go_gradio() more easily + for model_dict in reversed(model_list): + # handle defaults user didn't have to pass + # special defaults, ignore defaults for these if not specifically set, replace with '' + model_dict['base_model'] = model_dict.get('base_model', '') + model_dict['tokenizer_base_model'] = model_dict.get('tokenizer_base_model', '') + model_dict['lora_weights'] = model_dict.get('lora_weights', '') + model_dict['inference_server'] = model_dict.get('inference_server', '') + if prepare_offline_level >= 2: + if 'openai' not in model_dict['inference_server'] and 'replicate' not in model_dict['inference_server']: + # assume want locally, but OpenAI and replicate are never local for model part + model_dict['inference_server'] = '' + prompt_type_infer = not model_dict.get('prompt_type') + model_dict['prompt_type'] = model_dict.get('prompt_type', + model_list0[0]['prompt_type']) # don't use mutated value + # rest of generic defaults + for k in model_list0[0]: + if k not in model_dict: + model_dict[k] = model_list0[0][k] + + # begin prompt adjustments + # get query prompt for (say) last base model if using model lock + pre_prompt_query1, prompt_query1, pre_prompt_summary1, prompt_summary1 = ( + get_langchain_prompts(pre_prompt_query, prompt_query, + pre_prompt_summary, prompt_summary, + model_dict['base_model'], + model_dict['inference_server'], + model_dict['model_path_llama'])) + # if mixed setup, choose non-empty so best models best + # FIXME: Make per model dict passed through to evaluate + pre_prompt_query = pre_prompt_query or pre_prompt_query1 + prompt_query = prompt_query or prompt_query1 + pre_prompt_summary = pre_prompt_summary or pre_prompt_summary1 + prompt_summary = prompt_summary or prompt_summary1 + + # try to infer, ignore empty initial state leading to get_generate_params -> 'plain' + if prompt_type_infer: + model_lower1 = model_dict['base_model'].lower() + if model_lower1 in inv_prompt_type_to_model_lower: + model_dict['prompt_type'] = inv_prompt_type_to_model_lower[model_lower1] + model_dict['prompt_dict'], error0 = get_prompt(model_dict['prompt_type'], '', + chat=False, context='', reduced=False, + making_context=False, + return_dict=True, + system_prompt=system_prompt) + else: + model_dict['prompt_dict'] = prompt_dict + else: + model_dict['prompt_dict'] = prompt_dict + model_dict['prompt_dict'] = model_dict.get('prompt_dict', model_dict['prompt_dict']) + # end prompt adjustments + all_kwargs = locals().copy() + all_kwargs.update(model_dict) + if model_dict['base_model'] and not login_mode_if_model0: + model0, tokenizer0, device = get_model(reward_type=False, + **get_kwargs(get_model, exclude_names=['reward_type'], + **all_kwargs)) + else: + # if empty model, then don't load anything, just get gradio up + model0, tokenizer0, device = None, None, None + if model0 is None: + if fail_if_cannot_connect: + raise RuntimeError("Could not connect, see logs") + # skip + if isinstance(model_lock, list): + model_lock.remove(model_dict) + continue + model_state_trial = dict(model=model0, tokenizer=tokenizer0, device=device) + model_state_trial.update(model_dict) + diff_keys = set(list(model_state_none.keys())).symmetric_difference(model_state_trial.keys()) + assert len(model_state_none) == len(model_state_trial), diff_keys + print("Model %s" % model_dict, flush=True) + if model_lock: + # last in iteration will be first + model_states.insert(0, model_state_trial) + # fill model_state0 so go_gradio() easier, manage model_states separately + model_state0 = model_state_trial.copy() + else: + model_state0 = model_state_trial.copy() + assert len(model_state_none) == len(model_state0) + + visible_models = str_to_list(visible_models, allow_none=True) # None means first model + all_models = [x.get('base_model', xi) for xi, x in enumerate(model_states)] + visible_models_state0 = [x.get('base_model', xi) for xi, x in enumerate(model_states) if + visible_models is None or + x.get('base_model', xi) in visible_models or + xi in visible_models] + + # update to be consistent with what is passed from CLI and model chose + # do after go over all models if multi-model, so don't contaminate + # This is just so UI shows reasonable correct value, not 2048 dummy value + if len(model_states) >= 1: + max_seq_len = model_states[0]['tokenizer'].model_max_length + + # get score model + all_kwargs = locals().copy() + smodel, stokenizer, sdevice = get_score_model(reward_type=True, + **get_kwargs(get_score_model, exclude_names=['reward_type'], + **all_kwargs)) + score_model_state0 = dict(model=smodel, tokenizer=stokenizer, device=sdevice, + base_model=score_model, tokenizer_base_model='', lora_weights='', + inference_server='', prompt_type='', prompt_dict='', + visible_models=None, h2ogpt_key=None) + + if enable_captions: + if pre_load_caption_model: + from image_captions import H2OImageCaptionLoader + caption_loader = H2OImageCaptionLoader(caption_gpu=caption_gpu).load_model() + else: + caption_loader = 'gpu' if n_gpus > 0 and caption_gpu else 'cpu' + else: + caption_loader = False + + if pre_load_embedding_model and \ + langchain_mode != LangChainMode.DISABLED.value and \ + not use_openai_embedding: + from src.gpt_langchain import get_embedding + hf_embedding_model = dict(name=hf_embedding_model, + model=get_embedding(use_openai_embedding, hf_embedding_model=hf_embedding_model, + preload=True)) + if enable_doctr or enable_pdf_ocr in [True, 'auto', 'on']: + doctr_loader = 'gpu' if n_gpus > 0 and doctr_gpu else 'cpu' + else: + doctr_loader = False + + # assume gradio needs everything + go_gradio(**locals()) + + +def get_config(base_model, + use_auth_token=False, + trust_remote_code=True, + offload_folder=None, + revision=None, + rope_scaling=None, + triton_attn=False, + long_sequence=True, + return_model=False, + raise_exception=False, + max_seq_len=None, + verbose=False, + ): + from accelerate import init_empty_weights + with init_empty_weights(): + from transformers import AutoConfig + try: + config = AutoConfig.from_pretrained(base_model, use_auth_token=use_auth_token, + trust_remote_code=trust_remote_code, + offload_folder=offload_folder, + revision=revision, + rope_scaling=rope_scaling if rope_scaling else None) + except OSError as e: + if raise_exception: + raise + if 'not a local folder and is not a valid model identifier listed on' in str( + e) or '404 Client Error' in str(e) or "couldn't connect" in str(e): + # e.g. llama, gpjt, etc. + # e.g. HF TGI but not model on HF or private etc. + if max_seq_len is None and base_model.lower() in non_hf_types: + print("Could not determine --max_seq_len, setting to 2048. Pass if not correct", flush=True) + max_seq_len = 2048 + # HF TGI server only should really require prompt_type, not HF model state + return None, None, max_seq_len + else: + raise + if triton_attn and 'mpt-' in base_model.lower(): + config.attn_config['attn_impl'] = 'triton' + if long_sequence: + if 'mpt-7b-storywriter' in base_model.lower(): + config.update({"max_seq_len": 83968}) + if 'mosaicml/mpt-7b-chat' in base_model.lower(): + config.update({"max_seq_len": 4096}) + if 'mpt-30b' in base_model.lower(): + config.update({"max_seq_len": 2 * 8192}) + if return_model and \ + issubclass(config.__class__, tuple(AutoModel._model_mapping.keys())): + model = AutoModel.from_config( + config, + trust_remote_code=trust_remote_code, + ) + else: + # can't infer + model = None + if 'falcon' in base_model.lower(): + config.use_cache = False + + # allow override + if max_seq_len is not None: + print("Overriding max_seq_len -> %d" % max_seq_len, flush=True) + else: + if hasattr(config, 'max_seq_len'): + max_seq_len = int(config.max_seq_len) + elif hasattr(config, 'max_position_embeddings') and isinstance(config.max_position_embeddings, int): + # help automatically limit inputs to generate + max_seq_len = config.max_position_embeddings + if verbose: + print("Used max_position_embeddings=%s as base model (pre-rope) max_seq_len." + " If not desired, pass --max_seq_len and set to some integer value." % config.max_position_embeddings, + flush=True) + elif hasattr(config, 'n_ctx'): + # e.g. gpt2 + max_seq_len = int(config.n_ctx) + else: + print("Could not determine --max_seq_len, setting to 2048. Pass if not correct", flush=True) + max_seq_len = 2048 + # FIXME: + # raise RuntimeError("Could not determine max_seq_len," + # " please pass --max_seq_len and set to some value, e.g. 2048.") + + if rope_scaling: + if rope_scaling.get('factor'): + # HF transformers + max_seq_len *= rope_scaling.get('factor') + elif rope_scaling.get('alpha_value'): + # exllama + # Note: exllama's own tokenizer has this set correctly in loaders.py, this config will be unused + max_seq_len *= rope_scaling.get('alpha_value') + print("Automatically setting max_seq_len=%d for RoPE scaling" % max_seq_len, flush=True) + + return config, model, max_seq_len + + +def get_non_lora_model(base_model, model_loader, load_half, + load_gptq, + load_exllama, + use_safetensors, + revision, + model_kwargs, reward_type, + config, model, + gpu_id=0, + ): + """ + Ensure model gets on correct device + """ + + if model is not None: + # NOTE: Can specify max_memory={0: max_mem, 1: max_mem}, to shard model + # NOTE: Some models require avoiding sharding some layers, + # then would pass no_split_module_classes and give list of those layers. + from accelerate import infer_auto_device_map + device_map = infer_auto_device_map( + model, + dtype=torch.float16 if load_half else torch.float32, + ) + if hasattr(model, 'model'): + device_map_model = infer_auto_device_map( + model.model, + dtype=torch.float16 if load_half else torch.float32, + ) + device_map.update(device_map_model) + else: + device_map = "auto" + + n_gpus = torch.cuda.device_count() if torch.cuda.is_available() else 0 + n_gpus, gpu_ids = cuda_vis_check(n_gpus) + + if n_gpus > 0: + if gpu_id >= 0: + # FIXME: If really distributes model, tend to get things like: ValueError: gpt_neox.embed_in.weight doesn't have any device set. + # So avoid for now, just put on first GPU, unless score_model, put on last + if reward_type: + device_map = {'': n_gpus - 1} + else: + device_map = {'': min(n_gpus - 1, gpu_id)} + if gpu_id == -1: + device_map = {'': 'cuda'} + else: + device_map = {'': 'cpu'} + model_kwargs['load_in_8bit'] = False + model_kwargs['load_in_4bit'] = False + print('device_map: %s' % device_map, flush=True) + + load_in_8bit = model_kwargs.get('load_in_8bit', False) + load_in_4bit = model_kwargs.get('load_in_4bit', False) + model_kwargs['device_map'] = device_map + model_kwargs['use_safetensors'] = use_safetensors + model_kwargs['revision'] = revision + pop_unused_model_kwargs(model_kwargs) + + if load_exllama: + model = model_loader + elif load_gptq: + if 'Llama-2-70B-chat-GPTQ' in base_model: + model_kwargs.update(dict(inject_fused_attention=False)) + model_kwargs.pop('torch_dtype', None) + model_kwargs.pop('device_map') + model = model_loader( + model_name_or_path=base_model, + model_basename=load_gptq, + **model_kwargs, + ) + elif load_in_8bit or load_in_4bit or not load_half: + model = model_loader( + base_model, + config=config, + **model_kwargs, + ) + else: + + model = model_loader( + base_model, + config=config, + **model_kwargs, + ) + if not getattr(model, "is_quantized", False): + model = model.half() + return model + + +def get_client_from_inference_server(inference_server, base_model=None, raise_connection_exception=False): + inference_server, headers = get_hf_server(inference_server) + # preload client since slow for gradio case especially + from gradio_utils.grclient import GradioClient + gr_client = None + hf_client = None + if headers is None: + try: + print("GR Client Begin: %s %s" % (inference_server, base_model), flush=True) + # first do sanity check if alive, else gradio client takes too long by default + requests.get(inference_server, timeout=int(os.getenv('REQUEST_TIMEOUT', '30'))) + gr_client = GradioClient(inference_server) + print("GR Client End: %s" % inference_server, flush=True) + except (OSError, ValueError) as e: + # Occurs when wrong endpoint and should have been HF client, so don't hard raise, just move to HF + gr_client = None + print("GR Client Failed %s %s: %s" % (inference_server, base_model, str(e)), flush=True) + except (ConnectTimeoutError, ConnectTimeout, MaxRetryError, ConnectionError, ConnectionError2, + JSONDecodeError, ReadTimeout2, KeyError) as e: + t, v, tb = sys.exc_info() + ex = ''.join(traceback.format_exception(t, v, tb)) + print("GR Client Failed %s %s: %s" % (inference_server, base_model, str(ex)), flush=True) + if raise_connection_exception: + raise + + if gr_client is None: + res = None + from text_generation import Client as HFClient + print("HF Client Begin: %s %s" % (inference_server, base_model)) + try: + hf_client = HFClient(inference_server, headers=headers, timeout=int(os.getenv('REQUEST_TIMEOUT', '30'))) + # quick check valid TGI endpoint + res = hf_client.generate('What?', max_new_tokens=1) + hf_client = HFClient(inference_server, headers=headers, timeout=300) + except (ConnectTimeoutError, ConnectTimeout, MaxRetryError, ConnectionError, ConnectionError2, + JSONDecodeError, ReadTimeout2, KeyError) as e: + hf_client = None + t, v, tb = sys.exc_info() + ex = ''.join(traceback.format_exception(t, v, tb)) + print("HF Client Failed %s %s: %s" % (inference_server, base_model, str(ex))) + if raise_connection_exception: + raise + print("HF Client End: %s %s : %s" % (inference_server, base_model, res)) + return inference_server, gr_client, hf_client + + +def get_model( + load_8bit: bool = False, + load_4bit: bool = False, + low_bit_mode: int = 1, + load_half: bool = True, + load_gptq: str = '', + load_exllama: bool = False, + use_safetensors: bool = False, + revision: str = None, + use_gpu_id: bool = True, + base_model: str = '', + inference_server: str = "", + tokenizer_base_model: str = '', + lora_weights: str = "", + gpu_id: int = 0, + n_jobs=None, + + reward_type: bool = None, + local_files_only: bool = False, + resume_download: bool = True, + use_auth_token: Union[str, bool] = False, + trust_remote_code: bool = True, + offload_folder: str = None, + rope_scaling: dict = None, + max_seq_len: int = None, + compile_model: bool = True, + llamacpp_dict=None, + + verbose: bool = False, +): + """ + + :param load_8bit: load model in 8-bit, not supported by all models + :param load_4bit: load model in 4-bit, not supported by all models + :param low_bit_mode: See gen.py + :param load_half: load model in 16-bit + :param load_gptq: GPTQ model_basename + :param load_exllama: whether to use exllama + :param use_safetensors: use safetensors file + :param revision: + :param use_gpu_id: Use torch infer of optimal placement of layers on devices (for non-lora case) + For non-LORA case, False will spread shards across multiple GPUs, but this can lead to cuda:x cuda:y mismatches + So it is not the default + :param base_model: name/path of base model + :param inference_server: whether base_model is hosted locally ('') or via http (url) + :param tokenizer_base_model: name/path of tokenizer + :param lora_weights: name/path + :param gpu_id: which GPU (0..n_gpus-1) or allow all GPUs if relevant (-1) + :param n_jobs: number of cores to use (e.g. for llama CPU model) + :param reward_type: reward type model for sequence classification + :param local_files_only: use local files instead of from HF + :param resume_download: resume downloads from HF + :param use_auth_token: assumes user did on CLI `huggingface-cli login` to access private repo + :param trust_remote_code: trust code needed by model + :param offload_folder: offload folder + :param rope_scaling: scaling for rope-based models, e.g. "{'type':'dynamic', 'factor':4}" + :param max_seq_len: override for maximum sequence length for model + :param max_seq_len: if set, use as max_seq_len for model + :param compile_model: whether to compile torch model + :param llamacpp_dict: dict of llama.cpp and GPT4All model options + :param verbose: + :return: + """ + print("Starting get_model: %s %s" % (base_model, inference_server), flush=True) + + triton_attn = False + long_sequence = True + config_kwargs = dict(use_auth_token=use_auth_token, + trust_remote_code=trust_remote_code, + offload_folder=offload_folder, + rope_scaling=rope_scaling, + triton_attn=triton_attn, + long_sequence=long_sequence, + revision=revision, + max_seq_len=max_seq_len, + verbose=verbose) + config, _, max_seq_len = get_config(base_model, **config_kwargs, raise_exception=False) + + if base_model in non_hf_types: + assert config is None, "Expected config None for %s" % base_model + + llama_type_from_config = 'llama' in str(config).lower() + llama_type_from_name = "llama" in base_model.lower() + llama_type = llama_type_from_config or llama_type_from_name + if "xgen" in base_model.lower() or 'llama2' in base_model.lower() or 'llama-2' in base_model.lower(): + llama_type = False + if llama_type: + if verbose: + print("Detected as llama type from" + " config (%s) or name (%s)" % (llama_type_from_config, llama_type_from_name), flush=True) + + model_name_exllama_if_no_config = '' if not llamacpp_dict else llamacpp_dict.get('model_name_exllama_if_no_config', + '') + model_loader, tokenizer_loader, conditional_type = ( + get_loaders(model_name=base_model, reward_type=reward_type, llama_type=llama_type, + load_gptq=load_gptq, load_exllama=load_exllama, config=config, + rope_scaling=rope_scaling, max_seq_len=max_seq_len, + model_name_exllama_if_no_config=model_name_exllama_if_no_config)) + + tokenizer_kwargs = dict(local_files_only=local_files_only, + resume_download=resume_download, + use_auth_token=use_auth_token, + trust_remote_code=trust_remote_code, + offload_folder=offload_folder, + revision=revision, + padding_side='left', + config=config, + ) + if not tokenizer_base_model: + tokenizer_base_model = base_model + + if load_exllama: + tokenizer = tokenizer_loader + elif config is not None and tokenizer_loader is not None and not isinstance(tokenizer_loader, str): + if load_exllama: + tokenizer = tokenizer_loader + else: + tokenizer = tokenizer_loader.from_pretrained(tokenizer_base_model, **tokenizer_kwargs) + # sets raw (no cushion) limit + # If using RoPE with scaling, then for non-exllama models (e.g. HF models), + # then config -> tokenizer will set model_max_length correctly + set_model_max_len(max_seq_len, tokenizer, verbose=False) + # if using fake tokenizer, not really accurate when lots of numbers, give a bit of buffer, else get: + # Generation Failed: Input validation error: `inputs` must have less than 2048 tokens. Given: 2233 + tokenizer.model_max_length = tokenizer.model_max_length - 50 + else: + tokenizer = None + + if isinstance(inference_server, str) and inference_server.startswith("http"): + inference_server, gr_client, hf_client = get_client_from_inference_server(inference_server, + base_model=base_model) + client = gr_client or hf_client + # Don't return None, None for model, tokenizer so triggers + if tokenizer is None: + # FIXME: Could use only tokenizer from llama etc. but hard to detatch from model, just use fake for now + if os.getenv("HARD_ASSERTS") and base_model not in non_hf_types: + raise RuntimeError("Unexpected tokenizer=None") + tokenizer = FakeTokenizer() + return client, tokenizer, 'http' + if isinstance(inference_server, str) and ( + inference_server.startswith('openai') or + inference_server.startswith('vllm') or + inference_server.startswith('replicate') or + inference_server.startswith('sagemaker') + ): + if inference_server.startswith('openai'): + assert os.getenv('OPENAI_API_KEY'), "Set environment for OPENAI_API_KEY" + # Don't return None, None for model, tokenizer so triggers + # include small token cushion + max_seq_len = model_token_mapping[base_model] + if inference_server.startswith('replicate'): + assert len(inference_server.split(':')) >= 3, "Expected replicate:model string, got %s" % inference_server + assert os.getenv('REPLICATE_API_TOKEN'), "Set environment for REPLICATE_API_TOKEN" + assert max_seq_len is not None, "Please pass --max_seq_len= for replicate models." + try: + import replicate as replicate_python + except ImportError: + raise ImportError( + "Could not import replicate python package. " + "Please install it with `pip install replicate`." + ) + if inference_server.startswith('sagemaker'): + assert len( + inference_server.split( + ':')) >= 3, "Expected sagemaker_chat::, got %s" % inference_server + assert os.getenv('AWS_ACCESS_KEY_ID'), "Set environment for AWS_ACCESS_KEY_ID" + assert os.getenv('AWS_SECRET_ACCESS_KEY'), "Set environment for AWS_SECRET_ACCESS_KEY" + # Don't return None, None for model, tokenizer so triggers + # include small token cushion + if inference_server.startswith('openai') or tokenizer is None: + # don't use fake (tiktoken) tokenizer for vLLM//replicate if know actual model with actual tokenizer + tokenizer = FakeTokenizer(model_max_length=max_seq_len - 50) + return inference_server, tokenizer, inference_server + assert not inference_server, "Malformed inference_server=%s" % inference_server + if base_model in non_hf_types: + from gpt4all_llm import get_model_tokenizer_gpt4all + model, tokenizer, device = get_model_tokenizer_gpt4all(base_model, n_jobs=n_jobs, + max_seq_len=max_seq_len, + llamacpp_dict=llamacpp_dict) + return model, tokenizer, device + if load_exllama: + return model_loader, tokenizer, 'cuda' + + # get local torch-HF model + return get_hf_model(load_8bit=load_8bit, + load_4bit=load_4bit, + low_bit_mode=low_bit_mode, + load_half=load_half, + load_gptq=load_gptq, + use_safetensors=use_safetensors, + revision=revision, + use_gpu_id=use_gpu_id, + base_model=base_model, + tokenizer_base_model=tokenizer_base_model, + lora_weights=lora_weights, + gpu_id=gpu_id, + + reward_type=reward_type, + local_files_only=local_files_only, + resume_download=resume_download, + use_auth_token=use_auth_token, + trust_remote_code=trust_remote_code, + offload_folder=offload_folder, + rope_scaling=rope_scaling, + compile_model=compile_model, + + llama_type=llama_type, + config_kwargs=config_kwargs, + tokenizer_kwargs=tokenizer_kwargs, + + verbose=verbose) + + +def get_hf_model(load_8bit: bool = False, + load_4bit: bool = False, + low_bit_mode: int = 1, + load_half: bool = True, + load_gptq: str = '', + use_safetensors: bool = False, + revision: str = None, + use_gpu_id: bool = True, + base_model: str = '', + tokenizer_base_model: str = '', + lora_weights: str = "", + gpu_id: int = 0, + + reward_type: bool = None, + local_files_only: bool = False, + resume_download: bool = True, + use_auth_token: Union[str, bool] = False, + trust_remote_code: bool = True, + offload_folder: str = None, + rope_scaling: dict = None, + compile_model: bool = True, + + llama_type: bool = False, + config_kwargs=None, + tokenizer_kwargs=None, + + verbose: bool = False, + ): + assert config_kwargs is not None + assert tokenizer_kwargs is not None + + load_exllama = False # Never should be in HF code for exllama + + if lora_weights is not None and lora_weights.strip(): + if verbose: + print("Get %s lora weights" % lora_weights, flush=True) + device = get_device() + + if 'gpt2' in base_model.lower(): + # RuntimeError: where expected condition to be a boolean tensor, but got a tensor with dtype Half + load_8bit = False + load_4bit = False + + assert base_model.strip(), ( + "Please choose a base model with --base_model (CLI) or load one from Models Tab (gradio)" + ) + + model_loader, tokenizer_loader, conditional_type = ( + get_loaders(model_name=base_model, reward_type=reward_type, llama_type=llama_type, + load_gptq=load_gptq, load_exllama=load_exllama)) + + config, _, max_seq_len = get_config(base_model, return_model=False, raise_exception=True, **config_kwargs) + + if tokenizer_loader is not None and not isinstance(tokenizer_loader, str): + if load_exllama: + tokenizer = tokenizer_loader + else: + tokenizer = tokenizer_loader.from_pretrained(tokenizer_base_model, + **tokenizer_kwargs) + else: + tokenizer = tokenizer_loader + + if isinstance(tokenizer, str): + # already a pipeline, tokenizer_loader is string for task + model = model_loader(tokenizer, + model=base_model, + device=0 if device == "cuda" else -1, + torch_dtype=torch.float16 if device == 'cuda' else torch.float32) + else: + assert device in ["cuda", "cpu", "mps"], "Unsupported device %s" % device + model_kwargs = dict(local_files_only=local_files_only, + torch_dtype=torch.float16 if device == 'cuda' else torch.float32, + resume_download=resume_download, + use_auth_token=use_auth_token, + trust_remote_code=trust_remote_code, + offload_folder=offload_folder, + revision=revision, + # rope_scaling=rope_scaling, # only put into config + ) + if 'mbart-' not in base_model.lower() and 'mpt-' not in base_model.lower(): + if use_gpu_id and gpu_id is not None and gpu_id >= 0 and device == 'cuda': + device_map = {"": gpu_id} + else: + device_map = "auto" + model_kwargs.update(dict(load_in_8bit=load_8bit, + load_in_4bit=load_4bit, + device_map=device_map, + )) + if 'mpt-' in base_model.lower() and gpu_id is not None and gpu_id >= 0: + # MPT doesn't support spreading over GPUs + model_kwargs.update(dict(device_map={"": gpu_id} if device == 'cuda' else "cpu")) + + if 'OpenAssistant/reward-model'.lower() in base_model.lower(): + # FIXME: could put on other GPUs + model_kwargs['device_map'] = {"": 0} if device == 'cuda' else {"": 'cpu'} + model_kwargs.pop('torch_dtype', None) + pop_unused_model_kwargs(model_kwargs) + + n_gpus = torch.cuda.device_count() if torch.cuda.is_available() else 0 + n_gpus, gpu_ids = cuda_vis_check(n_gpus) + if low_bit_mode == 1 and n_gpus != 0: + from transformers import BitsAndBytesConfig + model_kwargs['quantization_config'] = BitsAndBytesConfig(bnb_4bit_compute_dtype=torch.bfloat16, + load_in_4bit=load_4bit, + load_in_8bit=load_8bit, + ) + elif low_bit_mode == 2 and n_gpus != 0: + from transformers import BitsAndBytesConfig + model_kwargs['quantization_config'] = BitsAndBytesConfig(bnb_4bit_quant_type="nf4", + load_in_4bit=load_4bit, + load_in_8bit=load_8bit, + ) + elif low_bit_mode == 3 and n_gpus != 0: + from transformers import BitsAndBytesConfig + model_kwargs['quantization_config'] = BitsAndBytesConfig(bnb_4bit_use_double_quant=True, + load_in_4bit=load_4bit, + load_in_8bit=load_8bit, + ) + elif low_bit_mode == 4 and n_gpus != 0: + from transformers import BitsAndBytesConfig + model_kwargs['quantization_config'] = BitsAndBytesConfig(bnb_4bit_use_double_quant=True, + bnb_4bit_quant_type="nf4", + load_in_4bit=load_4bit, + load_in_8bit=load_8bit, + ) + + if not lora_weights: + # torch.device context uses twice memory for AutoGPTQ + context = NullContext if load_gptq else torch.device + with context(device): + + if use_gpu_id: + config, model, max_seq_len = get_config(base_model, + return_model=True, raise_exception=True, **config_kwargs) + model = get_non_lora_model(base_model, model_loader, load_half, load_gptq, + load_exllama, + use_safetensors, + revision, + model_kwargs, reward_type, + config, model, + gpu_id=gpu_id, + ) + else: + config, _, max_seq_len = get_config(base_model, **config_kwargs) + if load_half and not (load_8bit or load_4bit or load_gptq): + model = model_loader( + base_model, + config=config, + **model_kwargs) + if not getattr(model, "is_quantized", False): + model = model.half() + else: + model = model_loader( + base_model, + config=config, + **model_kwargs) + elif load_8bit or load_4bit: + config, _, max_seq_len = get_config(base_model, **config_kwargs) + model = model_loader( + base_model, + config=config, + **model_kwargs + ) + from peft import PeftModel # loads cuda, so avoid in global scope + model = PeftModel.from_pretrained( + model, + lora_weights, + torch_dtype=torch.float16 if device == 'cuda' else torch.float32, + local_files_only=local_files_only, + resume_download=resume_download, + use_auth_token=use_auth_token, + trust_remote_code=trust_remote_code, + offload_folder=offload_folder, + rope_scaling=rope_scaling, + revision=revision, + device_map={"": 0} if device == 'cuda' else {"": 'cpu'}, # seems to be required + ) + else: + with torch.device(device): + config, _, max_seq_len = get_config(base_model, raise_exception=True, **config_kwargs) + model = model_loader( + base_model, + config=config, + **model_kwargs + ) + from peft import PeftModel # loads cuda, so avoid in global scope + model = PeftModel.from_pretrained( + model, + lora_weights, + torch_dtype=torch.float16 if device == 'cuda' else torch.float32, + local_files_only=local_files_only, + resume_download=resume_download, + use_auth_token=use_auth_token, + trust_remote_code=trust_remote_code, + offload_folder=offload_folder, + rope_scaling=rope_scaling, + device_map="auto", + ) + if load_half and not load_gptq: + if not getattr(model, "is_quantized", False): + model = model.half() + + # unwind broken decapoda-research config + if llama_type: + model.config.pad_token_id = tokenizer.pad_token_id = 0 # unk + model.config.bos_token_id = 1 + model.config.eos_token_id = 2 + if 'gpt2' in base_model.lower(): + # add special tokens that otherwise all share the same id + tokenizer.add_special_tokens({'bos_token': '', + 'eos_token': '', + 'pad_token': ''}) + + if not isinstance(tokenizer, str): + model.eval() + if torch.__version__ >= "2" and sys.platform != "win32" and compile_model: + model = torch.compile(model) + + set_model_max_len(max_seq_len, tokenizer, verbose=False, reward_type=reward_type) + + # tell if conditional type + model.conditional_type = conditional_type + tokenizer.conditional_type = conditional_type + + return model, tokenizer, device + + +def set_model_max_len(max_seq_len, tokenizer, verbose=False, reward_type=False): + if reward_type: + # limit deberta, else uses too much memory and not worth response score + tokenizer.model_max_length = 512 + return + + tokenizer.model_max_length = int(max_seq_len) + if verbose: + print("model_max_length=%s" % tokenizer.model_max_length, flush=True) + # for bug in HF transformers + if tokenizer.model_max_length > 100000000: + tokenizer.model_max_length = 2048 + + +def pop_unused_model_kwargs(model_kwargs): + """ + in-place pop unused kwargs that are not dependency-upgrade friendly + no point passing in False, is default, and helps avoid needing to update requirements for new deps + :param model_kwargs: + :return: + """ + check_list = ['load_in_8bit', 'load_in_4bit'] + for k in check_list: + if k in model_kwargs and not model_kwargs[k]: + model_kwargs.pop(k) + + +def get_score_model(score_model: str = None, + load_8bit: bool = False, + load_4bit: bool = False, + low_bit_mode=1, + load_half: bool = True, + load_gptq: str = '', + load_exllama: bool = False, + use_gpu_id: bool = True, + base_model: str = '', + inference_server: str = '', + tokenizer_base_model: str = '', + lora_weights: str = "", + gpu_id: int = 0, + n_jobs=None, + + reward_type: bool = None, + local_files_only: bool = False, + resume_download: bool = True, + use_auth_token: Union[str, bool] = False, + trust_remote_code: bool = True, + offload_folder: str = None, + rope_scaling: dict = None, + compile_model: bool = True, + llamacpp_dict: typing.Dict = None, + + verbose: bool = False, + ): + if score_model is not None and score_model.strip(): + load_8bit = False + load_4bit = False + low_bit_mode = 1 + load_half = False + load_gptq = '' + load_exllama = False + use_safetensors = False + revision = None + base_model = score_model.strip() + tokenizer_base_model = '' + lora_weights = '' + inference_server = '' + llama_type = False + max_seq_len = None + compile_model = False + llamacpp_dict = {} + smodel, stokenizer, sdevice = get_model(reward_type=True, + **get_kwargs(get_model, exclude_names=['reward_type'], **locals())) + else: + smodel, stokenizer, sdevice = None, None, None + return smodel, stokenizer, sdevice + + +def evaluate_fake(*args, **kwargs): + yield dict(response=invalid_key_msg, sources='') + return + + +def evaluate( + model_state, + my_db_state, + selection_docs_state, + requests_state, + # START NOTE: Examples must have same order of parameters + instruction, + iinput, + context, + stream_output, + prompt_type, + prompt_dict, + temperature, + top_p, + top_k, + num_beams, + max_new_tokens, + min_new_tokens, + early_stopping, + max_time, + repetition_penalty, + num_return_sequences, + do_sample, + chat, + instruction_nochat, + iinput_nochat, + langchain_mode, + add_chat_history_to_context, + langchain_action, + langchain_agents, + top_k_docs, + chunk, + chunk_size, + document_subset, + document_choice, + pre_prompt_query, + prompt_query, + pre_prompt_summary, + prompt_summary, + system_prompt, + + image_loaders, + pdf_loaders, + url_loaders, + jq_schema, + visible_models, + h2ogpt_key, + add_search_to_context, + chat_conversation, + text_context_list, + docs_ordering_type, + min_max_new_tokens, + + # END NOTE: Examples must have same order of parameters + captions_model=None, + caption_loader=None, + doctr_loader=None, + pix2struct_loader=None, + async_output=None, + num_async=None, + src_lang=None, + tgt_lang=None, + debug=False, + concurrency_count=None, + save_dir=None, + sanitize_bot_response=False, + model_state0=None, + memory_restriction_level=None, + max_max_new_tokens=None, + is_public=None, + max_max_time=None, + raise_generate_gpu_exceptions=None, + lora_weights=None, + use_llm_if_no_docs=True, + load_db_if_exists=True, + dbs=None, + detect_user_path_changes_every_query=None, + use_openai_embedding=None, + use_openai_model=None, + hf_embedding_model=None, + migrate_embedding_model=None, + auto_migrate_db=None, + cut_distance=None, + db_type=None, + n_jobs=None, + first_para=None, + text_limit=None, + show_accordions=None, + top_k_docs_max_show=None, + show_link_in_sources=None, + verbose=False, + cli=False, + use_cache=None, + auto_reduce_chunks=None, + max_chunks=None, + headsize=None, + model_lock=None, + force_langchain_evaluate=None, + model_state_none=None, + load_exllama=None, + answer_with_sources=None, + append_sources_to_answer=None, + image_loaders_options0=None, + pdf_loaders_options0=None, + url_loaders_options0=None, + jq_schema0=None, + keep_sources_in_context=None, +): + # ensure passed these + assert concurrency_count is not None + assert memory_restriction_level is not None + assert raise_generate_gpu_exceptions is not None + assert use_openai_embedding is not None + assert use_openai_model is not None + assert hf_embedding_model is not None + assert migrate_embedding_model is not None + assert auto_migrate_db is not None + assert db_type is not None + assert top_k_docs is not None and isinstance(top_k_docs, int) + assert chunk is not None and isinstance(chunk, bool) + assert chunk_size is not None and isinstance(chunk_size, int) + assert n_jobs is not None + assert first_para is not None + assert isinstance(add_chat_history_to_context, bool) + assert isinstance(add_search_to_context, bool) + assert load_exllama is not None + # for lazy client (even chat client) + if image_loaders is None: + image_loaders = image_loaders_options0 + if pdf_loaders is None: + pdf_loaders = pdf_loaders_options0 + if url_loaders is None: + url_loaders = url_loaders_options0 + if jq_schema is None: + jq_schema = jq_schema0 + if isinstance(langchain_agents, str): + if langchain_agents.strip().startswith('['): + # already list, but as string + langchain_agents = str_to_list(langchain_agents) + else: + # just 1 item and make list + langchain_agents = [langchain_agents] + chat_conversation = str_to_list(chat_conversation) + text_context_list = str_to_list(text_context_list) + + langchain_modes = selection_docs_state['langchain_modes'] + langchain_mode_paths = selection_docs_state['langchain_mode_paths'] + langchain_mode_types = selection_docs_state['langchain_mode_types'] + + if debug: + locals_dict = locals().copy() + locals_dict.pop('model_state', None) + locals_dict.pop('model_state0', None) + locals_dict.pop('model_states', None) + print(locals_dict) + + no_model_msg = "Please choose a base model with --base_model (CLI) or load in Models Tab (gradio).\n" \ + "Then start New Conversation" + + if model_state is None: + model_state = model_state_none.copy() + if model_state0 is None: + # e.g. for no gradio case, set dummy value, else should be set + model_state0 = model_state_none.copy() + + # model_state['model] is only 'model' if should use model_state0 + # model could also be None + have_model_lock = model_lock is not None + have_fresh_model = model_state['model'] not in [None, 'model', no_model_str] + # for gradio UI control, expect model_state and model_state0 to match, so if have_model_lock=True, then should have_fresh_model=True + # but gradio API control will only use nochat api etc. and won't use fresh model, so can't assert in general + # if have_model_lock: + # assert have_fresh_model, "Expected model_state and model_state0 to match if have_model_lock" + have_cli_model = model_state0['model'] not in [None, 'model', no_model_str] + + if have_fresh_model: + # USE FRESH MODEL + if not have_model_lock: + # model_state0 is just one of model_state if model_lock, so don't nuke + # try to free-up original model (i.e. list was passed as reference) + if model_state0['model'] and hasattr(model_state0['model'], 'cpu'): + model_state0['model'].cpu() + model_state0['model'] = None + # try to free-up original tokenizer (i.e. list was passed as reference) + if model_state0['tokenizer']: + model_state0['tokenizer'] = None + clear_torch_cache() + chosen_model_state = model_state + elif have_cli_model: + # USE MODEL SETUP AT CLI + assert isinstance(model_state['model'], (type(None), str)) # expect no fresh model + chosen_model_state = model_state0 + else: + raise AssertionError(no_model_msg) + # get variables + model = chosen_model_state['model'] + tokenizer = chosen_model_state['tokenizer'] + device = chosen_model_state['device'] + base_model = chosen_model_state['base_model'] + tokenizer_base_model = chosen_model_state['tokenizer_base_model'] + lora_weights = chosen_model_state['lora_weights'] + inference_server = chosen_model_state['inference_server'] + visible_models = chosen_model_state['visible_models'] + # use overall key if have, so key for this gradio and any inner gradio + if chosen_model_state['h2ogpt_key'] is not None: + h2ogpt_key = chosen_model_state['h2ogpt_key'] + # prefer use input from API over model state + prompt_type = prompt_type or chosen_model_state['prompt_type'] + prompt_dict = prompt_dict or chosen_model_state['prompt_dict'] + + if base_model is None: + raise AssertionError(no_model_msg) + + assert base_model.strip(), no_model_msg + assert model, "Model is missing" + assert tokenizer, "Tokenizer is missing" + + # choose chat or non-chat mode + if not chat: + instruction = instruction_nochat + iinput = iinput_nochat + + # in some cases, like lean nochat API, don't want to force sending prompt_type, allow default choice + model_lower = base_model.lower() + if not prompt_type and model_lower in inv_prompt_type_to_model_lower and prompt_type != 'custom': + prompt_type = inv_prompt_type_to_model_lower[model_lower] + if verbose: + print("Auto-selecting prompt_type=%s for %s" % (prompt_type, model_lower), flush=True) + assert prompt_type is not None, "prompt_type was None" + + # Control generation hyperparameters + # adjust for bad inputs, e.g. in case also come from API that doesn't get constrained by gradio sliders + # below is for TGI server, not required for HF transformers + # limits are chosen similar to gradio_runner.py sliders/numbers + top_p = min(max(1e-3, top_p), 1.0 - 1e-3) + top_k = min(max(1, int(top_k)), 100) + temperature = min(max(0.01, temperature), 2.0) + # FIXME: https://github.com/h2oai/h2ogpt/issues/106 + num_beams = 1 if stream_output else num_beams # See max_beams in gradio_runner + max_max_new_tokens = get_max_max_new_tokens(chosen_model_state, + memory_restriction_level=memory_restriction_level, + max_new_tokens=max_new_tokens, + max_max_new_tokens=max_max_new_tokens) + if min_max_new_tokens is None: + # default for nochat api + min_max_new_tokens = 256 + if docs_ordering_type is None: + docs_ordering_type = 'reverse_ucurve_sort' + model_max_length = get_model_max_length(chosen_model_state) + max_new_tokens = min(max(1, int(max_new_tokens)), max_max_new_tokens) + min_new_tokens = min(max(0, int(min_new_tokens)), max_new_tokens) + max_time = min(max(0, max_time), max_max_time) + repetition_penalty = min(max(0.01, repetition_penalty), 3.0) + num_return_sequences = 1 if chat else min(max(1, int(num_return_sequences)), 10) + min_top_k_docs, max_top_k_docs, label_top_k_docs = get_minmax_top_k_docs(is_public) + # limit total tokens processed, e.g. for summarization, if public instance + if is_public: + total_tokens_for_docs = min(2 * model_max_length, 16384) + else: + total_tokens_for_docs = None + top_k_docs = min(max(min_top_k_docs, int(top_k_docs)), max_top_k_docs) + chunk_size = min(max(128, int(chunk_size)), 2048) + if not context: + context = '' + + # get prompter + prompter = Prompter(prompt_type, prompt_dict, debug=debug, chat=chat, stream_output=stream_output, + system_prompt=system_prompt) + + # THIRD PLACE where LangChain referenced, but imports only occur if enabled and have db to use + assert langchain_mode in langchain_modes, "Invalid langchain_mode %s not in %s" % (langchain_mode, langchain_modes) + assert langchain_action in langchain_actions, "Invalid langchain_action %s not in %s" % ( + langchain_action, langchain_actions) + assert len( + set(langchain_agents).difference(langchain_agents_list)) == 0, "Invalid langchain_agents %s" % langchain_agents + + # get db, but also fill db state so return already has my_db_state and dbs filled so faster next query + if langchain_mode != LangChainMode.DISABLED.value: + from src.gpt_langchain import get_any_db + db = get_any_db(my_db_state, langchain_mode, langchain_mode_paths, langchain_mode_types, + dbs=dbs, + load_db_if_exists=load_db_if_exists, + db_type=db_type, + use_openai_embedding=use_openai_embedding, + hf_embedding_model=hf_embedding_model, + migrate_embedding_model=migrate_embedding_model, + auto_migrate_db=auto_migrate_db, + for_sources_list=True, + verbose=verbose, + n_jobs=n_jobs, + ) + else: + db = None + + t_generate = time.time() + langchain_only_model = base_model in non_hf_types or \ + load_exllama or \ + inference_server.startswith('replicate') or \ + inference_server.startswith('sagemaker') or \ + inference_server.startswith('openai_azure_chat') or \ + inference_server.startswith('openai_azure') + do_langchain_path = langchain_mode not in [False, 'Disabled', 'LLM'] or \ + langchain_only_model or \ + force_langchain_evaluate or \ + len(text_context_list) > 0 + + if len(langchain_agents) > 0: + do_langchain_path = True + if add_search_to_context: + # easier to manage prompt etc. by doing full langchain path + do_langchain_path = True + + if do_langchain_path: + text = '' + sources = '' + response = '' + # use smaller cut_distance for wiki_full since so many matches could be obtained, and often irrelevant unless close + from gpt_langchain import run_qa_db + gen_hyper_langchain = dict(do_sample=do_sample, + temperature=temperature, + repetition_penalty=repetition_penalty, + top_k=top_k, + top_p=top_p, + num_beams=num_beams, + min_new_tokens=min_new_tokens, + max_new_tokens=max_new_tokens, + early_stopping=early_stopping, + max_time=max_time, + num_return_sequences=num_return_sequences, + ) + loaders_dict, captions_model = gr_to_lg(image_loaders, + pdf_loaders, + url_loaders, + captions_model=captions_model, + ) + loaders_dict.update(dict(captions_model=captions_model, + caption_loader=caption_loader, + doctr_loader=doctr_loader, + pix2struct_loader=pix2struct_loader, + jq_schema=jq_schema, + )) + data_point = dict(context=context, instruction=instruction, input=iinput) + # no longer stuff chat history directly into context this early + prompt_basic = prompter.generate_prompt(data_point, context_from_history=False) + prompt = prompt_basic + num_prompt_tokens = 0 + for r in run_qa_db( + inference_server=inference_server, + model_name=base_model, model=model, tokenizer=tokenizer, + langchain_only_model=langchain_only_model, + async_output=async_output, + num_async=num_async, + prompter=prompter, + use_llm_if_no_docs=use_llm_if_no_docs, + load_db_if_exists=load_db_if_exists, + db=db, + langchain_mode_paths=langchain_mode_paths, + langchain_mode_types=langchain_mode_types, + detect_user_path_changes_every_query=detect_user_path_changes_every_query, + cut_distance=1.1 if langchain_mode in ['wiki_full'] else cut_distance, + answer_with_sources=answer_with_sources, + append_sources_to_answer=append_sources_to_answer, + add_chat_history_to_context=add_chat_history_to_context, + add_search_to_context=add_search_to_context, + keep_sources_in_context=keep_sources_in_context, + memory_restriction_level=memory_restriction_level, + system_prompt=system_prompt, + use_openai_embedding=use_openai_embedding, + use_openai_model=use_openai_model, + hf_embedding_model=hf_embedding_model, + migrate_embedding_model=migrate_embedding_model, + auto_migrate_db=auto_migrate_db, + first_para=first_para, + text_limit=text_limit, + show_accordions=show_accordions, + top_k_docs_max_show=top_k_docs_max_show, + show_link_in_sources=show_link_in_sources, + + # evaluate args items + query=instruction, + iinput=iinput, + context=context, + stream_output=stream_output, + chunk=chunk, + chunk_size=chunk_size, + + **loaders_dict, + + langchain_mode=langchain_mode, + langchain_action=langchain_action, + langchain_agents=langchain_agents, + document_subset=document_subset, + document_choice=document_choice, + top_k_docs=top_k_docs, + prompt_type=prompt_type, + prompt_dict=prompt_dict, + pre_prompt_query=pre_prompt_query, + prompt_query=prompt_query, + pre_prompt_summary=pre_prompt_summary, + prompt_summary=prompt_summary, + text_context_list=text_context_list, + chat_conversation=chat_conversation, + visible_models=visible_models, + h2ogpt_key=h2ogpt_key, + docs_ordering_type=docs_ordering_type, + min_max_new_tokens=min_max_new_tokens, + + **gen_hyper_langchain, + + db_type=db_type, + n_jobs=n_jobs, + verbose=verbose, + cli=cli, + sanitize_bot_response=sanitize_bot_response, + + lora_weights=lora_weights, + + auto_reduce_chunks=auto_reduce_chunks, + max_chunks=max_chunks, + total_tokens_for_docs=total_tokens_for_docs, + headsize=headsize, + ): + # doesn't accumulate, new answer every yield, so only save that full answer + response = r['response'] + sources = r['sources'] + prompt = r['prompt'] + num_prompt_tokens = r['num_prompt_tokens'] + yield dict(response=response, sources=sources, save_dict=dict()) + if save_dir: + # estimate using tiktoken + extra_dict = gen_hyper_langchain.copy() + extra_dict.update(prompt_type=prompt_type, + inference_server=inference_server, + langchain_mode=langchain_mode, + langchain_action=langchain_action, + langchain_agents=langchain_agents, + document_subset=document_subset, + document_choice=document_choice, + chat_conversation=chat_conversation, + add_search_to_context=add_search_to_context, + num_prompt_tokens=num_prompt_tokens, + instruction=instruction, + iinput=iinput, + context=context, + t_generate=time.time() - t_generate, + ntokens=None, + tokens_persecond=None, + ) + save_dict = dict(prompt=prompt, + output=response, base_model=base_model, save_dir=save_dir, + where_from='run_qa_db', + extra_dict=extra_dict) + yield dict(response=response, sources=sources, save_dict=save_dict) + if verbose: + print( + 'Post-Generate Langchain: %s decoded_output: %s' % + (str(datetime.now()), len(response) if response else -1), + flush=True) + if response or sources or langchain_only_model: + # if got no response (e.g. not showing sources and got no sources, + # so nothing to give to LLM), then slip through and ask LLM + # Or if llama/gptj, then just return since they had no response and can't go down below code path + # don't clear torch cache here, delays multi-generation, and bot(), all_bot(), and evaluate_nochat() do it + return + + # NOT LANGCHAIN PATH, raw LLM + # restrict instruction + , typically what has large input + prompt, \ + instruction, iinput, context, \ + num_prompt_tokens, max_new_tokens, num_prompt_tokens0, num_prompt_tokens_actual, \ + chat_index, top_k_docs_trial, one_doc_size = \ + get_limited_prompt(instruction, + iinput, + tokenizer, + prompter=prompter, + inference_server=inference_server, + # prompt_type=prompt_type, + # prompt_dict=prompt_dict, + # chat=chat, + max_new_tokens=max_new_tokens, + # system_prompt=system_prompt, + context=context, + chat_conversation=chat_conversation, + keep_sources_in_context=keep_sources_in_context, + model_max_length=model_max_length, + memory_restriction_level=memory_restriction_level, + langchain_mode=langchain_mode, + add_chat_history_to_context=add_chat_history_to_context, + min_max_new_tokens=min_max_new_tokens, + ) + + if inference_server.startswith('vllm') or \ + inference_server.startswith('openai') or \ + inference_server.startswith('http'): + if inference_server.startswith('vllm') or inference_server.startswith('openai'): + assert not inference_server.startswith('openai_azure_chat'), "Not fo Azure, use langchain path" + assert not inference_server.startswith('openai_azure'), "Not for Azure, use langchain path" + openai, inf_type, deployment_name, base_url, api_version = set_openai(inference_server) + where_from = inf_type + + terminate_response = prompter.terminate_response or [] + stop_sequences = list(set(terminate_response + [prompter.PreResponse])) + stop_sequences = [x for x in stop_sequences if x] + # OpenAI will complain if ask for too many new tokens, takes it as min in some sense, wrongly so. + max_new_tokens_openai = min(max_new_tokens, model_max_length - num_prompt_tokens) + gen_server_kwargs = dict(temperature=temperature if do_sample else 0, + max_tokens=max_new_tokens_openai, + top_p=top_p if do_sample else 1, + frequency_penalty=0, + n=num_return_sequences, + presence_penalty=1.07 - repetition_penalty + 0.6, # so good default + ) + if inf_type == 'vllm' or inference_server == 'openai': + responses = openai.Completion.create( + model=base_model, + prompt=prompt, + **gen_server_kwargs, + stop=stop_sequences, + stream=stream_output, + ) + text = '' + sources = '' + response = '' + if not stream_output: + text = responses['choices'][0]['text'] + response = prompter.get_response(prompt + text, prompt=prompt, + sanitize_bot_response=sanitize_bot_response) + yield dict(response=response, sources=sources, save_dict=dict()) + else: + collected_events = [] + for event in responses: + collected_events.append(event) # save the event response + event_text = event['choices'][0]['text'] # extract the text + text += event_text # append the text + response = prompter.get_response(prompt + text, prompt=prompt, + sanitize_bot_response=sanitize_bot_response) + yield dict(response=response, sources=sources, save_dict=dict()) + elif inf_type == 'vllm_chat' or inference_server == 'openai_chat': + if inf_type == 'vllm_chat': + raise NotImplementedError('%s not supported by vLLM' % inf_type) + if system_prompt in [None, 'None', 'auto']: + openai_system_prompt = "You are a helpful assistant." + else: + openai_system_prompt = system_prompt + messages0 = [] + if openai_system_prompt: + messages0.append({"role": "system", "content": openai_system_prompt}) + messages0.append({'role': 'user', 'content': prompt}) + responses = openai.ChatCompletion.create( + model=base_model, + messages=messages0, + stream=stream_output, + **gen_server_kwargs, + ) + text = "" + sources = '' + response = "" + if not stream_output: + text = responses["choices"][0]["message"]["content"] + response = prompter.get_response(prompt + text, prompt=prompt, + sanitize_bot_response=sanitize_bot_response) + yield dict(response=response, sources=sources, save_dict=dict()) + else: + for chunk in responses: + delta = chunk["choices"][0]["delta"] + if 'content' in delta: + text += delta['content'] + response = prompter.get_response(prompt + text, prompt=prompt, + sanitize_bot_response=sanitize_bot_response) + yield dict(response=response, sources=sources, save_dict=dict()) + else: + raise RuntimeError("No such OpenAI mode: %s" % inference_server) + elif inference_server.startswith('http'): + inference_server, headers = get_hf_server(inference_server) + from gradio_utils.grclient import GradioClient + from text_generation import Client as HFClient + if isinstance(model, GradioClient): + gr_client = model + hf_client = None + elif isinstance(model, HFClient): + gr_client = None + hf_client = model + else: + inference_server, gr_client, hf_client = get_client_from_inference_server(inference_server, + base_model=base_model) + + # quick sanity check to avoid long timeouts, just see if can reach server + requests.get(inference_server, timeout=int(os.getenv('REQUEST_TIMEOUT_FAST', '10'))) + + if gr_client is not None: + # Note: h2oGPT gradio server could handle input token size issues for prompt, + # but best to handle here so send less data to server + + chat_client = False + where_from = "gr_client" + client_langchain_mode = 'Disabled' + client_add_chat_history_to_context = True + client_add_search_to_context = False + client_langchain_action = LangChainAction.QUERY.value + client_langchain_agents = [] + gen_server_kwargs = dict(temperature=temperature, + top_p=top_p, + top_k=top_k, + num_beams=num_beams, + max_new_tokens=max_new_tokens, + min_new_tokens=min_new_tokens, + early_stopping=early_stopping, + max_time=max_time, + repetition_penalty=repetition_penalty, + num_return_sequences=num_return_sequences, + do_sample=do_sample, + chat=chat_client, + ) + # account for gradio into gradio that handles prompting, avoid duplicating prompter prompt injection + if prompt_type in [None, '', PromptType.plain.name, PromptType.plain.value, + str(PromptType.plain.value)]: + # if our prompt is plain, assume either correct or gradio server knows different prompt type, + # so pass empty prompt_Type + gr_prompt_type = '' + gr_prompt_dict = '' + gr_prompt = prompt # already prepared prompt + gr_context = '' + gr_iinput = '' + else: + # if already have prompt_type that is not plain, None, or '', then already applied some prompting + # But assume server can handle prompting, and need to avoid double-up. + # Also assume server can do better job of using stopping.py to stop early, so avoid local prompting, let server handle + # So avoid "prompt" and let gradio server reconstruct from prompt_type we passed + # Note it's ok that prompter.get_response() has prompt+text, prompt=prompt passed, + # because just means extra processing and removal of prompt, but that has no human-bot prompting doesn't matter + # since those won't appear + gr_context = context + gr_prompt = instruction + gr_iinput = iinput + gr_prompt_type = prompt_type + gr_prompt_dict = prompt_dict + client_kwargs = dict(instruction=gr_prompt if chat_client else '', # only for chat=True + iinput=gr_iinput, # only for chat=True + context=gr_context, + # streaming output is supported, loops over and outputs each generation in streaming mode + # but leave stream_output=False for simple input/output mode + stream_output=stream_output, + + **gen_server_kwargs, + + prompt_type=gr_prompt_type, + prompt_dict=gr_prompt_dict, + + instruction_nochat=gr_prompt if not chat_client else '', + iinput_nochat=gr_iinput, # only for chat=False + langchain_mode=client_langchain_mode, + add_chat_history_to_context=client_add_chat_history_to_context, + langchain_action=client_langchain_action, + langchain_agents=client_langchain_agents, + top_k_docs=top_k_docs, + chunk=chunk, + chunk_size=chunk_size, + document_subset=DocumentSubset.Relevant.name, + document_choice=[DocumentChoice.ALL.value], + pre_prompt_query=pre_prompt_query, + prompt_query=prompt_query, + pre_prompt_summary=pre_prompt_summary, + prompt_summary=prompt_summary, + system_prompt=system_prompt, + image_loaders=image_loaders, + pdf_loaders=pdf_loaders, + url_loaders=url_loaders, + jq_schema=jq_schema, + visible_models=visible_models, + h2ogpt_key=h2ogpt_key, + add_search_to_context=client_add_search_to_context, + docs_ordering_type=None, + min_max_new_tokens=min_max_new_tokens, + ) + api_name = '/submit_nochat_api' # NOTE: like submit_nochat but stable API for string dict passing + response = '' + text = '' + sources = '' + if not stream_output: + res = gr_client.predict(str(dict(client_kwargs)), api_name=api_name) + res_dict = ast.literal_eval(res) + text = res_dict['response'] + sources = res_dict['sources'] + response = prompter.get_response(prompt + text, prompt=prompt, + sanitize_bot_response=sanitize_bot_response) + yield dict(response=response, sources=sources, save_dict=dict()) + else: + job = gr_client.submit(str(dict(client_kwargs)), api_name=api_name) + res_dict = dict(response=text, sources=sources, save_dict=dict()) + text0 = '' + while not job.done(): + if job.communicator.job.latest_status.code.name == 'FINISHED': + break + e = job.future._exception + if e is not None: + break + outputs_list = job.communicator.job.outputs + if outputs_list: + res = job.communicator.job.outputs[-1] + res_dict = ast.literal_eval(res) + text = res_dict['response'] + sources = res_dict['sources'] + if gr_prompt_type == 'plain': + # then gradio server passes back full prompt + text + prompt_and_text = text + else: + prompt_and_text = prompt + text + response = prompter.get_response(prompt_and_text, prompt=prompt, + sanitize_bot_response=sanitize_bot_response) + text_chunk = response[len(text0):] + if not text_chunk: + continue + # save old + text0 = response + yield dict(response=response, sources=sources, save_dict=dict()) + time.sleep(0.01) + # ensure get last output to avoid race + res_all = job.outputs() + if len(res_all) > 0: + res = res_all[-1] + res_dict = ast.literal_eval(res) + text = res_dict['response'] + sources = res_dict['sources'] + else: + # go with old text if last call didn't work + e = job.future._exception + if e is not None: + stre = str(e) + strex = ''.join(traceback.format_tb(e.__traceback__)) + else: + stre = '' + strex = '' + + print("Bad final response: %s %s %s %s %s: %s %s" % (base_model, inference_server, + res_all, prompt, text, stre, strex), + flush=True) + if gr_prompt_type == 'plain': + # then gradio server passes back full prompt + text + prompt_and_text = text + else: + prompt_and_text = prompt + text + response = prompter.get_response(prompt_and_text, prompt=prompt, + sanitize_bot_response=sanitize_bot_response) + yield dict(response=response, sources=sources, save_dict=dict()) + elif hf_client: + # HF inference server needs control over input tokens + where_from = "hf_client" + response = '' + extra = '' + sources = '' + + # prompt must include all human-bot like tokens, already added by prompt + # https://github.com/huggingface/text-generation-inference/tree/main/clients/python#types + terminate_response = prompter.terminate_response or [] + stop_sequences = list(set(terminate_response + [prompter.PreResponse])) + stop_sequences = [x for x in stop_sequences if x] + gen_server_kwargs = dict(do_sample=do_sample, + max_new_tokens=max_new_tokens, + # best_of=None, + repetition_penalty=repetition_penalty, + return_full_text=False, + seed=SEED, + stop_sequences=stop_sequences, + temperature=temperature, + top_k=top_k, + top_p=top_p, + # truncate=False, # behaves oddly + # typical_p=top_p, + # watermark=False, + # decoder_input_details=False, + ) + # work-around for timeout at constructor time, will be issue if multi-threading, + # so just do something reasonable or max_time if larger + # lower bound because client is re-used if multi-threading + hf_client.timeout = max(300, max_time) + if not stream_output: + text = hf_client.generate(prompt, **gen_server_kwargs).generated_text + response = prompter.get_response(prompt + text, prompt=prompt, + sanitize_bot_response=sanitize_bot_response) + yield dict(response=response, sources=sources, save_dict=dict()) + else: + text = "" + for responses in hf_client.generate_stream(prompt, **gen_server_kwargs): + if not responses.token.special: + # stop_sequences + text_chunk = responses.token.text + text += text_chunk + response = prompter.get_response(prompt + text, prompt=prompt, + sanitize_bot_response=sanitize_bot_response) + sources = '' + yield dict(response=response, sources=sources, save_dict=dict()) + else: + raise RuntimeError("Failed to get client: %s" % inference_server) + else: + raise RuntimeError("No such inference_server %s" % inference_server) + + if save_dir and text: + # save prompt + new text + extra_dict = gen_server_kwargs.copy() + extra_dict.update(dict(inference_server=inference_server, num_prompt_tokens=num_prompt_tokens, + t_generate=time.time() - t_generate, + ntokens=None, + tokens_persecond=None, + )) + save_dict = dict(prompt=prompt, output=text, base_model=base_model, save_dir=save_dir, + where_from=where_from, extra_dict=extra_dict) + yield dict(response=response, sources=sources, save_dict=save_dict) + return + else: + assert not inference_server, "inference_server=%s not supported" % inference_server + + if isinstance(tokenizer, str): + # pipeline + if tokenizer == "summarization": + key = 'summary_text' + else: + raise RuntimeError("No such task type %s" % tokenizer) + # NOTE: uses max_length only + sources = '' + yield dict(response=model(prompt, max_length=max_new_tokens)[0][key], sources=sources, save_dict=dict()) + + if 'mbart-' in base_model.lower(): + assert src_lang is not None + tokenizer.src_lang = languages_covered()[src_lang] + + stopping_criteria = get_stopping(prompt_type, prompt_dict, tokenizer, device, base_model, + model_max_length=model_max_length, + prompter=prompter) + + inputs = tokenizer(prompt, return_tensors="pt") + if debug and len(inputs["input_ids"]) > 0: + print('input_ids length', len(inputs["input_ids"][0]), flush=True) + input_ids = inputs["input_ids"].to(device) + # CRITICAL LIMIT else will fail + max_max_tokens = tokenizer.model_max_length + max_input_tokens = max(0, int(max_max_tokens - min_new_tokens)) + # NOTE: Don't limit up front due to max_new_tokens, let go up to max or reach max_max_tokens in stopping.py + assert isinstance(max_input_tokens, int), "Bad type for max_input_tokens=%s %s" % ( + max_input_tokens, type(max_input_tokens)) + input_ids = input_ids[:, -max_input_tokens:] + # required for falcon if multiple threads or asyncio accesses to model during generation + if use_cache is None: + use_cache = False if 'falcon' in base_model else True + gen_config_kwargs = dict(num_beams=num_beams, + do_sample=do_sample, + repetition_penalty=float(repetition_penalty), + num_return_sequences=num_return_sequences, + renormalize_logits=True, + remove_invalid_values=True, + use_cache=use_cache, + ) + if do_sample: + gen_config_kwargs.update(dict(temperature=float(temperature), + top_p=float(top_p), + top_k=top_k)) + if True: + # unclear impact, some odd things going on inside + # leads to: + # The attention mask and the pad token id were not set. As a consequence, you may observe unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results. + # Setting `pad_token_id` to `eos_token_id`:2 for open-end generation. + # or leads to: + # Using cls_token, but it is not set yet. + # Using mask_token, but it is not set yet. + # Using pad_token, but it is not set yet. + # Using sep_token, but it is not set yet. + token_ids = ['eos_token_id', 'pad_token_id', 'bos_token_id', 'cls_token_id', 'sep_token_id'] + for token_id in token_ids: + if hasattr(tokenizer, token_id) and getattr(tokenizer, token_id) is not None: + gen_config_kwargs.update({token_id: getattr(tokenizer, token_id)}) + generation_config = GenerationConfig(**gen_config_kwargs) + + gen_kwargs = dict(input_ids=input_ids, + generation_config=generation_config, + return_dict_in_generate=True, + output_scores=True, + max_new_tokens=max_new_tokens, # prompt + new + min_new_tokens=min_new_tokens, # prompt + new + early_stopping=early_stopping, # False, True, "never" + max_time=max_time, + stopping_criteria=stopping_criteria, + ) + if 'gpt2' in base_model.lower(): + gen_kwargs.update(dict(bos_token_id=tokenizer.bos_token_id, pad_token_id=tokenizer.eos_token_id)) + elif 'mbart-' in base_model.lower(): + assert tgt_lang is not None + tgt_lang = languages_covered()[tgt_lang] + gen_kwargs.update(dict(forced_bos_token_id=tokenizer.lang_code_to_id[tgt_lang])) + else: + token_ids = ['eos_token_id', 'bos_token_id', 'pad_token_id'] + for token_id in token_ids: + if hasattr(tokenizer, token_id) and getattr(tokenizer, token_id) is not None: + gen_kwargs.update({token_id: getattr(tokenizer, token_id)}) + + decoder_kwargs = dict(skip_special_tokens=True, + clean_up_tokenization_spaces=True) + + decoder = functools.partial(tokenizer.decode, + **decoder_kwargs + ) + with torch.no_grad(): + have_lora_weights = lora_weights not in [no_lora_str, '', None] + context_class_cast = NullContext if device == 'cpu' or have_lora_weights or device == 'mps' else torch.autocast + if t5_type(base_model): + # issues when casting to float16, can mess up t5 model, e.g. only when not streaming, or other odd behaviors + context_class_cast = NullContext + with context_class_cast(device): + # protection for gradio not keeping track of closed users, + # else hit bitsandbytes lack of thread safety: + # https://github.com/h2oai/h2ogpt/issues/104 + # but only makes sense if concurrency_count == 1 + context_class = NullContext # if concurrency_count > 1 else filelock.FileLock + if verbose: + print('Pre-Generate: %s' % str(datetime.now()), flush=True) + decoded_output = None + response = '' + with context_class("generate.lock"): + if verbose: + print('Generate: %s' % str(datetime.now()), flush=True) + always_use_streaming_method = True # to deal with complex parsing of prompt vs. generation due to odd tokenizing + if stream_output or always_use_streaming_method: + skip_prompt = True # True means first output excludes prompt + streamer = H2OTextIteratorStreamer(tokenizer, skip_prompt=skip_prompt, block=False, + **decoder_kwargs) + gen_kwargs.update(dict(streamer=streamer)) + target = wrapped_partial(generate_with_exceptions, model.generate, + raise_generate_gpu_exceptions=raise_generate_gpu_exceptions, + **gen_kwargs) + bucket = queue.Queue() + thread = EThread(target=target, streamer=streamer, bucket=bucket) + thread.start() + ret = dict(response='', sources='', save_dict=dict()) + outputs = "" + sources = '' + try: + for new_text in streamer: + if bucket.qsize() > 0 or thread.exc: + thread.join() + outputs += new_text + response = prompter.get_response(outputs, prompt=None, + only_new_text=True, + sanitize_bot_response=sanitize_bot_response) + ret = dict(response=response, sources=sources, save_dict=dict()) + if stream_output: + yield ret + if not stream_output: + yield ret + except BaseException: + # if any exception, raise that exception if was from thread, first + if thread.exc: + raise thread.exc + raise + finally: + # don't clear torch cache here, delays multi-generation, and bot(), all_bot(), and evaluate_nochat() do it + # in case no exception and didn't join with thread yet, then join + if not thread.exc: + thread.join() + # in case raise StopIteration or broke queue loop in streamer, but still have exception + if thread.exc: + raise thread.exc + decoded_output = outputs + ntokens = len(outputs) // 4 # hack for now + else: + # below length removal doesn't work in general, because encoding does not match internal of model generation + input_ids_len = gen_kwargs['input_ids'][0].shape[0] + try: + outputs = model.generate(**gen_kwargs) + finally: + pass + # don't clear torch cache here, delays multi-generation, and bot(), all_bot(), and evaluate_nochat() do it + # skip first IDs + ntokens = sum([len(s) - input_ids_len for s in outputs.sequences]) if save_dir else -1 + outputs = [decoder(s[input_ids_len:]) for s in outputs.sequences] + sources = '' + response = prompter.get_response(outputs, prompt=None, + only_new_text=True, + sanitize_bot_response=sanitize_bot_response) + yield dict(response=response, sources=sources, save_dict=dict()) + if outputs and len(outputs) >= 1: + decoded_output = prompt + outputs[0] + if save_dir and decoded_output: + extra_dict = gen_config_kwargs.copy() + extra_dict.update(dict(num_prompt_tokens=num_prompt_tokens, + t_generate=time.time() - t_generate, + ntokens=ntokens, + tokens_persecond=ntokens / (time.time() - t_generate), + )) + save_dict = dict(prompt=prompt, output=decoded_output, base_model=base_model, save_dir=save_dir, + where_from="evaluate_%s" % str(stream_output), + extra_dict=extra_dict) + yield dict(response=response, sources=sources, save_dict=save_dict) + if verbose: + print('Post-Generate: %s decoded_output: %s' % ( + str(datetime.now()), len(decoded_output) if decoded_output else -1), flush=True) + + +inputs_list_names = list(inspect.signature(evaluate).parameters) +state_names = input_args_list.copy() # doesn't have to be the same, but state_names must match evaluate() and how filled then +inputs_kwargs_list = [x for x in inputs_list_names if x not in eval_func_param_names + state_names] + + +def get_cutoffs(memory_restriction_level, for_context=False, model_max_length=2048): + # help to avoid errors like: + # RuntimeError: The size of tensor a (2048) must match the size of tensor b (2049) at non-singleton dimension 3 + # RuntimeError: expected scalar type Half but found Float + # with - 256 + if memory_restriction_level > 0: + max_length_tokenize = 768 - 256 if memory_restriction_level <= 2 else 512 - 256 + else: + # at least give room for 1 paragraph output + max_length_tokenize = model_max_length - 256 + cutoff_len = max_length_tokenize * 4 # if reaches limit, then can't generate new tokens + output_smallest = 30 * 4 + max_prompt_length = cutoff_len - output_smallest + + if for_context: + # then lower even more to avoid later chop, since just estimate tokens in context bot + max_prompt_length = max(64, int(max_prompt_length * 0.8)) + + return cutoff_len, output_smallest, max_length_tokenize, max_prompt_length + + +class H2OTextIteratorStreamer(TextIteratorStreamer): + """ + normally, timeout required for now to handle exceptions, else get() + but with H2O version of TextIteratorStreamer, loop over block to handle + """ + + def __init__(self, tokenizer, skip_prompt: bool = False, timeout: typing.Optional[float] = None, + block=True, **decode_kwargs): + super().__init__(tokenizer, skip_prompt, **decode_kwargs) + self.text_queue = queue.Queue() + self.stop_signal = None + self.do_stop = False + self.timeout = timeout + self.block = block + + def on_finalized_text(self, text: str, stream_end: bool = False): + """Put the new text in the queue. If the stream is ending, also put a stop signal in the queue.""" + self.text_queue.put(text, timeout=self.timeout) + if stream_end: + self.text_queue.put(self.stop_signal, timeout=self.timeout) + + def __iter__(self): + return self + + def __next__(self): + while True: + try: + value = self.stop_signal # value looks unused in pycharm, not true + if self.do_stop: + print("hit stop", flush=True) + # could raise or break, maybe best to raise and make parent see if any exception in thread + self.clear_queue() + self.do_stop = False + raise StopIteration() + # break + value = self.text_queue.get(block=self.block, timeout=self.timeout) + break + except queue.Empty: + time.sleep(0.01) + if value == self.stop_signal: + self.clear_queue() + self.do_stop = False + raise StopIteration() + else: + return value + + def clear_queue(self): + # make sure streamer is reusable after stop hit + with self.text_queue.mutex: + self.text_queue.queue.clear() + + def put(self, value): + """ + Receives tokens, decodes them, and prints them to stdout as soon as they form entire words. + # same as base class, except remove hack w.r.t. text.rfind(" ") that ruins LLaMa2 + """ + if len(value.shape) > 1 and value.shape[0] > 1: + raise ValueError("TextStreamer only supports batch size 1") + elif len(value.shape) > 1: + value = value[0] + + if self.skip_prompt and self.next_tokens_are_prompt: + self.next_tokens_are_prompt = False + return + + # Add the new token to the cache and decodes the entire thing. + self.token_cache.extend(value.tolist()) + text = self.tokenizer.decode(self.token_cache, **self.decode_kwargs) + + # After the symbol for a new line, we flush the cache. + if text.endswith("\n"): + printable_text = text[self.print_len:] + self.token_cache = [] + self.print_len = 0 + # If the last token is a CJK character, we print the characters. + elif len(text) > 0 and self._is_chinese_char(ord(text[-1])): + printable_text = text[self.print_len:] + self.print_len += len(printable_text) + # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, + # which may change with the subsequent token -- there are probably smarter ways to do this!) + elif len(text) > 0 and text[-1] == '�': + printable_text = text[self.print_len: text.rfind(" ") + 1] + self.print_len += len(printable_text) + else: + printable_text = text[self.print_len:] + self.print_len += len(printable_text) + + self.on_finalized_text(printable_text) + + +def generate_with_exceptions(func, *args, raise_generate_gpu_exceptions=True, **kwargs): + try: + func(*args, **kwargs) + except torch.cuda.OutOfMemoryError as e: + print("GPU OOM 2: exception: %s" % str(e), + flush=True) + if 'input_ids' in kwargs: + if kwargs['input_ids'] is not None: + kwargs['input_ids'].cpu() + kwargs['input_ids'] = None + traceback.print_exc() + clear_torch_cache() + return + except (Exception, RuntimeError) as e: + if 'Expected all tensors to be on the same device' in str(e) or \ + 'expected scalar type Half but found Float' in str(e) or \ + 'probability tensor contains either' in str(e) or \ + 'cublasLt ran into an error!' in str(e) or \ + 'mat1 and mat2 shapes cannot be multiplied' in str(e): + print( + "GPU Error: exception: %s" % str(e), + flush=True) + traceback.print_exc() + clear_torch_cache() + if raise_generate_gpu_exceptions: + raise + return + else: + clear_torch_cache() + if raise_generate_gpu_exceptions: + raise + + +def get_generate_params(model_lower, + chat, + stream_output, show_examples, + prompt_type, prompt_dict, + system_prompt, + pre_prompt_query, prompt_query, + pre_prompt_summary, prompt_summary, + temperature, top_p, top_k, num_beams, + max_new_tokens, min_new_tokens, early_stopping, max_time, + repetition_penalty, num_return_sequences, + do_sample, + top_k_docs, chunk, chunk_size, + image_loaders, + pdf_loaders, + url_loaders, + jq_schema, + docs_ordering_type, + min_max_new_tokens, + verbose, + ): + use_defaults = False + use_default_examples = True + examples = [] + task_info = 'LLM' + if model_lower: + print(f"Using Model {model_lower}", flush=True) + else: + if verbose: + print("No model defined yet", flush=True) + + min_new_tokens = min_new_tokens if min_new_tokens is not None else 0 + early_stopping = early_stopping if early_stopping is not None else False + max_time_defaults = 60 * 3 + max_time = max_time if max_time is not None else max_time_defaults + + if not prompt_type and model_lower in inv_prompt_type_to_model_lower and prompt_type != 'custom': + prompt_type = inv_prompt_type_to_model_lower[model_lower] + if verbose: + print("Auto-selecting prompt_type=%s for %s" % (prompt_type, model_lower), flush=True) + + # examples at first don't include chat, instruction_nochat, iinput_nochat, added at end + if show_examples is None: + if chat: + show_examples = False + else: + show_examples = True + + summarize_example1 = """Jeff: Can I train a ? Transformers model on Amazon SageMaker? +Philipp: Sure you can use the new Hugging Face Deep Learning Container. +Jeff: ok. +Jeff: and how can I get started? +Jeff: where can I find documentation? +Philipp: ok, ok you can find everything here. https://huggingface.co/blog/the-partnership-amazon-sagemaker-and-hugging-face""" + + use_placeholder_instruction_as_example = False + if 'bart-large-cnn-samsum' in model_lower or 'flan-t5-base-samsum' in model_lower: + placeholder_instruction = summarize_example1 + placeholder_input = "" + use_defaults = True + use_default_examples = False + use_placeholder_instruction_as_example = True + task_info = "Summarization" + elif 't5-' in model_lower or 't5' == model_lower or 'flan-' in model_lower: + placeholder_instruction = "The square root of x is the cube root of y. What is y to the power of 2, if x = 4?" + placeholder_input = "" + use_defaults = True + use_default_examples = True + task_info = "Multi-Task: Q/A, translation, Chain-of-Thought, Logical Reasoning, Summarization, etc. Best to use task prefix as trained on, e.g. `translate English to German: ` (space after colon)" + elif 'mbart-' in model_lower: + placeholder_instruction = "The girl has long hair." + placeholder_input = "" + use_defaults = True + use_default_examples = False + use_placeholder_instruction_as_example = True + elif 'gpt2' in model_lower: + placeholder_instruction = "The sky is" + placeholder_input = "" + prompt_type = prompt_type or 'plain' + use_default_examples = True # some will be odd "continuations" but can be ok + use_placeholder_instruction_as_example = True + task_info = "Auto-complete phrase, code, etc." + use_defaults = True + else: + if chat: + placeholder_instruction = "" + else: + placeholder_instruction = "Give detailed answer for whether Einstein or Newton is smarter." + placeholder_input = "" + if not prompt_type and model_lower in inv_prompt_type_to_model_lower and prompt_type != 'custom': + prompt_type = inv_prompt_type_to_model_lower[model_lower] + elif model_lower: + # default is plain, because might rely upon trust_remote_code to handle prompting + prompt_type = prompt_type or 'plain' + else: + prompt_type = '' + task_info = "No task" + if prompt_type == 'instruct': + task_info = "Answer question or follow imperative as instruction with optionally input." + elif prompt_type == 'plain': + task_info = "Auto-complete phrase, code, etc." + elif prompt_type == 'human_bot': + if chat: + task_info = "Chat (Shift-Enter to give question/imperative, input concatenated with instruction)" + else: + task_info = "Ask question/imperative (input concatenated with instruction)" + + # revert to plain if still nothing + prompt_type = prompt_type or 'plain' + if use_defaults: + temperature = 1.0 if temperature is None else temperature + top_p = 1.0 if top_p is None else top_p + top_k = 40 if top_k is None else top_k + num_beams = num_beams or 1 + max_new_tokens = max_new_tokens or 512 + repetition_penalty = repetition_penalty or 1.07 + num_return_sequences = min(num_beams, num_return_sequences or 1) + do_sample = False if do_sample is None else do_sample + else: + temperature = 0.1 if temperature is None else temperature + top_p = 0.75 if top_p is None else top_p + top_k = 40 if top_k is None else top_k + num_beams = num_beams or 1 + max_new_tokens = max_new_tokens or 1024 + repetition_penalty = repetition_penalty or 1.07 + num_return_sequences = min(num_beams, num_return_sequences or 1) + do_sample = False if do_sample is None else do_sample + # doesn't include chat, instruction_nochat, iinput_nochat, added later + params_list = ["", + stream_output, + prompt_type, prompt_dict, + temperature, top_p, top_k, num_beams, + max_new_tokens, min_new_tokens, + early_stopping, max_time, repetition_penalty, num_return_sequences, do_sample] + + if use_placeholder_instruction_as_example: + examples += [[placeholder_instruction, ''] + params_list] + + if use_default_examples: + examples += [ + ["Translate English to French", "Good morning"] + params_list, + ["Give detailed answer for whether Einstein or Newton is smarter.", ''] + params_list, + ["Explain in detailed list, all the best practices for coding in python.", ''] + params_list, + [ + "Create a markdown table with 3 rows for the primary colors, and 2 columns, with color name and hex codes.", + ''] + params_list, + ['Translate to German: My name is Arthur', ''] + params_list, + ["Please answer to the following question. Who is going to be the next Ballon d'or?", ''] + params_list, + ['Can Geoffrey Hinton have a conversation with George Washington? Give the rationale before answering.', + ''] + params_list, + ['Please answer the following question. What is the boiling point of Nitrogen?', ''] + params_list, + ['Answer the following yes/no question. Can you write a whole Haiku in a single tweet?', ''] + params_list, + ["Simplify the following expression: (False or False and True). Explain your answer.", ''] + params_list, + [ + "Premise: At my age you will probably have learnt one lesson. Hypothesis: It's not certain how many lessons you'll learn by your thirties. Does the premise entail the hypothesis?", + ''] + params_list, + ['The square root of x is the cube root of y. What is y to the power of 2, if x = 4?', ''] + params_list, + [ + 'Answer the following question by reasoning step by step. The cafeteria had 23 apples. If they used 20 for lunch, and bought 6 more, how many apple do they have?', + ''] + params_list, + ["""def area_of_rectangle(a: float, b: float): + \"\"\"Return the area of the rectangle.\"\"\"""", ''] + params_list, + ["""# a function in native python: +def mean(a): + return sum(a)/len(a) + +# the same function using numpy: +import numpy as np +def mean(a):""", ''] + params_list, + ["""X = np.random.randn(100, 100) +y = np.random.randint(0, 1, 100) + +# fit random forest classifier with 20 estimators""", ''] + params_list, + ] + # add summary example + examples += [ + [summarize_example1, 'Summarize' if prompt_type not in ['plain', 'instruct_simple'] else ''] + params_list] + + src_lang = "English" + tgt_lang = "Russian" + + # move to correct position + for example in examples: + example += [chat, '', '', LangChainMode.DISABLED.value, True, + LangChainAction.QUERY.value, [], + top_k_docs, chunk, chunk_size, DocumentSubset.Relevant.name, [], + pre_prompt_query, prompt_query, + pre_prompt_summary, prompt_summary, + system_prompt, + image_loaders, + pdf_loaders, + url_loaders, + jq_schema, + None, + None, + False, + None, + None, + docs_ordering_type, + min_max_new_tokens, + ] + # adjust examples if non-chat mode + if not chat: + example[eval_func_param_names.index('instruction_nochat')] = example[ + eval_func_param_names.index('instruction')] + example[eval_func_param_names.index('instruction')] = '' + + example[eval_func_param_names.index('iinput_nochat')] = example[eval_func_param_names.index('iinput')] + example[eval_func_param_names.index('iinput')] = '' + assert len(example) == len(eval_func_param_names), "Wrong example: %s %s" % ( + len(example), len(eval_func_param_names)) + + if prompt_type == PromptType.custom.name and not prompt_dict: + raise ValueError("Unexpected to get non-empty prompt_dict=%s for prompt_type=%s" % (prompt_dict, prompt_type)) + + # get prompt_dict from prompt_type, so user can see in UI etc., or for custom do nothing except check format + prompt_dict, error0 = get_prompt(prompt_type, prompt_dict, + chat=False, context='', reduced=False, making_context=False, return_dict=True, + system_prompt=system_prompt) + if error0: + raise RuntimeError("Prompt wrong: %s" % error0) + + return placeholder_instruction, placeholder_input, \ + stream_output, show_examples, \ + prompt_type, prompt_dict, \ + temperature, top_p, top_k, num_beams, \ + max_new_tokens, min_new_tokens, early_stopping, max_time, \ + repetition_penalty, num_return_sequences, \ + do_sample, \ + src_lang, tgt_lang, \ + examples, \ + task_info + + +def languages_covered(): + # https://huggingface.co/facebook/mbart-large-50-many-to-many-mmt#languages-covered + covered = """Arabic (ar_AR), Czech (cs_CZ), German (de_DE), English (en_XX), Spanish (es_XX), Estonian (et_EE), Finnish (fi_FI), French (fr_XX), Gujarati (gu_IN), Hindi (hi_IN), Italian (it_IT), Japanese (ja_XX), Kazakh (kk_KZ), Korean (ko_KR), Lithuanian (lt_LT), Latvian (lv_LV), Burmese (my_MM), Nepali (ne_NP), Dutch (nl_XX), Romanian (ro_RO), Russian (ru_RU), Sinhala (si_LK), Turkish (tr_TR), Vietnamese (vi_VN), Chinese (zh_CN), Afrikaans (af_ZA), Azerbaijani (az_AZ), Bengali (bn_IN), Persian (fa_IR), Hebrew (he_IL), Croatian (hr_HR), Indonesian (id_ID), Georgian (ka_GE), Khmer (km_KH), Macedonian (mk_MK), Malayalam (ml_IN), Mongolian (mn_MN), Marathi (mr_IN), Polish (pl_PL), Pashto (ps_AF), Portuguese (pt_XX), Swedish (sv_SE), Swahili (sw_KE), Tamil (ta_IN), Telugu (te_IN), Thai (th_TH), Tagalog (tl_XX), Ukrainian (uk_UA), Urdu (ur_PK), Xhosa (xh_ZA), Galician (gl_ES), Slovene (sl_SI)""" + covered = covered.split(', ') + covered = {x.split(' ')[0]: x.split(' ')[1].replace(')', '').replace('(', '') for x in covered} + return covered + + +def score_qa(smodel, stokenizer, max_length_tokenize, question, answer, cutoff_len): + question = question[-cutoff_len:] + answer = answer[-cutoff_len:] + + inputs = stokenizer(question, answer, + return_tensors="pt", + truncation=True, + max_length=max_length_tokenize).to(smodel.device) + try: + score = torch.sigmoid(smodel(**inputs.to(smodel.device)).logits[0].float()).cpu().detach().numpy()[0] + except torch.cuda.OutOfMemoryError as e: + print("GPU OOM 3: question: %s answer: %s exception: %s" % (question, answer, str(e)), flush=True) + del inputs + traceback.print_exc() + clear_torch_cache() + return 'Response Score: GPU OOM' + except (Exception, RuntimeError) as e: + if 'Expected all tensors to be on the same device' in str(e) or \ + 'expected scalar type Half but found Float' in str(e) or \ + 'probability tensor contains either' in str(e) or \ + 'cublasLt ran into an error!' in str(e) or \ + 'device-side assert triggered' in str(e): + print("GPU Error: question: %s answer: %s exception: %s" % (question, answer, str(e)), + flush=True) + traceback.print_exc() + clear_torch_cache() + return 'Response Score: GPU Error' + else: + raise + os.environ['TOKENIZERS_PARALLELISM'] = 'true' + return score + + +def check_locals(**kwargs): + # ensure everything in evaluate is here + can_skip_because_locally_generated = no_default_param_names + [ + # get_model: + 'reward_type' + ] + for k in eval_func_param_names: + if k in can_skip_because_locally_generated: + continue + assert k in kwargs, "Missing %s" % k + for k in inputs_kwargs_list: + if k in can_skip_because_locally_generated: + continue + assert k in kwargs, "Missing %s" % k + + for k in list(inspect.signature(get_model).parameters): + if k in can_skip_because_locally_generated: + continue + assert k in kwargs, "Missing %s" % k + + +def get_model_max_length(model_state): + if not isinstance(model_state['tokenizer'], (str, type(None))): + return model_state['tokenizer'].model_max_length + else: + return 2048 + + +def get_max_max_new_tokens(model_state, **kwargs): + if not isinstance(model_state['tokenizer'], (str, type(None))): + max_max_new_tokens = model_state['tokenizer'].model_max_length + else: + max_max_new_tokens = None + + if kwargs['max_max_new_tokens'] is not None and max_max_new_tokens is not None: + return min(max_max_new_tokens, kwargs['max_max_new_tokens']) + elif kwargs['max_max_new_tokens'] is not None: + return kwargs['max_max_new_tokens'] + elif kwargs['memory_restriction_level'] == 1: + return 768 + elif kwargs['memory_restriction_level'] == 2: + return 512 + elif kwargs['memory_restriction_level'] >= 3: + return 256 + else: + # FIXME: Need to update after new model loaded, so user can control with slider + return 2048 + + +def get_minmax_top_k_docs(is_public): + if is_public: + min_top_k_docs = 1 + max_top_k_docs = 8 + label_top_k_docs = "Number of document chunks" + else: + min_top_k_docs = -1 + max_top_k_docs = 100 + label_top_k_docs = "Number of document chunks (-1 = auto fill model context)" + return min_top_k_docs, max_top_k_docs, label_top_k_docs + + +def merge_chat_conversation_history(chat_conversation1, history): + # chat_conversation and history ordered so largest index of list is most recent + if chat_conversation1: + chat_conversation1 = str_to_list(chat_conversation1) + for conv1 in chat_conversation1: + assert isinstance(conv1, (list, tuple)) + assert len(conv1) == 2 + + if isinstance(history, list): + # make copy so only local change + if chat_conversation1: + # so priority will be newest that comes from actual chat history from UI, then chat_conversation + history = chat_conversation1 + history.copy() + elif chat_conversation1: + history = chat_conversation1 + else: + history = [] + return history + + +def history_to_context(history, langchain_mode=None, + add_chat_history_to_context=None, + prompt_type=None, prompt_dict=None, chat=None, model_max_length=None, + memory_restriction_level=None, keep_sources_in_context=None, + system_prompt=None, chat_conversation=None): + """ + consumes all history up to (but not including) latest history item that is presumed to be an [instruction, None] pair + :param history: + :param langchain_mode: + :param add_chat_history_to_context: + :param prompt_type: + :param prompt_dict: + :param chat: + :param model_max_length: + :param memory_restriction_level: + :param keep_sources_in_context: + :param system_prompt: + :param chat_conversation: + :return: + """ + history = merge_chat_conversation_history(chat_conversation, history) + + if len(history) >= 1 and len(history[-1]) >= 2 and not history[-1][1]: + len_history = len(history) - 1 + else: + # full history + len_history = len(history) + + # ensure output will be unique to models + _, _, _, max_prompt_length = get_cutoffs(memory_restriction_level, + for_context=True, model_max_length=model_max_length) + context1 = '' + if max_prompt_length is not None and add_chat_history_to_context: + context1 = '' + # - 1 below because current instruction already in history from user() + for histi in range(0, len_history): + data_point = dict(instruction=history[histi][0], input='', output=history[histi][1]) + prompt, pre_response, terminate_response, chat_sep, chat_turn_sep = \ + generate_prompt(data_point, + prompt_type, + prompt_dict, + chat, + reduced=True, + making_context=True, + system_prompt=system_prompt, + histi=histi) + # md -> back to text, maybe not super important if model trained enough + if not keep_sources_in_context and langchain_mode != 'Disabled' and prompt.find(super_source_prefix) >= 0: + # FIXME: This is relatively slow even for small amount of text, like 0.3s each history item + import re + prompt = re.sub(f'{re.escape(super_source_prefix)}.*?{re.escape(super_source_postfix)}', '', prompt, + flags=re.DOTALL) + if prompt.endswith('\n

'): + prompt = prompt[:-4] + prompt = prompt.replace('
', chat_turn_sep) + if not prompt.endswith(chat_turn_sep): + prompt += chat_turn_sep + # most recent first, add older if can + # only include desired chat history + if len(prompt + context1) > max_prompt_length: + break + context1 += prompt + + _, pre_response, terminate_response, chat_sep, chat_turn_sep = \ + generate_prompt({}, prompt_type, prompt_dict, + chat, reduced=True, + making_context=True, + system_prompt=system_prompt, + histi=-1) + if context1 and not context1.endswith(chat_turn_sep): + context1 += chat_turn_sep # ensure if terminates abruptly, then human continues on next line + return context1 + + +def get_limited_prompt(instruction, + iinput, + tokenizer, + prompter=None, + inference_server=None, + prompt_type=None, prompt_dict=None, chat=False, max_new_tokens=None, + system_prompt='', + context='', chat_conversation=None, text_context_list=None, + keep_sources_in_context=False, + model_max_length=None, memory_restriction_level=0, + langchain_mode=None, add_chat_history_to_context=True, + verbose=False, + doc_importance=0.5, + min_max_new_tokens=256, + ): + if prompter: + prompt_type = prompter.prompt_type + prompt_dict = prompter.prompt_dict + chat = prompter.chat + stream_output = prompter.stream_output + system_prompt = prompter.system_prompt + + # merge handles if chat_conversation is None + history = [] + history = merge_chat_conversation_history(chat_conversation, history) + history_to_context_func = functools.partial(history_to_context, + langchain_mode=langchain_mode, + add_chat_history_to_context=add_chat_history_to_context, + prompt_type=prompt_type, + prompt_dict=prompt_dict, + chat=chat, + model_max_length=model_max_length, + memory_restriction_level=memory_restriction_level, + keep_sources_in_context=keep_sources_in_context, + system_prompt=system_prompt) + context2 = history_to_context_func(history) + context1 = context + if context1 is None: + context1 = '' + + from h2oai_pipeline import H2OTextGenerationPipeline + data_point_just_instruction = dict(context='', instruction=instruction, input='') + prompt_just_instruction = prompter.generate_prompt(data_point_just_instruction) + instruction, num_instruction_tokens = H2OTextGenerationPipeline.limit_prompt(instruction, tokenizer) + num_instruction_tokens_real = get_token_count(prompt_just_instruction, tokenizer) + num_instruction_tokens += (num_instruction_tokens_real - num_instruction_tokens) + + context1, num_context1_tokens = H2OTextGenerationPipeline.limit_prompt(context1, tokenizer) + context2, num_context2_tokens = H2OTextGenerationPipeline.limit_prompt(context2, tokenizer) + iinput, num_iinput_tokens = H2OTextGenerationPipeline.limit_prompt(iinput, tokenizer) + if text_context_list is None: + text_context_list = [] + num_doc_tokens = sum([get_token_count(x + '\n\n', tokenizer) for x in text_context_list]) + + num_prompt_tokens0 = (num_instruction_tokens or 0) + \ + (num_context1_tokens or 0) + \ + (num_context2_tokens or 0) + \ + (num_iinput_tokens or 0) + \ + (num_doc_tokens or 0) + + # go down to no less than 256, about 1 paragraph + # use max_new_tokens before use num_prompt_tokens0 else would be negative or ~0 + min_max_new_tokens = min(min_max_new_tokens, max_new_tokens) + # by default assume can handle all chat and docs + chat_index = 0 + + # allowed residual is either half of what is allowed if doc exceeds half, or is rest of what doc didn't consume + num_non_doc_tokens = num_prompt_tokens0 - num_doc_tokens + # to doc first then non-doc, shouldn't matter much either way + doc_max_length = max(model_max_length - num_non_doc_tokens, doc_importance * model_max_length) + top_k_docs, one_doc_size, num_doc_tokens = get_docs_tokens(tokenizer, text_context_list=text_context_list, + max_input_tokens=doc_max_length) + non_doc_max_length = max(model_max_length - num_doc_tokens, (1.0 - doc_importance) * model_max_length) + + if num_non_doc_tokens > non_doc_max_length: + # need to limit in some way, keep portion of history but all of context and instruction + # 1) drop iinput (unusual to include anyways) + # 2) reduce history + # 3) reduce context1 + # 4) limit instruction so will fit + diff1 = non_doc_max_length - ( + num_instruction_tokens + num_context1_tokens + num_context2_tokens + min_max_new_tokens) + diff2 = non_doc_max_length - (num_instruction_tokens + num_context1_tokens + min_max_new_tokens) + diff3 = non_doc_max_length - (num_instruction_tokens + min_max_new_tokens) + diff4 = non_doc_max_length - min_max_new_tokens + if diff1 > 0: + # then should be able to do #1 + iinput = '' + num_iinput_tokens = 0 + elif diff2 > 0 > diff1: + # then may be able to do #1 + #2 + iinput = '' + num_iinput_tokens = 0 + chat_index_final = len(history) + for chat_index in range(len(history)): + # NOTE: history and chat_conversation are older for first entries + # FIXME: This is a slow for many short conversations + context2 = history_to_context_func(history[chat_index:]) + num_context2_tokens = get_token_count(context2, tokenizer) + diff1 = non_doc_max_length - ( + num_instruction_tokens + num_context1_tokens + num_context2_tokens + min_max_new_tokens) + if diff1 > 0: + chat_index_final = chat_index + if verbose: + print("chat_conversation used %d out of %d" % (chat_index, len(history)), flush=True) + break + chat_index = chat_index_final # i.e. if chat_index == len(history), then nothing can be consumed + elif diff3 > 0 > diff2: + # then may be able to do #1 + #2 + #3 + iinput = '' + num_iinput_tokens = 0 + context2 = '' + num_context2_tokens = 0 + context1, num_context1_tokens = H2OTextGenerationPipeline.limit_prompt(context1, tokenizer, + max_prompt_length=diff3) + if num_context1_tokens <= diff3: + pass + else: + print("failed to reduce", flush=True) + else: + # then must be able to do #1 + #2 + #3 + #4 + iinput = '' + num_iinput_tokens = 0 + context2 = '' + num_context2_tokens = 0 + context1 = '' + num_context1_tokens = 0 + # diff4 accounts for real prompting for instruction + # FIXME: history_to_context could include instruction, in case system prompt long, we overcount and could have more free tokens + instruction, num_instruction_tokens = H2OTextGenerationPipeline.limit_prompt(instruction, tokenizer, + max_prompt_length=diff4) + # get actual tokens + data_point_just_instruction = dict(context='', instruction=instruction, input='') + prompt_just_instruction = prompter.generate_prompt(data_point_just_instruction) + num_instruction_tokens_real = get_token_count(prompt_just_instruction, tokenizer) + num_instruction_tokens += (num_instruction_tokens_real - num_instruction_tokens) + + # update full context + context = context1 + context2 + # update token counts (docs + non-docs, all tokens) + num_prompt_tokens = (num_instruction_tokens or 0) + \ + (num_context1_tokens or 0) + \ + (num_context2_tokens or 0) + \ + (num_iinput_tokens or 0) + \ + (num_doc_tokens or 0) + + # update max_new_tokens + if inference_server and inference_server.startswith('http'): + # assume TGI/Gradio setup to consume tokens and have long output too, even if exceeds model capacity. + pass + else: + # limit so max_new_tokens = prompt + new < max + # otherwise model can fail etc. e.g. for distilgpt2 asking for 1024 tokens is enough to fail if prompt=1 token + max_new_tokens = min(max_new_tokens, model_max_length - num_prompt_tokens) + + if prompter is None: + # get prompter + debug = False + stream_output = False # doesn't matter + prompter = Prompter(prompt_type, prompt_dict, debug=debug, chat=chat, stream_output=stream_output, + system_prompt=system_prompt) + + data_point = dict(context=context, instruction=instruction, input=iinput) + # handle promptA/promptB addition if really from history. + # if not from history, then reduced=False inside correct + # if mixed, then no specific correct thing to do, so treat like history and promptA/B will come first still + context_from_history = len(history) > 0 and len(context1) > 0 + prompt = prompter.generate_prompt(data_point, context_from_history=context_from_history) + num_prompt_tokens_actual = get_token_count(prompt, tokenizer) + + return prompt, \ + instruction, iinput, context, \ + num_prompt_tokens, max_new_tokens, num_prompt_tokens0, num_prompt_tokens_actual, \ + chat_index, top_k_docs, one_doc_size + + +def get_docs_tokens(tokenizer, text_context_list=[], max_input_tokens=None): + if text_context_list is None or len(text_context_list) == 0: + return 0, None, 0 + if max_input_tokens is None: + max_input_tokens = tokenizer.model_max_length + tokens = [get_token_count(x + '\n\n', tokenizer) for x in text_context_list] + tokens_cumsum = np.cumsum(tokens) + where_res = np.where(tokens_cumsum < max_input_tokens)[0] + # if below condition fails, then keep top_k_docs=-1 and trigger special handling next + if where_res.shape[0] > 0: + top_k_docs = 1 + where_res[-1] + one_doc_size = None + num_doc_tokens = tokens_cumsum[top_k_docs - 1] # by index + else: + # if here, means 0 and just do best with 1 doc + top_k_docs = 1 + text_context_list = text_context_list[:top_k_docs] + # critical protection + from src.h2oai_pipeline import H2OTextGenerationPipeline + doc_content = text_context_list[0] + doc_content, new_tokens0 = H2OTextGenerationPipeline.limit_prompt(doc_content, + tokenizer, + max_prompt_length=max_input_tokens) + text_context_list[0] = doc_content + one_doc_size = len(doc_content) + num_doc_tokens = get_token_count(doc_content + '\n\n', tokenizer) + print("Unexpected large chunks and can't add to context, will add 1 anyways. Tokens %s -> %s" % ( + tokens[0], new_tokens0), flush=True) + return top_k_docs, one_doc_size, num_doc_tokens + + +def entrypoint_main(): + """ + Examples: + + WORLD_SIZE=4 CUDA_VISIBLE_DEVICES="0,1,2,3" torchrun --nproc_per_node=4 --master_port=1234 generate.py --base_model='EleutherAI/gpt-j-6B' --lora_weights=lora-alpaca_6B + python generate.py --base_model='EleutherAI/gpt-j-6B' --lora_weights='lora-alpaca_6B' + python generate.py --base_model='EleutherAI/gpt-neox-20b' --lora_weights='lora-alpaca_20B' + + # generate without lora weights, no prompt + python generate.py --base_model='EleutherAI/gpt-neox-20b' --prompt_type='plain' + python generate.py --base_model='togethercomputer/GPT-NeoXT-Chat-Base-20B' --prompt_type='dai_faq' + + python generate.py --base_model='togethercomputer/GPT-NeoXT-Chat-Base-20B' --prompt_type='dai_faq' --lora_weights='lora_20B_daifaq' + # OpenChatKit settings: + python generate.py --base_model='togethercomputer/GPT-NeoXT-Chat-Base-20B' --prompt_type='human_bot --debug=True --num_beams=1 --temperature=0.6 --top_k=40 --top_p=1.0 + + python generate.py --base_model='distilgpt2' --prompt_type='plain' --debug=True --num_beams=1 --temperature=0.6 --top_k=40 --top_p=1.0 --share=False + python generate.py --base_model='t5-large' --prompt_type='simple_instruct' + python generate.py --base_model='philschmid/bart-large-cnn-samsum' + python generate.py --base_model='philschmid/flan-t5-base-samsum' + python generate.py --base_model='facebook/mbart-large-50-many-to-many-mmt' + + python generate.py --base_model='togethercomputer/GPT-NeoXT-Chat-Base-20B' --prompt_type='human_bot' --lora_weights='GPT-NeoXT-Chat-Base-20B.merged.json.8_epochs.57b2892c53df5b8cefac45f84d019cace803ef26.28' + + must have 4*48GB GPU and run without 8bit in order for sharding to work with use_gpu_id=False + can also pass --prompt_type='human_bot' and model can somewhat handle instructions without being instruct tuned + python generate.py --base_model=decapoda-research/llama-65b-hf --load_8bit=False --use_gpu_id=False --prompt_type='human_bot' + + python generate.py --base_model=h2oai/h2ogpt-oig-oasst1-512-6_9b + """ + H2O_Fire(main) + + +if __name__ == "__main__": + entrypoint_main() diff --git a/src/gpt4all_llm.py b/src/gpt4all_llm.py new file mode 100644 index 0000000000000000000000000000000000000000..5f973d42a7775d7f3e5a9c27e725429ca6d607e1 --- /dev/null +++ b/src/gpt4all_llm.py @@ -0,0 +1,403 @@ +import inspect +import os +from typing import Dict, Any, Optional, List, Iterator +from langchain.callbacks.manager import CallbackManagerForLLMRun +from langchain.schema.output import GenerationChunk +from pydantic import root_validator +from langchain.llms import gpt4all + +from utils import FakeTokenizer, get_ngpus_vis, url_alive, download_simple + + +def get_model_tokenizer_gpt4all(base_model, n_jobs=None, max_seq_len=None, llamacpp_dict=None): + assert llamacpp_dict is not None + # defaults (some of these are generation parameters, so need to be passed in at generation time) + model_name = base_model.lower() + model = get_llm_gpt4all(model_name, model=None, + # max_new_tokens=max_new_tokens, + # temperature=temperature, + # repetition_penalty=repetition_penalty, + # top_k=top_k, + # top_p=top_p, + # callbacks=callbacks, + n_jobs=n_jobs, + # verbose=verbose, + # streaming=stream_output, + # prompter=prompter, + # context=context, + # iinput=iinput, + inner_class=True, + max_seq_len=max_seq_len, + llamacpp_dict=llamacpp_dict, + ) + return model, FakeTokenizer(), 'cpu' + + +from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler + + +class H2OStreamingStdOutCallbackHandler(StreamingStdOutCallbackHandler): + + def on_llm_new_token(self, token: str, **kwargs: Any) -> None: + """Run on new LLM token. Only available when streaming is enabled.""" + # streaming to std already occurs without this + # sys.stdout.write(token) + # sys.stdout.flush() + pass + + +def get_model_kwargs(llamacpp_dict, default_kwargs, cls, exclude_list=[]): + # default from class + model_kwargs = {k: v.default for k, v in dict(inspect.signature(cls).parameters).items() if k not in exclude_list} + # from our defaults + model_kwargs.update(default_kwargs) + # from user defaults + model_kwargs.update(llamacpp_dict) + # ensure only valid keys + func_names = list(inspect.signature(cls).parameters) + model_kwargs = {k: v for k, v in model_kwargs.items() if k in func_names} + # make int or float if can to satisfy types for class + for k, v in model_kwargs.items(): + try: + if float(v) == int(v): + model_kwargs[k] = int(v) + else: + model_kwargs[k] = float(v) + except: + pass + return model_kwargs + + +def get_gpt4all_default_kwargs(max_new_tokens=256, + temperature=0.1, + repetition_penalty=1.0, + top_k=40, + top_p=0.7, + n_jobs=None, + verbose=False, + max_seq_len=None, + ): + if n_jobs in [None, -1]: + n_jobs = int(os.getenv('OMP_NUM_THREADS', str(os.cpu_count()//2))) + n_jobs = max(1, min(20, n_jobs)) # hurts beyond some point + n_gpus = get_ngpus_vis() + default_kwargs = dict(context_erase=0.5, + n_batch=1, + max_tokens=max_seq_len - max_new_tokens, + n_predict=max_new_tokens, + repeat_last_n=64 if repetition_penalty != 1.0 else 0, + repeat_penalty=repetition_penalty, + temp=temperature, + temperature=temperature, + top_k=top_k, + top_p=top_p, + use_mlock=True, + n_ctx=max_seq_len, + n_threads=n_jobs, + verbose=verbose) + if n_gpus != 0: + default_kwargs.update(dict(n_gpu_layers=100)) + return default_kwargs + + +def get_llm_gpt4all(model_name, + model=None, + max_new_tokens=256, + temperature=0.1, + repetition_penalty=1.0, + top_k=40, + top_p=0.7, + streaming=False, + callbacks=None, + prompter=None, + context='', + iinput='', + n_jobs=None, + verbose=False, + inner_class=False, + max_seq_len=None, + llamacpp_dict=None, + ): + if not inner_class: + assert prompter is not None + + default_kwargs = \ + get_gpt4all_default_kwargs(max_new_tokens=max_new_tokens, + temperature=temperature, + repetition_penalty=repetition_penalty, + top_k=top_k, + top_p=top_p, + n_jobs=n_jobs, + verbose=verbose, + max_seq_len=max_seq_len, + ) + if model_name == 'llama': + cls = H2OLlamaCpp + if model is None: + llamacpp_dict = llamacpp_dict.copy() + model_path = llamacpp_dict.pop('model_path_llama') + if os.path.isfile(os.path.basename(model_path)): + # e.g. if offline but previously downloaded + model_path = os.path.basename(model_path) + elif url_alive(model_path): + # online + ggml_path = os.getenv('GGML_PATH') + dest = os.path.join(ggml_path, os.path.basename(model_path)) if ggml_path else None + model_path = download_simple(model_path, dest=dest) + else: + model_path = model + model_kwargs = get_model_kwargs(llamacpp_dict, default_kwargs, cls, exclude_list=['lc_kwargs']) + model_kwargs.update(dict(model_path=model_path, callbacks=callbacks, streaming=streaming, + prompter=prompter, context=context, iinput=iinput)) + + # migration to new langchain fix: + odd_keys = ['model_kwargs', 'grammar_path', 'grammar'] + for key in odd_keys: + model_kwargs.pop(key, None) + + llm = cls(**model_kwargs) + llm.client.verbose = verbose + inner_model = llm.client + elif model_name == 'gpt4all_llama': + cls = H2OGPT4All + if model is None: + llamacpp_dict = llamacpp_dict.copy() + model_path = llamacpp_dict.pop('model_name_gpt4all_llama') + if url_alive(model_path): + # online + ggml_path = os.getenv('GGML_PATH') + dest = os.path.join(ggml_path, os.path.basename(model_path)) if ggml_path else None + model_path = download_simple(model_path, dest=dest) + else: + model_path = model + model_kwargs = get_model_kwargs(llamacpp_dict, default_kwargs, cls, exclude_list=['lc_kwargs']) + model_kwargs.update( + dict(model=model_path, backend='llama', callbacks=callbacks, streaming=streaming, + prompter=prompter, context=context, iinput=iinput)) + llm = cls(**model_kwargs) + inner_model = llm.client + elif model_name == 'gptj': + cls = H2OGPT4All + if model is None: + llamacpp_dict = llamacpp_dict.copy() + model_path = llamacpp_dict.pop('model_name_gptj') if model is None else model + if url_alive(model_path): + ggml_path = os.getenv('GGML_PATH') + dest = os.path.join(ggml_path, os.path.basename(model_path)) if ggml_path else None + model_path = download_simple(model_path, dest=dest) + else: + model_path = model + model_kwargs = get_model_kwargs(llamacpp_dict, default_kwargs, cls, exclude_list=['lc_kwargs']) + model_kwargs.update( + dict(model=model_path, backend='gptj', callbacks=callbacks, streaming=streaming, + prompter=prompter, context=context, iinput=iinput)) + llm = cls(**model_kwargs) + inner_model = llm.client + else: + raise RuntimeError("No such model_name %s" % model_name) + if inner_class: + return inner_model + else: + return llm + + +class H2OGPT4All(gpt4all.GPT4All): + model: Any + prompter: Any + context: Any = '' + iinput: Any = '' + """Path to the pre-trained GPT4All model file.""" + + @root_validator() + def validate_environment(cls, values: Dict) -> Dict: + """Validate that the python package exists in the environment.""" + try: + if isinstance(values["model"], str): + from gpt4all import GPT4All as GPT4AllModel + + full_path = values["model"] + model_path, delimiter, model_name = full_path.rpartition("/") + model_path += delimiter + + values["client"] = GPT4AllModel( + model_name=model_name, + model_path=model_path or None, + model_type=values["backend"], + allow_download=True, + ) + if values["n_threads"] is not None: + # set n_threads + values["client"].model.set_thread_count(values["n_threads"]) + else: + values["client"] = values["model"] + if values["n_threads"] is not None: + # set n_threads + values["client"].model.set_thread_count(values["n_threads"]) + try: + values["backend"] = values["client"].model_type + except AttributeError: + # The below is for compatibility with GPT4All Python bindings <= 0.2.3. + values["backend"] = values["client"].model.model_type + + except ImportError: + raise ValueError( + "Could not import gpt4all python package. " + "Please install it with `pip install gpt4all`." + ) + return values + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs, + ) -> str: + # Roughly 4 chars per token if natural language + n_ctx = 2048 + prompt = prompt[-self.max_tokens * 4:] + + # use instruct prompting + data_point = dict(context=self.context, instruction=prompt, input=self.iinput) + prompt = self.prompter.generate_prompt(data_point) + + verbose = False + if verbose: + print("_call prompt: %s" % prompt, flush=True) + # FIXME: GPT4ALl doesn't support yield during generate, so cannot support streaming except via itself to stdout + return super()._call(prompt, stop=stop, run_manager=run_manager) + + # FIXME: Unsure what uses + #def get_token_ids(self, text: str) -> List[int]: + # return self.client.tokenize(b" " + text.encode("utf-8")) + + +from langchain.llms import LlamaCpp + + +class H2OLlamaCpp(LlamaCpp): + model_path: Any + prompter: Any + context: Any + iinput: Any + """Path to the pre-trained GPT4All model file.""" + + @root_validator() + def validate_environment(cls, values: Dict) -> Dict: + """Validate that llama-cpp-python library is installed.""" + if isinstance(values["model_path"], str): + model_path = values["model_path"] + model_param_names = [ + "lora_path", + "lora_base", + "n_ctx", + "n_parts", + "seed", + "f16_kv", + "logits_all", + "vocab_only", + "use_mlock", + "n_threads", + "n_batch", + "use_mmap", + "last_n_tokens_size", + ] + model_params = {k: values[k] for k in model_param_names} + # For backwards compatibility, only include if non-null. + if values["n_gpu_layers"] is not None: + model_params["n_gpu_layers"] = values["n_gpu_layers"] + + try: + try: + from llama_cpp import Llama + except ImportError: + from llama_cpp_cuda import Llama + + values["client"] = Llama(model_path, **model_params) + except ImportError: + raise ModuleNotFoundError( + "Could not import llama-cpp-python library. " + "Please install the llama-cpp-python library to " + "use this embedding model: pip install llama-cpp-python" + ) + except Exception as e: + raise ValueError( + f"Could not load Llama model from path: {model_path}. " + f"Received error {e}" + ) + else: + values["client"] = values["model_path"] + return values + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs, + ) -> str: + verbose = False + # tokenize twice, just to count tokens, since llama cpp python wrapper has no way to truncate + # still have to avoid crazy sizes, else hit llama_tokenize: too many tokens -- might still hit, not fatal + prompt = prompt[-self.n_ctx * 4:] + prompt_tokens = self.client.tokenize(b" " + prompt.encode("utf-8")) + num_prompt_tokens = len(prompt_tokens) + if num_prompt_tokens > self.n_ctx: + # conservative by using int() + chars_per_token = int(len(prompt) / num_prompt_tokens) + prompt = prompt[-self.n_ctx * chars_per_token:] + if verbose: + print("reducing tokens, assuming average of %s chars/token: %s" % chars_per_token, flush=True) + prompt_tokens2 = self.client.tokenize(b" " + prompt.encode("utf-8")) + num_prompt_tokens2 = len(prompt_tokens2) + print("reduced tokens from %d -> %d" % (num_prompt_tokens, num_prompt_tokens2), flush=True) + + # use instruct prompting + data_point = dict(context=self.context, instruction=prompt, input=self.iinput) + prompt = self.prompter.generate_prompt(data_point) + + if verbose: + print("_call prompt: %s" % prompt, flush=True) + + if self.streaming: + # parent handler of streamer expects to see prompt first else output="" and lose if prompt=None in prompter + text = "" + for token in self.stream(input=prompt, stop=stop): + # for token in self.stream(input=prompt, stop=stop, run_manager=run_manager): + text_chunk = token # ["choices"][0]["text"] + # self.stream already calls text_callback + # if text_callback: + # text_callback(text_chunk) + text += text_chunk + # parent handler of streamer expects to see prompt first else output="" and lose if prompt=None in prompter + return text[len(prompt):] + else: + params = self._get_parameters(stop) + params = {**params, **kwargs} + result = self.client(prompt=prompt, **params) + return result["choices"][0]["text"] + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + # parent handler of streamer expects to see prompt first else output="" and lose if prompt=None in prompter + logprobs = 0 + chunk = GenerationChunk( + text=prompt, + generation_info={"logprobs": logprobs}, + ) + yield chunk + if run_manager: + run_manager.on_llm_new_token( + token=chunk.text, verbose=self.verbose, log_probs=logprobs + ) + # actual new tokens + for chunk in super()._stream(prompt, stop=stop, run_manager=run_manager, **kwargs): + yield chunk + + def get_token_ids(self, text: str) -> List[int]: + return self.client.tokenize(b" " + text.encode("utf-8")) diff --git a/src/gpt_langchain.py b/src/gpt_langchain.py new file mode 100644 index 0000000000000000000000000000000000000000..144d9ec5c3783430db8c0714828028137ceac94d --- /dev/null +++ b/src/gpt_langchain.py @@ -0,0 +1,5394 @@ +import ast +import asyncio +import copy +import functools +import glob +import gzip +import inspect +import json +import os +import pathlib +import pickle +import shutil +import subprocess +import tempfile +import time +import traceback +import types +import typing +import urllib.error +import uuid +import zipfile +from collections import defaultdict +from datetime import datetime +from functools import reduce +from operator import concat +import filelock +import tabulate +import yaml + +from joblib import delayed +from langchain.callbacks import streaming_stdout +from langchain.embeddings import HuggingFaceInstructEmbeddings +from langchain.llms.huggingface_pipeline import VALID_TASKS +from langchain.llms.utils import enforce_stop_tokens +from langchain.schema import LLMResult, Generation +from langchain.tools import PythonREPLTool +from langchain.tools.json.tool import JsonSpec +from tqdm import tqdm + +from src.db_utils import length_db1, set_dbid, set_userid, get_dbid, get_userid_direct, get_username_direct, \ + set_userid_direct +from utils import wrapped_partial, EThread, import_matplotlib, sanitize_filename, makedirs, get_url, flatten_list, \ + get_device, ProgressParallel, remove, hash_file, clear_torch_cache, NullContext, get_hf_server, FakeTokenizer, \ + have_libreoffice, have_arxiv, have_playwright, have_selenium, have_tesseract, have_doctr, have_pymupdf, set_openai, \ + get_list_or_str, have_pillow, only_selenium, only_playwright, only_unstructured_urls, get_sha, get_short_name, \ + get_accordion, have_jq, get_doc, get_source, have_chromamigdb, get_token_count, reverse_ucurve_list +from enums import DocumentSubset, no_lora_str, model_token_mapping, source_prefix, source_postfix, non_query_commands, \ + LangChainAction, LangChainMode, DocumentChoice, LangChainTypes, font_size, head_acc, super_source_prefix, \ + super_source_postfix, langchain_modes_intrinsic, get_langchain_prompts, LangChainAgent +from evaluate_params import gen_hyper, gen_hyper0 +from gen import get_model, SEED, get_limited_prompt, get_docs_tokens +from prompter import non_hf_types, PromptType, Prompter +from src.serpapi import H2OSerpAPIWrapper +from utils_langchain import StreamingGradioCallbackHandler, _chunk_sources, _add_meta, add_parser, fix_json_meta + +import_matplotlib() + +import numpy as np +import pandas as pd +import requests +from langchain.chains.qa_with_sources import load_qa_with_sources_chain +# , GCSDirectoryLoader, GCSFileLoader +# , OutlookMessageLoader # GPL3 +# ImageCaptionLoader, # use our own wrapper +# ReadTheDocsLoader, # no special file, some path, so have to give as special option +from langchain.document_loaders import PyPDFLoader, TextLoader, CSVLoader, PythonLoader, TomlLoader, \ + UnstructuredURLLoader, UnstructuredHTMLLoader, UnstructuredWordDocumentLoader, UnstructuredMarkdownLoader, \ + EverNoteLoader, UnstructuredEmailLoader, UnstructuredODTLoader, UnstructuredPowerPointLoader, \ + UnstructuredEPubLoader, UnstructuredImageLoader, UnstructuredRTFLoader, ArxivLoader, UnstructuredPDFLoader, \ + UnstructuredExcelLoader, JSONLoader +from langchain.text_splitter import Language +from langchain.chains.question_answering import load_qa_chain +from langchain.docstore.document import Document +from langchain import PromptTemplate, HuggingFaceTextGenInference, HuggingFacePipeline +from langchain.vectorstores import Chroma +from chromamig import ChromaMig + + +def split_list(input_list, split_size): + for i in range(0, len(input_list), split_size): + yield input_list[i:i + split_size] + + +def get_db(sources, use_openai_embedding=False, db_type='faiss', + persist_directory=None, load_db_if_exists=True, + langchain_mode='notset', + langchain_mode_paths={}, + langchain_mode_types={}, + collection_name=None, + hf_embedding_model=None, + migrate_embedding_model=False, + auto_migrate_db=False, + n_jobs=-1): + if not sources: + return None + user_path = langchain_mode_paths.get(langchain_mode) + if persist_directory is None: + langchain_type = langchain_mode_types.get(langchain_mode, LangChainTypes.EITHER.value) + persist_directory, langchain_type = get_persist_directory(langchain_mode, langchain_type=langchain_type) + langchain_mode_types[langchain_mode] = langchain_type + assert hf_embedding_model is not None + + # get freshly-determined embedding model + embedding = get_embedding(use_openai_embedding, hf_embedding_model=hf_embedding_model) + assert collection_name is not None or langchain_mode != 'notset' + if collection_name is None: + collection_name = langchain_mode.replace(' ', '_') + + # Create vector database + if db_type == 'faiss': + from langchain.vectorstores import FAISS + db = FAISS.from_documents(sources, embedding) + elif db_type == 'weaviate': + import weaviate + from weaviate.embedded import EmbeddedOptions + from langchain.vectorstores import Weaviate + + if os.getenv('WEAVIATE_URL', None): + client = _create_local_weaviate_client() + else: + client = weaviate.Client( + embedded_options=EmbeddedOptions(persistence_data_path=persist_directory) + ) + index_name = collection_name.capitalize() + db = Weaviate.from_documents(documents=sources, embedding=embedding, client=client, by_text=False, + index_name=index_name) + elif db_type in ['chroma', 'chroma_old']: + assert persist_directory is not None + # use_base already handled when making persist_directory, unless was passed into get_db() + makedirs(persist_directory, exist_ok=True) + + # see if already actually have persistent db, and deal with possible changes in embedding + db, use_openai_embedding, hf_embedding_model = \ + get_existing_db(None, persist_directory, load_db_if_exists, db_type, + use_openai_embedding, + langchain_mode, langchain_mode_paths, langchain_mode_types, + hf_embedding_model, migrate_embedding_model, auto_migrate_db, + verbose=False, + n_jobs=n_jobs) + if db is None: + import logging + logging.getLogger("chromadb").setLevel(logging.ERROR) + if db_type == 'chroma': + from chromadb.config import Settings + settings_extra_kwargs = dict(is_persistent=True) + else: + from chromamigdb.config import Settings + settings_extra_kwargs = dict(chroma_db_impl="duckdb+parquet") + client_settings = Settings(anonymized_telemetry=False, + persist_directory=persist_directory, + **settings_extra_kwargs) + if n_jobs in [None, -1]: + n_jobs = int(os.getenv('OMP_NUM_THREADS', str(os.cpu_count() // 2))) + num_threads = max(1, min(n_jobs, 8)) + else: + num_threads = max(1, n_jobs) + collection_metadata = {"hnsw:num_threads": num_threads} + from_kwargs = dict(embedding=embedding, + persist_directory=persist_directory, + collection_name=collection_name, + client_settings=client_settings, + collection_metadata=collection_metadata) + if db_type == 'chroma': + import chromadb + api = chromadb.PersistentClient(path=persist_directory) + max_batch_size = api._producer.max_batch_size + sources_batches = split_list(sources, max_batch_size) + for sources_batch in sources_batches: + db = Chroma.from_documents(documents=sources_batch, **from_kwargs) + db.persist() + else: + db = ChromaMig.from_documents(documents=sources, **from_kwargs) + clear_embedding(db) + save_embed(db, use_openai_embedding, hf_embedding_model) + else: + # then just add + # doesn't check or change embedding, just saves it in case not saved yet, after persisting + db, num_new_sources, new_sources_metadata = add_to_db(db, sources, db_type=db_type, + use_openai_embedding=use_openai_embedding, + hf_embedding_model=hf_embedding_model) + else: + raise RuntimeError("No such db_type=%s" % db_type) + + # once here, db is not changing and embedding choices in calling functions does not matter + return db + + +def _get_unique_sources_in_weaviate(db): + batch_size = 100 + id_source_list = [] + result = db._client.data_object.get(class_name=db._index_name, limit=batch_size) + + while result['objects']: + id_source_list += [(obj['id'], obj['properties']['source']) for obj in result['objects']] + last_id = id_source_list[-1][0] + result = db._client.data_object.get(class_name=db._index_name, limit=batch_size, after=last_id) + + unique_sources = {source for _, source in id_source_list} + return unique_sources + + +def del_from_db(db, sources, db_type=None): + if db_type in ['chroma', 'chroma_old'] and db is not None: + # sources should be list of x.metadata['source'] from document metadatas + if isinstance(sources, str): + sources = [sources] + else: + assert isinstance(sources, (list, tuple, types.GeneratorType)) + metadatas = set(sources) + client_collection = db._client.get_collection(name=db._collection.name, + embedding_function=db._collection._embedding_function) + for source in metadatas: + meta = dict(source=source) + try: + client_collection.delete(where=meta) + except KeyError: + pass + + +def add_to_db(db, sources, db_type='faiss', + avoid_dup_by_file=False, + avoid_dup_by_content=True, + use_openai_embedding=False, + hf_embedding_model=None): + assert hf_embedding_model is not None + num_new_sources = len(sources) + if not sources: + return db, num_new_sources, [] + if db_type == 'faiss': + db.add_documents(sources) + elif db_type == 'weaviate': + # FIXME: only control by file name, not hash yet + if avoid_dup_by_file or avoid_dup_by_content: + unique_sources = _get_unique_sources_in_weaviate(db) + sources = [x for x in sources if x.metadata['source'] not in unique_sources] + num_new_sources = len(sources) + if num_new_sources == 0: + return db, num_new_sources, [] + db.add_documents(documents=sources) + elif db_type in ['chroma', 'chroma_old']: + collection = get_documents(db) + # files we already have: + metadata_files = set([x['source'] for x in collection['metadatas']]) + if avoid_dup_by_file: + # Too weak in case file changed content, assume parent shouldn't pass true for this for now + raise RuntimeError("Not desired code path") + if avoid_dup_by_content: + # look at hash, instead of page_content + # migration: If no hash previously, avoid updating, + # since don't know if need to update and may be expensive to redo all unhashed files + metadata_hash_ids = set( + [x['hashid'] for x in collection['metadatas'] if 'hashid' in x and x['hashid'] not in ["None", None]]) + # avoid sources with same hash + sources = [x for x in sources if x.metadata.get('hashid') not in metadata_hash_ids] + num_nohash = len([x for x in sources if not x.metadata.get('hashid')]) + print("Found %s new sources (%d have no hash in original source," + " so have to reprocess for migration to sources with hash)" % (len(sources), num_nohash), flush=True) + # get new file names that match existing file names. delete existing files we are overridding + dup_metadata_files = set([x.metadata['source'] for x in sources if x.metadata['source'] in metadata_files]) + print("Removing %s duplicate files from db because ingesting those as new documents" % len( + dup_metadata_files), flush=True) + client_collection = db._client.get_collection(name=db._collection.name, + embedding_function=db._collection._embedding_function) + for dup_file in dup_metadata_files: + dup_file_meta = dict(source=dup_file) + try: + client_collection.delete(where=dup_file_meta) + except KeyError: + pass + num_new_sources = len(sources) + if num_new_sources == 0: + return db, num_new_sources, [] + if hasattr(db, '_persist_directory'): + print("Existing db, adding to %s" % db._persist_directory, flush=True) + # chroma only + lock_file = get_db_lock_file(db) + context = filelock.FileLock + else: + lock_file = None + context = NullContext + with context(lock_file): + # this is place where add to db, but others maybe accessing db, so lock access. + # else see RuntimeError: Index seems to be corrupted or unsupported + import chromadb + api = chromadb.PersistentClient(path=db._persist_directory) + max_batch_size = api._producer.max_batch_size + sources_batches = split_list(sources, max_batch_size) + for sources_batch in sources_batches: + db.add_documents(documents=sources_batch) + db.persist() + clear_embedding(db) + # save here is for migration, in case old db directory without embedding saved + save_embed(db, use_openai_embedding, hf_embedding_model) + else: + raise RuntimeError("No such db_type=%s" % db_type) + + new_sources_metadata = [x.metadata for x in sources] + + return db, num_new_sources, new_sources_metadata + + +def create_or_update_db(db_type, persist_directory, collection_name, + user_path, langchain_type, + sources, use_openai_embedding, add_if_exists, verbose, + hf_embedding_model, migrate_embedding_model, auto_migrate_db, + n_jobs=-1): + if not os.path.isdir(persist_directory) or not add_if_exists: + if os.path.isdir(persist_directory): + if verbose: + print("Removing %s" % persist_directory, flush=True) + remove(persist_directory) + if verbose: + print("Generating db", flush=True) + if db_type == 'weaviate': + import weaviate + from weaviate.embedded import EmbeddedOptions + + if os.getenv('WEAVIATE_URL', None): + client = _create_local_weaviate_client() + else: + client = weaviate.Client( + embedded_options=EmbeddedOptions(persistence_data_path=persist_directory) + ) + + index_name = collection_name.replace(' ', '_').capitalize() + if client.schema.exists(index_name) and not add_if_exists: + client.schema.delete_class(index_name) + if verbose: + print("Removing %s" % index_name, flush=True) + elif db_type in ['chroma', 'chroma_old']: + pass + + if not add_if_exists: + if verbose: + print("Generating db", flush=True) + else: + if verbose: + print("Loading and updating db", flush=True) + + db = get_db(sources, + use_openai_embedding=use_openai_embedding, + db_type=db_type, + persist_directory=persist_directory, + langchain_mode=collection_name, + langchain_mode_paths={collection_name: user_path}, + langchain_mode_types={collection_name: langchain_type}, + hf_embedding_model=hf_embedding_model, + migrate_embedding_model=migrate_embedding_model, + auto_migrate_db=auto_migrate_db, + n_jobs=n_jobs) + + return db + + +from langchain.embeddings import FakeEmbeddings + + +class H2OFakeEmbeddings(FakeEmbeddings): + """Fake embedding model, but constant instead of random""" + + size: int + """The size of the embedding vector.""" + + def _get_embedding(self) -> typing.List[float]: + return [1] * self.size + + def embed_documents(self, texts: typing.List[str]) -> typing.List[typing.List[float]]: + return [self._get_embedding() for _ in texts] + + def embed_query(self, text: str) -> typing.List[float]: + return self._get_embedding() + + +def get_embedding(use_openai_embedding, hf_embedding_model=None, preload=False): + assert hf_embedding_model is not None + # Get embedding model + if use_openai_embedding: + assert os.getenv("OPENAI_API_KEY") is not None, "Set ENV OPENAI_API_KEY" + from langchain.embeddings import OpenAIEmbeddings + embedding = OpenAIEmbeddings(disallowed_special=()) + elif hf_embedding_model == 'fake': + embedding = H2OFakeEmbeddings(size=1) + else: + if isinstance(hf_embedding_model, str): + pass + elif isinstance(hf_embedding_model, dict): + # embedding itself preloaded globally + return hf_embedding_model['model'] + else: + # object + return hf_embedding_model + # to ensure can fork without deadlock + from langchain.embeddings import HuggingFaceEmbeddings + + device, torch_dtype, context_class = get_device_dtype() + model_kwargs = dict(device=device) + if 'instructor' in hf_embedding_model: + encode_kwargs = {'normalize_embeddings': True} + embedding = HuggingFaceInstructEmbeddings(model_name=hf_embedding_model, + model_kwargs=model_kwargs, + encode_kwargs=encode_kwargs) + else: + embedding = HuggingFaceEmbeddings(model_name=hf_embedding_model, model_kwargs=model_kwargs) + embedding.client.preload = preload + return embedding + + +def get_answer_from_sources(chain, sources, question): + return chain( + { + "input_documents": sources, + "question": question, + }, + return_only_outputs=True, + )["output_text"] + + +"""Wrapper around Huggingface text generation inference API.""" +from functools import partial +from typing import Any, Dict, List, Optional, Set, Iterable + +from pydantic import Extra, Field, root_validator + +from langchain.callbacks.manager import CallbackManagerForLLMRun, AsyncCallbackManagerForLLMRun +from langchain.llms.base import LLM + + +class GradioInference(LLM): + """ + Gradio generation inference API. + """ + inference_server_url: str = "" + + temperature: float = 0.8 + top_p: Optional[float] = 0.95 + top_k: Optional[int] = None + num_beams: Optional[int] = 1 + max_new_tokens: int = 512 + min_new_tokens: int = 1 + early_stopping: bool = False + max_time: int = 180 + repetition_penalty: Optional[float] = None + num_return_sequences: Optional[int] = 1 + do_sample: bool = False + chat_client: bool = False + + return_full_text: bool = False + stream_output: bool = False + sanitize_bot_response: bool = False + + prompter: Any = None + context: Any = '' + iinput: Any = '' + client: Any = None + tokenizer: Any = None + + system_prompt: Any = None + visible_models: Any = None + h2ogpt_key: Any = None + + count_input_tokens: Any = 0 + count_output_tokens: Any = 0 + + min_max_new_tokens: Any = 256 + + class Config: + """Configuration for this pydantic object.""" + + extra = Extra.forbid + + @root_validator() + def validate_environment(cls, values: Dict) -> Dict: + """Validate that python package exists in environment.""" + + try: + if values['client'] is None: + import gradio_client + values["client"] = gradio_client.Client( + values["inference_server_url"] + ) + except ImportError: + raise ImportError( + "Could not import gradio_client python package. " + "Please install it with `pip install gradio_client`." + ) + return values + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "gradio_inference" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + # NOTE: prompt here has no prompt_type (e.g. human: bot:) prompt injection, + # so server should get prompt_type or '', not plain + # This is good, so gradio server can also handle stopping.py conditions + # this is different than TGI server that uses prompter to inject prompt_type prompting + stream_output = self.stream_output + gr_client = self.client + client_langchain_mode = 'Disabled' + client_add_chat_history_to_context = True + client_add_search_to_context = False + client_chat_conversation = [] + client_langchain_action = LangChainAction.QUERY.value + client_langchain_agents = [] + top_k_docs = 1 + chunk = True + chunk_size = 512 + client_kwargs = dict(instruction=prompt if self.chat_client else '', # only for chat=True + iinput=self.iinput if self.chat_client else '', # only for chat=True + context=self.context, + # streaming output is supported, loops over and outputs each generation in streaming mode + # but leave stream_output=False for simple input/output mode + stream_output=stream_output, + prompt_type=self.prompter.prompt_type, + prompt_dict='', + + temperature=self.temperature, + top_p=self.top_p, + top_k=self.top_k, + num_beams=self.num_beams, + max_new_tokens=self.max_new_tokens, + min_new_tokens=self.min_new_tokens, + early_stopping=self.early_stopping, + max_time=self.max_time, + repetition_penalty=self.repetition_penalty, + num_return_sequences=self.num_return_sequences, + do_sample=self.do_sample, + chat=self.chat_client, + + instruction_nochat=prompt if not self.chat_client else '', + iinput_nochat=self.iinput if not self.chat_client else '', + langchain_mode=client_langchain_mode, + add_chat_history_to_context=client_add_chat_history_to_context, + langchain_action=client_langchain_action, + langchain_agents=client_langchain_agents, + top_k_docs=top_k_docs, + chunk=chunk, + chunk_size=chunk_size, + document_subset=DocumentSubset.Relevant.name, + document_choice=[DocumentChoice.ALL.value], + pre_prompt_query=None, + prompt_query=None, + pre_prompt_summary=None, + prompt_summary=None, + system_prompt=self.system_prompt, + image_loaders=None, # don't need to further do doc specific things + pdf_loaders=None, # don't need to further do doc specific things + url_loaders=None, # don't need to further do doc specific things + jq_schema=None, # don't need to further do doc specific things + visible_models=self.visible_models, + h2ogpt_key=self.h2ogpt_key, + add_search_to_context=client_add_search_to_context, + chat_conversation=client_chat_conversation, + text_context_list=None, + docs_ordering_type=None, + min_max_new_tokens=self.min_max_new_tokens, + ) + api_name = '/submit_nochat_api' # NOTE: like submit_nochat but stable API for string dict passing + self.count_input_tokens += self.get_num_tokens(prompt) + + if not stream_output: + res = gr_client.predict(str(dict(client_kwargs)), api_name=api_name) + res_dict = ast.literal_eval(res) + text = res_dict['response'] + ret = self.prompter.get_response(prompt + text, prompt=prompt, + sanitize_bot_response=self.sanitize_bot_response) + self.count_output_tokens += self.get_num_tokens(ret) + return ret + else: + text_callback = None + if run_manager: + text_callback = partial( + run_manager.on_llm_new_token, verbose=self.verbose + ) + + job = gr_client.submit(str(dict(client_kwargs)), api_name=api_name) + text0 = '' + while not job.done(): + if job.communicator.job.latest_status.code.name == 'FINISHED': + break + e = job.future._exception + if e is not None: + break + outputs_list = job.communicator.job.outputs + if outputs_list: + res = job.communicator.job.outputs[-1] + res_dict = ast.literal_eval(res) + text = res_dict['response'] + text = self.prompter.get_response(prompt + text, prompt=prompt, + sanitize_bot_response=self.sanitize_bot_response) + # FIXME: derive chunk from full for now + text_chunk = text[len(text0):] + if not text_chunk: + continue + # save old + text0 = text + + if text_callback: + text_callback(text_chunk) + + time.sleep(0.01) + + # ensure get last output to avoid race + res_all = job.outputs() + if len(res_all) > 0: + res = res_all[-1] + res_dict = ast.literal_eval(res) + text = res_dict['response'] + # FIXME: derive chunk from full for now + else: + # go with old if failure + text = text0 + text_chunk = text[len(text0):] + if text_callback: + text_callback(text_chunk) + ret = self.prompter.get_response(prompt + text, prompt=prompt, + sanitize_bot_response=self.sanitize_bot_response) + self.count_output_tokens += self.get_num_tokens(ret) + return ret + + def get_token_ids(self, text: str) -> List[int]: + return self.tokenizer.encode(text) + # avoid base method that is not aware of how to properly tokenize (uses GPT2) + # return _get_token_ids_default_method(text) + + +class H2OHuggingFaceTextGenInference(HuggingFaceTextGenInference): + max_new_tokens: int = 512 + do_sample: bool = False + top_k: Optional[int] = None + top_p: Optional[float] = 0.95 + typical_p: Optional[float] = 0.95 + temperature: float = 0.8 + repetition_penalty: Optional[float] = None + return_full_text: bool = False + stop_sequences: List[str] = Field(default_factory=list) + seed: Optional[int] = None + inference_server_url: str = "" + timeout: int = 300 + headers: dict = None + stream_output: bool = False + sanitize_bot_response: bool = False + prompter: Any = None + context: Any = '' + iinput: Any = '' + tokenizer: Any = None + async_sem: Any = None + count_input_tokens: Any = 0 + count_output_tokens: Any = 0 + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + if stop is None: + stop = self.stop_sequences.copy() + else: + stop += self.stop_sequences.copy() + stop_tmp = stop.copy() + stop = [] + [stop.append(x) for x in stop_tmp if x not in stop] + + # HF inference server needs control over input tokens + assert self.tokenizer is not None + from h2oai_pipeline import H2OTextGenerationPipeline + prompt, num_prompt_tokens = H2OTextGenerationPipeline.limit_prompt(prompt, self.tokenizer) + + # NOTE: TGI server does not add prompting, so must do here + data_point = dict(context=self.context, instruction=prompt, input=self.iinput) + prompt = self.prompter.generate_prompt(data_point) + self.count_input_tokens += self.get_num_tokens(prompt) + + gen_server_kwargs = dict(do_sample=self.do_sample, + stop_sequences=stop, + max_new_tokens=self.max_new_tokens, + top_k=self.top_k, + top_p=self.top_p, + typical_p=self.typical_p, + temperature=self.temperature, + repetition_penalty=self.repetition_penalty, + return_full_text=self.return_full_text, + seed=self.seed, + ) + gen_server_kwargs.update(kwargs) + + # lower bound because client is re-used if multi-threading + self.client.timeout = max(300, self.timeout) + + if not self.stream_output: + res = self.client.generate( + prompt, + **gen_server_kwargs, + ) + if self.return_full_text: + gen_text = res.generated_text[len(prompt):] + else: + gen_text = res.generated_text + # remove stop sequences from the end of the generated text + for stop_seq in stop: + if stop_seq in gen_text: + gen_text = gen_text[:gen_text.index(stop_seq)] + text = prompt + gen_text + text = self.prompter.get_response(text, prompt=prompt, + sanitize_bot_response=self.sanitize_bot_response) + else: + text_callback = None + if run_manager: + text_callback = partial( + run_manager.on_llm_new_token, verbose=self.verbose + ) + # parent handler of streamer expects to see prompt first else output="" and lose if prompt=None in prompter + if text_callback: + text_callback(prompt) + text = "" + # Note: Streaming ignores return_full_text=True + for response in self.client.generate_stream(prompt, **gen_server_kwargs): + text_chunk = response.token.text + text += text_chunk + text = self.prompter.get_response(prompt + text, prompt=prompt, + sanitize_bot_response=self.sanitize_bot_response) + # stream part + is_stop = False + for stop_seq in stop: + if stop_seq in text_chunk: + is_stop = True + break + if is_stop: + break + if not response.token.special: + if text_callback: + text_callback(text_chunk) + self.count_output_tokens += self.get_num_tokens(text) + return text + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + # print("acall", flush=True) + if stop is None: + stop = self.stop_sequences.copy() + else: + stop += self.stop_sequences.copy() + stop_tmp = stop.copy() + stop = [] + [stop.append(x) for x in stop_tmp if x not in stop] + + # HF inference server needs control over input tokens + assert self.tokenizer is not None + from h2oai_pipeline import H2OTextGenerationPipeline + prompt, num_prompt_tokens = H2OTextGenerationPipeline.limit_prompt(prompt, self.tokenizer) + + # NOTE: TGI server does not add prompting, so must do here + data_point = dict(context=self.context, instruction=prompt, input=self.iinput) + prompt = self.prompter.generate_prompt(data_point) + + gen_text = await super()._acall(prompt, stop=stop, run_manager=run_manager, **kwargs) + + # remove stop sequences from the end of the generated text + for stop_seq in stop: + if stop_seq in gen_text: + gen_text = gen_text[:gen_text.index(stop_seq)] + text = prompt + gen_text + text = self.prompter.get_response(text, prompt=prompt, + sanitize_bot_response=self.sanitize_bot_response) + # print("acall done", flush=True) + return text + + async def _agenerate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Run the LLM on the given prompt and input.""" + generations = [] + new_arg_supported = inspect.signature(self._acall).parameters.get("run_manager") + self.count_input_tokens += sum([self.get_num_tokens(prompt) for prompt in prompts]) + tasks = [ + asyncio.ensure_future(self._agenerate_one(prompt, stop=stop, run_manager=run_manager, + new_arg_supported=new_arg_supported, **kwargs)) + for prompt in prompts + ] + texts = await asyncio.gather(*tasks) + self.count_output_tokens += sum([self.get_num_tokens(text) for text in texts]) + [generations.append([Generation(text=text)]) for text in texts] + return LLMResult(generations=generations) + + async def _agenerate_one( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + new_arg_supported=None, + **kwargs: Any, + ) -> str: + async with self.async_sem: # semaphore limits num of simultaneous downloads + return await self._acall(prompt, stop=stop, run_manager=run_manager, **kwargs) \ + if new_arg_supported else \ + await self._acall(prompt, stop=stop, **kwargs) + + def get_token_ids(self, text: str) -> List[int]: + return self.tokenizer.encode(text) + # avoid base method that is not aware of how to properly tokenize (uses GPT2) + # return _get_token_ids_default_method(text) + + +from langchain.chat_models import ChatOpenAI, AzureChatOpenAI +from langchain.llms import OpenAI, AzureOpenAI, Replicate +from langchain.llms.openai import _streaming_response_template, completion_with_retry, _update_response, \ + update_token_usage + + +class H2OOpenAI(OpenAI): + """ + New class to handle vLLM's use of OpenAI, no vllm_chat supported, so only need here + Handles prompting that OpenAI doesn't need, stopping as well + """ + stop_sequences: Any = None + sanitize_bot_response: bool = False + prompter: Any = None + context: Any = '' + iinput: Any = '' + tokenizer: Any = None + + @classmethod + def _all_required_field_names(cls) -> Set: + _all_required_field_names = super(OpenAI, cls)._all_required_field_names() + _all_required_field_names.update( + {'top_p', 'frequency_penalty', 'presence_penalty', 'stop_sequences', 'sanitize_bot_response', 'prompter', + 'tokenizer', 'logit_bias'}) + return _all_required_field_names + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + stop_tmp = self.stop_sequences if not stop else self.stop_sequences + stop + stop = [] + [stop.append(x) for x in stop_tmp if x not in stop] + + # HF inference server needs control over input tokens + assert self.tokenizer is not None + from h2oai_pipeline import H2OTextGenerationPipeline + for prompti, prompt in enumerate(prompts): + prompt, num_prompt_tokens = H2OTextGenerationPipeline.limit_prompt(prompt, self.tokenizer) + # NOTE: OpenAI/vLLM server does not add prompting, so must do here + data_point = dict(context=self.context, instruction=prompt, input=self.iinput) + prompt = self.prompter.generate_prompt(data_point) + prompts[prompti] = prompt + + params = self._invocation_params + params = {**params, **kwargs} + sub_prompts = self.get_sub_prompts(params, prompts, stop) + choices = [] + token_usage: Dict[str, int] = {} + # Get the token usage from the response. + # Includes prompt, completion, and total tokens used. + _keys = {"completion_tokens", "prompt_tokens", "total_tokens"} + text = '' + for _prompts in sub_prompts: + if self.streaming: + text_with_prompt = "" + prompt = _prompts[0] + if len(_prompts) > 1: + raise ValueError("Cannot stream results with multiple prompts.") + params["stream"] = True + response = _streaming_response_template() + first = True + for stream_resp in completion_with_retry( + self, prompt=_prompts, **params + ): + if first: + stream_resp["choices"][0]["text"] = prompt + stream_resp["choices"][0]["text"] + first = False + text_chunk = stream_resp["choices"][0]["text"] + text_with_prompt += text_chunk + text = self.prompter.get_response(text_with_prompt, prompt=prompt, + sanitize_bot_response=self.sanitize_bot_response) + if run_manager: + run_manager.on_llm_new_token( + text_chunk, + verbose=self.verbose, + logprobs=stream_resp["choices"][0]["logprobs"], + ) + _update_response(response, stream_resp) + choices.extend(response["choices"]) + else: + response = completion_with_retry(self, prompt=_prompts, **params) + choices.extend(response["choices"]) + if not self.streaming: + # Can't update token usage if streaming + update_token_usage(_keys, response, token_usage) + if self.streaming: + choices[0]['text'] = text + return self.create_llm_result(choices, prompts, token_usage) + + def get_token_ids(self, text: str) -> List[int]: + if self.tokenizer is not None: + return self.tokenizer.encode(text) + else: + # OpenAI uses tiktoken + return super().get_token_ids(text) + + +class H2OReplicate(Replicate): + stop_sequences: Any = None + sanitize_bot_response: bool = False + prompter: Any = None + context: Any = '' + iinput: Any = '' + tokenizer: Any = None + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call to replicate endpoint.""" + stop_tmp = self.stop_sequences if not stop else self.stop_sequences + stop + stop = [] + [stop.append(x) for x in stop_tmp if x not in stop] + + # HF inference server needs control over input tokens + assert self.tokenizer is not None + from h2oai_pipeline import H2OTextGenerationPipeline + prompt, num_prompt_tokens = H2OTextGenerationPipeline.limit_prompt(prompt, self.tokenizer) + # Note Replicate handles the prompting of the specific model + return super()._call(prompt, stop=stop, run_manager=run_manager, **kwargs) + + def get_token_ids(self, text: str) -> List[int]: + return self.tokenizer.encode(text) + # avoid base method that is not aware of how to properly tokenize (uses GPT2) + # return _get_token_ids_default_method(text) + + +class H2OChatOpenAI(ChatOpenAI): + @classmethod + def _all_required_field_names(cls) -> Set: + _all_required_field_names = super(ChatOpenAI, cls)._all_required_field_names() + _all_required_field_names.update({'top_p', 'frequency_penalty', 'presence_penalty', 'logit_bias'}) + return _all_required_field_names + + +class H2OAzureChatOpenAI(AzureChatOpenAI): + @classmethod + def _all_required_field_names(cls) -> Set: + _all_required_field_names = super(AzureChatOpenAI, cls)._all_required_field_names() + _all_required_field_names.update({'top_p', 'frequency_penalty', 'presence_penalty', 'logit_bias'}) + return _all_required_field_names + + +class H2OAzureOpenAI(AzureOpenAI): + @classmethod + def _all_required_field_names(cls) -> Set: + _all_required_field_names = super(AzureOpenAI, cls)._all_required_field_names() + _all_required_field_names.update({'top_p', 'frequency_penalty', 'presence_penalty', 'logit_bias'}) + return _all_required_field_names + + +class H2OHuggingFacePipeline(HuggingFacePipeline): + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + response = self.pipeline(prompt, stop=stop) + if self.pipeline.task == "text-generation": + # Text generation return includes the starter text. + text = response[0]["generated_text"][len(prompt):] + elif self.pipeline.task == "text2text-generation": + text = response[0]["generated_text"] + elif self.pipeline.task == "summarization": + text = response[0]["summary_text"] + else: + raise ValueError( + f"Got invalid task {self.pipeline.task}, " + f"currently only {VALID_TASKS} are supported" + ) + if stop: + # This is a bit hacky, but I can't figure out a better way to enforce + # stop tokens when making calls to huggingface_hub. + text = enforce_stop_tokens(text, stop) + return text + + +def get_llm(use_openai_model=False, + model_name=None, + model=None, + tokenizer=None, + inference_server=None, + langchain_only_model=None, + stream_output=False, + async_output=True, + num_async=3, + do_sample=False, + temperature=0.1, + top_k=40, + top_p=0.7, + num_beams=1, + max_new_tokens=512, + min_new_tokens=1, + early_stopping=False, + max_time=180, + repetition_penalty=1.0, + num_return_sequences=1, + prompt_type=None, + prompt_dict=None, + prompter=None, + context=None, + iinput=None, + sanitize_bot_response=False, + system_prompt='', + visible_models=0, + h2ogpt_key=None, + min_max_new_tokens=None, + n_jobs=None, + cli=False, + llamacpp_dict=None, + verbose=False, + ): + # currently all but h2oai_pipeline case return prompt + new text, but could change + only_new_text = False + + if n_jobs in [None, -1]: + n_jobs = int(os.getenv('OMP_NUM_THREADS', str(os.cpu_count() // 2))) + if inference_server is None: + inference_server = '' + if inference_server.startswith('replicate'): + model_string = ':'.join(inference_server.split(':')[1:]) + if 'meta/llama' in model_string: + temperature = max(0.01, temperature if do_sample else 0) + else: + temperature =temperature if do_sample else 0 + gen_kwargs = dict(temperature=temperature, + seed=1234, + max_length=max_new_tokens, # langchain + max_new_tokens=max_new_tokens, # replicate docs + top_p=top_p if do_sample else 1, + top_k=top_k, # not always supported + repetition_penalty=repetition_penalty) + if system_prompt in [None, 'None', 'auto']: + if prompter.system_prompt: + system_prompt = prompter.system_prompt + else: + system_prompt = '' + if system_prompt: + gen_kwargs.update(dict(system_prompt=system_prompt)) + + # replicate handles prompting, so avoid get_response() filter + prompter.prompt_type = 'plain' + if stream_output: + callbacks = [StreamingGradioCallbackHandler()] + streamer = callbacks[0] if stream_output else None + llm = H2OReplicate( + streaming=True, + callbacks=callbacks, + model=model_string, + input=gen_kwargs, + stop=prompter.stop_sequences, + stop_sequences=prompter.stop_sequences, + sanitize_bot_response=sanitize_bot_response, + prompter=prompter, + context=context, + iinput=iinput, + tokenizer=tokenizer, + ) + else: + streamer = None + llm = H2OReplicate( + model=model_string, + input=gen_kwargs, + stop=prompter.stop_sequences, + stop_sequences=prompter.stop_sequences, + sanitize_bot_response=sanitize_bot_response, + prompter=prompter, + context=context, + iinput=iinput, + tokenizer=tokenizer, + ) + elif use_openai_model or inference_server.startswith('openai') or inference_server.startswith('vllm'): + if use_openai_model and model_name is None: + model_name = "gpt-3.5-turbo" + # FIXME: Will later import be ignored? I think so, so should be fine + openai, inf_type, deployment_name, base_url, api_version = set_openai(inference_server) + kwargs_extra = {} + if inf_type == 'openai_chat' or inf_type == 'vllm_chat': + cls = H2OChatOpenAI + # FIXME: Support context, iinput + # if inf_type == 'vllm_chat': + # kwargs_extra.update(dict(tokenizer=tokenizer)) + openai_api_key = openai.api_key + elif inf_type == 'openai_azure_chat': + cls = H2OAzureChatOpenAI + kwargs_extra.update(dict(openai_api_type='azure')) + # FIXME: Support context, iinput + if os.getenv('OPENAI_AZURE_KEY') is not None: + openai_api_key = os.getenv('OPENAI_AZURE_KEY') + else: + openai_api_key = openai.api_key + elif inf_type == 'openai_azure': + cls = H2OAzureOpenAI + kwargs_extra.update(dict(openai_api_type='azure')) + # FIXME: Support context, iinput + if os.getenv('OPENAI_AZURE_KEY') is not None: + openai_api_key = os.getenv('OPENAI_AZURE_KEY') + else: + openai_api_key = openai.api_key + else: + cls = H2OOpenAI + if inf_type == 'vllm': + kwargs_extra.update(dict(stop_sequences=prompter.stop_sequences, + sanitize_bot_response=sanitize_bot_response, + prompter=prompter, + context=context, + iinput=iinput, + tokenizer=tokenizer, + openai_api_base=openai.api_base, + client=None)) + else: + assert inf_type == 'openai' or use_openai_model + openai_api_key = openai.api_key + + if deployment_name: + kwargs_extra.update(dict(deployment_name=deployment_name)) + if api_version: + kwargs_extra.update(dict(openai_api_version=api_version)) + elif openai.api_version: + kwargs_extra.update(dict(openai_api_version=openai.api_version)) + elif inf_type in ['openai_azure', 'openai_azure_chat']: + kwargs_extra.update(dict(openai_api_version="2023-05-15")) + if base_url: + kwargs_extra.update(dict(openai_api_base=base_url)) + else: + kwargs_extra.update(dict(openai_api_base=openai.api_base)) + + callbacks = [StreamingGradioCallbackHandler()] + llm = cls(model_name=model_name, + temperature=temperature if do_sample else 0, + # FIXME: Need to count tokens and reduce max_new_tokens to fit like in generate.py + max_tokens=max_new_tokens, + top_p=top_p if do_sample else 1, + frequency_penalty=0, + presence_penalty=1.07 - repetition_penalty + 0.6, # so good default + callbacks=callbacks if stream_output else None, + openai_api_key=openai_api_key, + logit_bias=None if inf_type == 'vllm' else {}, + max_retries=6, + streaming=stream_output, + **kwargs_extra + ) + streamer = callbacks[0] if stream_output else None + if inf_type in ['openai', 'openai_chat', 'openai_azure', 'openai_azure_chat']: + prompt_type = inference_server + else: + # vllm goes here + prompt_type = prompt_type or 'plain' + elif inference_server and inference_server.startswith('sagemaker'): + callbacks = [StreamingGradioCallbackHandler()] # FIXME + streamer = None + + endpoint_name = ':'.join(inference_server.split(':')[1:2]) + region_name = ':'.join(inference_server.split(':')[2:]) + + from sagemaker import H2OSagemakerEndpoint, ChatContentHandler, BaseContentHandler + if inference_server.startswith('sagemaker_chat'): + content_handler = ChatContentHandler() + else: + content_handler = BaseContentHandler() + model_kwargs = dict(temperature=temperature if do_sample else 1E-10, + return_full_text=False, top_p=top_p, max_new_tokens=max_new_tokens) + llm = H2OSagemakerEndpoint( + endpoint_name=endpoint_name, + region_name=region_name, + aws_access_key_id=os.environ.get('AWS_ACCESS_KEY_ID'), + aws_secret_access_key=os.environ.get('AWS_SECRET_ACCESS_KEY'), + model_kwargs=model_kwargs, + content_handler=content_handler, + endpoint_kwargs={'CustomAttributes': 'accept_eula=true'}, + ) + elif inference_server: + assert inference_server.startswith( + 'http'), "Malformed inference_server=%s. Did you add http:// in front?" % inference_server + + from gradio_utils.grclient import GradioClient + from text_generation import Client as HFClient + if isinstance(model, GradioClient): + gr_client = model + hf_client = None + else: + gr_client = None + hf_client = model + assert isinstance(hf_client, HFClient) + + inference_server, headers = get_hf_server(inference_server) + + # quick sanity check to avoid long timeouts, just see if can reach server + requests.get(inference_server, timeout=int(os.getenv('REQUEST_TIMEOUT_FAST', '10'))) + callbacks = [StreamingGradioCallbackHandler()] + + if gr_client: + async_output = False # FIXME: not implemented yet + chat_client = False + llm = GradioInference( + inference_server_url=inference_server, + return_full_text=False, + + temperature=temperature, + top_p=top_p, + top_k=top_k, + num_beams=num_beams, + max_new_tokens=max_new_tokens, + min_new_tokens=min_new_tokens, + early_stopping=early_stopping, + max_time=max_time, + repetition_penalty=repetition_penalty, + num_return_sequences=num_return_sequences, + do_sample=do_sample, + chat_client=chat_client, + + callbacks=callbacks if stream_output else None, + stream_output=stream_output, + prompter=prompter, + context=context, + iinput=iinput, + client=gr_client, + sanitize_bot_response=sanitize_bot_response, + tokenizer=tokenizer, + system_prompt=system_prompt, + visible_models=visible_models, + h2ogpt_key=h2ogpt_key, + min_max_new_tokens=min_max_new_tokens, + ) + elif hf_client: + # no need to pass original client, no state and fast, so can use same validate_environment from base class + async_sem = asyncio.Semaphore(num_async) if async_output else NullContext() + llm = H2OHuggingFaceTextGenInference( + inference_server_url=inference_server, + do_sample=do_sample, + max_new_tokens=max_new_tokens, + repetition_penalty=repetition_penalty, + return_full_text=False, # this only controls internal behavior, still returns processed text + seed=SEED, + + stop_sequences=prompter.stop_sequences, + temperature=temperature, + top_k=top_k, + top_p=top_p, + # typical_p=top_p, + callbacks=callbacks if stream_output else None, + stream_output=stream_output, + prompter=prompter, + context=context, + iinput=iinput, + tokenizer=tokenizer, + timeout=max_time, + sanitize_bot_response=sanitize_bot_response, + async_sem=async_sem, + ) + else: + raise RuntimeError("No defined client") + streamer = callbacks[0] if stream_output else None + elif model_name in non_hf_types: + async_output = False # FIXME: not implemented yet + assert langchain_only_model + if model_name == 'llama': + callbacks = [StreamingGradioCallbackHandler()] + streamer = callbacks[0] if stream_output else None + else: + # stream_output = False + # doesn't stream properly as generator, but at least + callbacks = [streaming_stdout.StreamingStdOutCallbackHandler()] + streamer = None + if prompter: + prompt_type = prompter.prompt_type + else: + prompter = Prompter(prompt_type, prompt_dict, debug=False, chat=False, stream_output=stream_output) + pass # assume inputted prompt_type is correct + from gpt4all_llm import get_llm_gpt4all + max_max_tokens = tokenizer.model_max_length + llm = get_llm_gpt4all(model_name, + model=model, + max_new_tokens=max_new_tokens, + temperature=temperature, + repetition_penalty=repetition_penalty, + top_k=top_k, + top_p=top_p, + callbacks=callbacks, + n_jobs=n_jobs, + verbose=verbose, + streaming=stream_output, + prompter=prompter, + context=context, + iinput=iinput, + max_seq_len=max_max_tokens, + llamacpp_dict=llamacpp_dict, + ) + elif hasattr(model, 'is_exlama') and model.is_exlama(): + async_output = False # FIXME: not implemented yet + assert langchain_only_model + callbacks = [StreamingGradioCallbackHandler()] + streamer = callbacks[0] if stream_output else None + max_max_tokens = tokenizer.model_max_length + + from src.llm_exllama import Exllama + llm = Exllama(streaming=stream_output, + model_path=None, + model=model, + lora_path=None, + temperature=temperature, + top_k=top_k, + top_p=top_p, + typical=.7, + beams=1, + # beam_length = 40, + stop_sequences=prompter.stop_sequences, + callbacks=callbacks, + verbose=verbose, + max_seq_len=max_max_tokens, + fused_attn=False, + # alpha_value = 1.0, #For use with any models + # compress_pos_emb = 4.0, #For use with superhot + # set_auto_map = "3, 2" #Gpu split, this will split 3gigs/2gigs + prompter=prompter, + context=context, + iinput=iinput, + ) + else: + async_output = False # FIXME: not implemented yet + if model is None: + # only used if didn't pass model in + assert tokenizer is None + prompt_type = 'human_bot' + if model_name is None: + model_name = 'h2oai/h2ogpt-oasst1-512-12b' + # model_name = 'h2oai/h2ogpt-oig-oasst1-512-6_9b' + # model_name = 'h2oai/h2ogpt-oasst1-512-20b' + inference_server = '' + model, tokenizer, device = get_model(load_8bit=True, base_model=model_name, + inference_server=inference_server, gpu_id=0) + + max_max_tokens = tokenizer.model_max_length + only_new_text = True + gen_kwargs = dict(do_sample=do_sample, + num_beams=num_beams, + max_new_tokens=max_new_tokens, + min_new_tokens=min_new_tokens, + early_stopping=early_stopping, + max_time=max_time, + repetition_penalty=repetition_penalty, + num_return_sequences=num_return_sequences, + return_full_text=not only_new_text, + handle_long_generation=None) + if do_sample: + gen_kwargs.update(dict(temperature=temperature, + top_k=top_k, + top_p=top_p)) + assert len(set(gen_hyper).difference(gen_kwargs.keys())) == 0 + else: + assert len(set(gen_hyper0).difference(gen_kwargs.keys())) == 0 + + if stream_output: + skip_prompt = only_new_text + from gen import H2OTextIteratorStreamer + decoder_kwargs = {} + streamer = H2OTextIteratorStreamer(tokenizer, skip_prompt=skip_prompt, block=False, **decoder_kwargs) + gen_kwargs.update(dict(streamer=streamer)) + else: + streamer = None + + from h2oai_pipeline import H2OTextGenerationPipeline + pipe = H2OTextGenerationPipeline(model=model, use_prompter=True, + prompter=prompter, + context=context, + iinput=iinput, + prompt_type=prompt_type, + prompt_dict=prompt_dict, + sanitize_bot_response=sanitize_bot_response, + chat=False, stream_output=stream_output, + tokenizer=tokenizer, + # leave some room for 1 paragraph, even if min_new_tokens=0 + max_input_tokens=max_max_tokens - max(min_new_tokens, 256), + base_model=model_name, + **gen_kwargs) + # pipe.task = "text-generation" + # below makes it listen only to our prompt removal, + # not built in prompt removal that is less general and not specific for our model + pipe.task = "text2text-generation" + + llm = H2OHuggingFacePipeline(pipeline=pipe) + return llm, model_name, streamer, prompt_type, async_output, only_new_text + + +def get_device_dtype(): + # torch.device("cuda") leads to cuda:x cuda:y mismatches for multi-GPU consistently + import torch + n_gpus = torch.cuda.device_count() if torch.cuda.is_available else 0 + device = 'cpu' if n_gpus == 0 else 'cuda' + # from utils import NullContext + # context_class = NullContext if n_gpus > 1 or n_gpus == 0 else context_class + context_class = torch.device + torch_dtype = torch.float16 if device == 'cuda' else torch.float32 + return device, torch_dtype, context_class + + +def get_wiki_data(title, first_paragraph_only, text_limit=None, take_head=True): + """ + Get wikipedia data from online + :param title: + :param first_paragraph_only: + :param text_limit: + :param take_head: + :return: + """ + filename = 'wiki_%s_%s_%s_%s.data' % (first_paragraph_only, title, text_limit, take_head) + url = f"https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&explaintext=1&titles={title}" + if first_paragraph_only: + url += "&exintro=1" + import json + if not os.path.isfile(filename): + data = requests.get(url).json() + json.dump(data, open(filename, 'wt')) + else: + data = json.load(open(filename, "rt")) + page_content = list(data["query"]["pages"].values())[0]["extract"] + if take_head is not None and text_limit is not None: + page_content = page_content[:text_limit] if take_head else page_content[-text_limit:] + title_url = str(title).replace(' ', '_') + return Document( + page_content=str(page_content), + metadata={"source": f"https://en.wikipedia.org/wiki/{title_url}"}, + ) + + +def get_wiki_sources(first_para=True, text_limit=None): + """ + Get specific named sources from wikipedia + :param first_para: + :param text_limit: + :return: + """ + default_wiki_sources = ['Unix', 'Microsoft_Windows', 'Linux'] + wiki_sources = list(os.getenv('WIKI_SOURCES', default_wiki_sources)) + return [get_wiki_data(x, first_para, text_limit=text_limit) for x in wiki_sources] + + +def get_github_docs(repo_owner, repo_name): + """ + Access github from specific repo + :param repo_owner: + :param repo_name: + :return: + """ + with tempfile.TemporaryDirectory() as d: + subprocess.check_call( + f"git clone --depth 1 https://github.com/{repo_owner}/{repo_name}.git .", + cwd=d, + shell=True, + ) + git_sha = ( + subprocess.check_output("git rev-parse HEAD", shell=True, cwd=d) + .decode("utf-8") + .strip() + ) + repo_path = pathlib.Path(d) + markdown_files = list(repo_path.glob("*/*.md")) + list( + repo_path.glob("*/*.mdx") + ) + for markdown_file in markdown_files: + with open(markdown_file, "r") as f: + relative_path = markdown_file.relative_to(repo_path) + github_url = f"https://github.com/{repo_owner}/{repo_name}/blob/{git_sha}/{relative_path}" + yield Document(page_content=str(f.read()), metadata={"source": github_url}) + + +def get_dai_pickle(dest="."): + from huggingface_hub import hf_hub_download + # True for case when locally already logged in with correct token, so don't have to set key + token = os.getenv('HUGGING_FACE_HUB_TOKEN', True) + path_to_zip_file = hf_hub_download('h2oai/dai_docs', 'dai_docs.pickle', token=token, repo_type='dataset') + shutil.copy(path_to_zip_file, dest) + + +def get_dai_docs(from_hf=False, get_pickle=True): + """ + Consume DAI documentation, or consume from public pickle + :param from_hf: get DAI docs from HF, then generate pickle for later use by LangChain + :param get_pickle: Avoid raw DAI docs, just get pickle directly from HF + :return: + """ + import pickle + + if get_pickle: + get_dai_pickle() + + dai_store = 'dai_docs.pickle' + dst = "working_dir_docs" + if not os.path.isfile(dai_store): + from create_data import setup_dai_docs + dst = setup_dai_docs(dst=dst, from_hf=from_hf) + + import glob + files = list(glob.glob(os.path.join(dst, '*rst'), recursive=True)) + + basedir = os.path.abspath(os.getcwd()) + from create_data import rst_to_outputs + new_outputs = rst_to_outputs(files) + os.chdir(basedir) + + pickle.dump(new_outputs, open(dai_store, 'wb')) + else: + new_outputs = pickle.load(open(dai_store, 'rb')) + + sources = [] + for line, file in new_outputs: + # gradio requires any linked file to be with app.py + sym_src = os.path.abspath(os.path.join(dst, file)) + sym_dst = os.path.abspath(os.path.join(os.getcwd(), file)) + if os.path.lexists(sym_dst): + os.remove(sym_dst) + os.symlink(sym_src, sym_dst) + itm = Document(page_content=str(line), metadata={"source": file}) + # NOTE: yield has issues when going into db, loses metadata + # yield itm + sources.append(itm) + return sources + + +def get_supported_types(): + non_image_types0 = ["pdf", "txt", "csv", "toml", "py", "rst", "xml", "rtf", + "md", + "html", "mhtml", "htm", + "enex", "eml", "epub", "odt", "pptx", "ppt", + "zip", + "gz", + "gzip", + "urls", + ] + # "msg", GPL3 + + video_types0 = ['WEBM', + 'MPG', 'MP2', 'MPEG', 'MPE', '.PV', + 'OGG', + 'MP4', 'M4P', 'M4V', + 'AVI', 'WMV', + 'MOV', 'QT', + 'FLV', 'SWF', + 'AVCHD'] + video_types0 = [x.lower() for x in video_types0] + if have_pillow: + from PIL import Image + exts = Image.registered_extensions() + image_types0 = {ex for ex, f in exts.items() if f in Image.OPEN if ex not in video_types0 + non_image_types0} + image_types0 = sorted(image_types0) + image_types0 = [x[1:] if x.startswith('.') else x for x in image_types0] + else: + image_types0 = [] + return non_image_types0, image_types0, video_types0 + + +non_image_types, image_types, video_types = get_supported_types() +set_image_types = set(image_types) + +if have_libreoffice or True: + # or True so it tries to load, e.g. on MAC/Windows, even if don't have libreoffice since works without that + non_image_types.extend(["docx", "doc", "xls", "xlsx"]) +if have_jq: + non_image_types.extend(["json", "jsonl"]) + +file_types = non_image_types + image_types + + +def try_as_html(file): + # try treating as html as occurs when scraping websites + from bs4 import BeautifulSoup + with open(file, "rt") as f: + try: + is_html = bool(BeautifulSoup(f.read(), "html.parser").find()) + except: # FIXME + is_html = False + if is_html: + file_url = 'file://' + file + doc1 = UnstructuredURLLoader(urls=[file_url]).load() + doc1 = [x for x in doc1 if x.page_content] + else: + doc1 = [] + return doc1 + + +def json_metadata_func(record: dict, metadata: dict) -> dict: + # Define the metadata extraction function. + + if isinstance(record, dict): + metadata["sender_name"] = record.get("sender_name") + metadata["timestamp_ms"] = record.get("timestamp_ms") + + if "source" in metadata: + metadata["source_json"] = metadata['source'] + if "seq_num" in metadata: + metadata["seq_num_json"] = metadata['seq_num'] + + return metadata + + +def file_to_doc(file, + filei=0, + base_path=None, verbose=False, fail_any_exception=False, + chunk=True, chunk_size=512, n_jobs=-1, + is_url=False, is_txt=False, + + # urls + use_unstructured=True, + use_playwright=False, + use_selenium=False, + + # pdfs + use_pymupdf='auto', + use_unstructured_pdf='auto', + use_pypdf='auto', + enable_pdf_ocr='auto', + try_pdf_as_html='auto', + enable_pdf_doctr='auto', + + # images + enable_ocr=False, + enable_doctr=False, + enable_pix2struct=False, + enable_captions=True, + captions_model=None, + model_loaders=None, + + # json + jq_schema='.[]', + + headsize=50, # see also H2OSerpAPIWrapper + db_type=None, + selected_file_types=None): + assert isinstance(model_loaders, dict) + if selected_file_types is not None: + set_image_types1 = set_image_types.intersection(set(selected_file_types)) + else: + set_image_types1 = set_image_types + + assert db_type is not None + chunk_sources = functools.partial(_chunk_sources, chunk=chunk, chunk_size=chunk_size, db_type=db_type) + add_meta = functools.partial(_add_meta, headsize=headsize, filei=filei) + # FIXME: if zip, file index order will not be correct if other files involved + path_to_docs_func = functools.partial(path_to_docs, + verbose=verbose, + fail_any_exception=fail_any_exception, + n_jobs=n_jobs, + chunk=chunk, chunk_size=chunk_size, + # url=file if is_url else None, + # text=file if is_txt else None, + + # urls + use_unstructured=use_unstructured, + use_playwright=use_playwright, + use_selenium=use_selenium, + + # pdfs + use_pymupdf=use_pymupdf, + use_unstructured_pdf=use_unstructured_pdf, + use_pypdf=use_pypdf, + enable_pdf_ocr=enable_pdf_ocr, + enable_pdf_doctr=enable_pdf_doctr, + try_pdf_as_html=try_pdf_as_html, + + # images + enable_ocr=enable_ocr, + enable_doctr=enable_doctr, + enable_pix2struct=enable_pix2struct, + enable_captions=enable_captions, + captions_model=captions_model, + + caption_loader=model_loaders['caption'], + doctr_loader=model_loaders['doctr'], + pix2struct_loader=model_loaders['pix2struct'], + + # json + jq_schema=jq_schema, + + db_type=db_type, + ) + + if file is None: + if fail_any_exception: + raise RuntimeError("Unexpected None file") + else: + return [] + doc1 = [] # in case no support, or disabled support + if base_path is None and not is_txt and not is_url: + # then assume want to persist but don't care which path used + # can't be in base_path + dir_name = os.path.dirname(file) + base_name = os.path.basename(file) + # if from gradio, will have its own temp uuid too, but that's ok + base_name = sanitize_filename(base_name) + "_" + str(uuid.uuid4())[:10] + base_path = os.path.join(dir_name, base_name) + if is_url: + file = file.strip() # in case accidental spaces in front or at end + file_lower = file.lower() + case1 = file_lower.startswith('arxiv:') and len(file_lower.split('arxiv:')) == 2 + case2 = file_lower.startswith('https://arxiv.org/abs') and len(file_lower.split('https://arxiv.org/abs')) == 2 + case3 = file_lower.startswith('http://arxiv.org/abs') and len(file_lower.split('http://arxiv.org/abs')) == 2 + case4 = file_lower.startswith('arxiv.org/abs/') and len(file_lower.split('arxiv.org/abs/')) == 2 + if case1 or case2 or case3 or case4: + if case1: + query = file.lower().split('arxiv:')[1].strip() + elif case2: + query = file.lower().split('https://arxiv.org/abs/')[1].strip() + elif case2: + query = file.lower().split('http://arxiv.org/abs/')[1].strip() + elif case3: + query = file.lower().split('arxiv.org/abs/')[1].strip() + else: + raise RuntimeError("Unexpected arxiv error for %s" % file) + if have_arxiv: + trials = 3 + docs1 = [] + for trial in range(trials): + try: + docs1 = ArxivLoader(query=query, load_max_docs=20, load_all_available_meta=True).load() + break + except urllib.error.URLError: + pass + if not docs1: + print("Failed to get arxiv %s" % query, flush=True) + # ensure string, sometimes None + [[x.metadata.update({k: str(v)}) for k, v in x.metadata.items()] for x in docs1] + query_url = f"https://arxiv.org/abs/{query}" + [x.metadata.update( + dict(source=x.metadata.get('entry_id', query_url), query=query_url, + input_type='arxiv', head=x.metadata.get('Title', ''), date=str(datetime.now))) for x in + docs1] + else: + docs1 = [] + else: + if not (file.startswith("http://") or file.startswith("file://") or file.startswith("https://")): + file = 'http://' + file + docs1 = [] + do_unstructured = only_unstructured_urls or use_unstructured + if only_selenium or only_playwright: + do_unstructured = False + do_playwright = have_playwright and (use_playwright or only_playwright) + if only_unstructured_urls or only_selenium: + do_playwright = False + do_selenium = have_selenium and (use_selenium or only_selenium) + if only_unstructured_urls or only_playwright: + do_selenium = False + if do_unstructured or use_unstructured: + docs1a = UnstructuredURLLoader(urls=[file]).load() + docs1a = [x for x in docs1a if x.page_content] + add_parser(docs1a, 'UnstructuredURLLoader') + docs1.extend(docs1a) + if len(docs1) == 0 and have_playwright or do_playwright: + # then something went wrong, try another loader: + from langchain.document_loaders import PlaywrightURLLoader + docs1a = asyncio.run(PlaywrightURLLoader(urls=[file]).aload()) + # docs1 = PlaywrightURLLoader(urls=[file]).load() + docs1a = [x for x in docs1a if x.page_content] + add_parser(docs1a, 'PlaywrightURLLoader') + docs1.extend(docs1a) + if len(docs1) == 0 and have_selenium or do_selenium: + # then something went wrong, try another loader: + # but requires Chrome binary, else get: selenium.common.exceptions.WebDriverException: + # Message: unknown error: cannot find Chrome binary + from langchain.document_loaders import SeleniumURLLoader + from selenium.common.exceptions import WebDriverException + try: + docs1a = SeleniumURLLoader(urls=[file]).load() + docs1a = [x for x in docs1a if x.page_content] + add_parser(docs1a, 'SeleniumURLLoader') + docs1.extend(docs1a) + except WebDriverException as e: + print("No web driver: %s" % str(e), flush=True) + [x.metadata.update(dict(input_type='url', date=str(datetime.now))) for x in docs1] + add_meta(docs1, file, parser="is_url") + docs1 = clean_doc(docs1) + doc1 = chunk_sources(docs1) + elif is_txt: + base_path = "user_paste" + base_path = makedirs(base_path, exist_ok=True, tmp_ok=True, use_base=True) + source_file = os.path.join(base_path, "_%s" % str(uuid.uuid4())[:10]) + with open(source_file, "wt") as f: + f.write(file) + metadata = dict(source=source_file, date=str(datetime.now()), input_type='pasted txt') + doc1 = Document(page_content=str(file), metadata=metadata) + add_meta(doc1, file, parser="f.write") + # Bit odd to change if was original text + # doc1 = clean_doc(doc1) + elif file.lower().endswith('.html') or file.lower().endswith('.mhtml') or file.lower().endswith('.htm'): + docs1 = UnstructuredHTMLLoader(file_path=file).load() + add_meta(docs1, file, parser='UnstructuredHTMLLoader') + docs1 = clean_doc(docs1) + doc1 = chunk_sources(docs1, language=Language.HTML) + elif (file.lower().endswith('.docx') or file.lower().endswith('.doc')) and (have_libreoffice or True): + docs1 = UnstructuredWordDocumentLoader(file_path=file).load() + add_meta(docs1, file, parser='UnstructuredWordDocumentLoader') + doc1 = chunk_sources(docs1) + elif (file.lower().endswith('.xlsx') or file.lower().endswith('.xls')) and (have_libreoffice or True): + docs1 = UnstructuredExcelLoader(file_path=file).load() + add_meta(docs1, file, parser='UnstructuredExcelLoader') + doc1 = chunk_sources(docs1) + elif file.lower().endswith('.odt'): + docs1 = UnstructuredODTLoader(file_path=file).load() + add_meta(docs1, file, parser='UnstructuredODTLoader') + doc1 = chunk_sources(docs1) + elif file.lower().endswith('pptx') or file.lower().endswith('ppt'): + docs1 = UnstructuredPowerPointLoader(file_path=file).load() + add_meta(docs1, file, parser='UnstructuredPowerPointLoader') + docs1 = clean_doc(docs1) + doc1 = chunk_sources(docs1) + elif file.lower().endswith('.txt'): + # use UnstructuredFileLoader ? + docs1 = TextLoader(file, encoding="utf8", autodetect_encoding=True).load() + # makes just one, but big one + doc1 = chunk_sources(docs1) + # Bit odd to change if was original text + # doc1 = clean_doc(doc1) + add_meta(doc1, file, parser='TextLoader') + elif file.lower().endswith('.rtf'): + docs1 = UnstructuredRTFLoader(file).load() + add_meta(docs1, file, parser='UnstructuredRTFLoader') + doc1 = chunk_sources(docs1) + elif file.lower().endswith('.md'): + docs1 = UnstructuredMarkdownLoader(file).load() + add_meta(docs1, file, parser='UnstructuredMarkdownLoader') + docs1 = clean_doc(docs1) + doc1 = chunk_sources(docs1, language=Language.MARKDOWN) + elif file.lower().endswith('.enex'): + docs1 = EverNoteLoader(file).load() + add_meta(doc1, file, parser='EverNoteLoader') + doc1 = chunk_sources(docs1) + elif file.lower().endswith('.epub'): + docs1 = UnstructuredEPubLoader(file).load() + add_meta(docs1, file, parser='UnstructuredEPubLoader') + doc1 = chunk_sources(docs1) + elif any(file.lower().endswith(x) for x in set_image_types1): + docs1 = [] + if verbose: + print("BEGIN: Tesseract", flush=True) + if have_tesseract and enable_ocr: + # OCR, somewhat works, but not great + docs1a = UnstructuredImageLoader(file, strategy='ocr_only').load() + # docs1a = UnstructuredImageLoader(file, strategy='hi_res').load() + docs1a = [x for x in docs1a if x.page_content] + add_meta(docs1a, file, parser='UnstructuredImageLoader') + docs1.extend(docs1a) + if verbose: + print("END: Tesseract", flush=True) + if have_doctr and enable_doctr: + if verbose: + print("BEGIN: DocTR", flush=True) + if model_loaders['doctr'] is not None and not isinstance(model_loaders['doctr'], (str, bool)): + if verbose: + print("Reuse DocTR", flush=True) + model_loaders['doctr'].load_model() + else: + if verbose: + print("Fresh DocTR", flush=True) + from image_doctr import H2OOCRLoader + model_loaders['doctr'] = H2OOCRLoader() + model_loaders['doctr'].set_document_paths([file]) + docs1c = model_loaders['doctr'].load() + docs1c = [x for x in docs1c if x.page_content] + add_meta(docs1c, file, parser='H2OOCRLoader: %s' % 'DocTR') + # caption didn't set source, so fix-up meta + for doci in docs1c: + doci.metadata['source'] = doci.metadata.get('document_path', file) + doci.metadata['hashid'] = hash_file(doci.metadata['source']) + docs1.extend(docs1c) + if verbose: + print("END: DocTR", flush=True) + if enable_captions: + # BLIP + if verbose: + print("BEGIN: BLIP", flush=True) + if model_loaders['caption'] is not None and not isinstance(model_loaders['caption'], (str, bool)): + # assumes didn't fork into this process with joblib, else can deadlock + if verbose: + print("Reuse BLIP", flush=True) + model_loaders['caption'].load_model() + else: + if verbose: + print("Fresh BLIP", flush=True) + from image_captions import H2OImageCaptionLoader + model_loaders['caption'] = H2OImageCaptionLoader(caption_gpu=model_loaders['caption'] == 'gpu', + blip_model=captions_model, + blip_processor=captions_model) + model_loaders['caption'].set_image_paths([file]) + docs1c = model_loaders['caption'].load() + docs1c = [x for x in docs1c if x.page_content] + add_meta(docs1c, file, parser='H2OImageCaptionLoader: %s' % captions_model) + # caption didn't set source, so fix-up meta + for doci in docs1c: + doci.metadata['source'] = doci.metadata.get('image_path', file) + doci.metadata['hashid'] = hash_file(doci.metadata['source']) + docs1.extend(docs1c) + + if verbose: + print("END: BLIP", flush=True) + if enable_pix2struct: + # BLIP + if verbose: + print("BEGIN: Pix2Struct", flush=True) + if model_loaders['pix2struct'] is not None and not isinstance(model_loaders['pix2struct'], (str, bool)): + if verbose: + print("Reuse pix2struct", flush=True) + model_loaders['pix2struct'].load_model() + else: + if verbose: + print("Fresh pix2struct", flush=True) + from image_pix2struct import H2OPix2StructLoader + model_loaders['pix2struct'] = H2OPix2StructLoader() + model_loaders['pix2struct'].set_image_paths([file]) + docs1c = model_loaders['pix2struct'].load() + docs1c = [x for x in docs1c if x.page_content] + add_meta(docs1c, file, parser='H2OPix2StructLoader: %s' % model_loaders['pix2struct']) + # caption didn't set source, so fix-up meta + for doci in docs1c: + doci.metadata['source'] = doci.metadata.get('image_path', file) + doci.metadata['hashid'] = hash_file(doci.metadata['source']) + docs1.extend(docs1c) + if verbose: + print("END: Pix2Struct", flush=True) + doc1 = chunk_sources(docs1) + elif file.lower().endswith('.msg'): + raise RuntimeError("Not supported, GPL3 license") + # docs1 = OutlookMessageLoader(file).load() + # docs1[0].metadata['source'] = file + elif file.lower().endswith('.eml'): + try: + docs1 = UnstructuredEmailLoader(file).load() + add_meta(docs1, file, parser='UnstructuredEmailLoader') + doc1 = chunk_sources(docs1) + except ValueError as e: + if 'text/html content not found in email' in str(e): + pass + else: + raise + doc1 = [x for x in doc1 if x.page_content] + if len(doc1) == 0: + # e.g. plain/text dict key exists, but not + # doc1 = TextLoader(file, encoding="utf8").load() + docs1 = UnstructuredEmailLoader(file, content_source="text/plain").load() + docs1 = [x for x in docs1 if x.page_content] + add_meta(docs1, file, parser='UnstructuredEmailLoader text/plain') + doc1 = chunk_sources(docs1) + # elif file.lower().endswith('.gcsdir'): + # doc1 = GCSDirectoryLoader(project_name, bucket, prefix).load() + # elif file.lower().endswith('.gcsfile'): + # doc1 = GCSFileLoader(project_name, bucket, blob).load() + elif file.lower().endswith('.rst'): + with open(file, "r") as f: + doc1 = Document(page_content=str(f.read()), metadata={"source": file}) + add_meta(doc1, file, parser='f.read()') + doc1 = chunk_sources(doc1, language=Language.RST) + elif file.lower().endswith('.json'): + # 10k rows, 100 columns-like parts 4 bytes each + JSON_SIZE_LIMIT = int(os.getenv('JSON_SIZE_LIMIT', str(10 * 10 * 1024 * 10 * 4))) + if os.path.getsize(file) > JSON_SIZE_LIMIT: + raise ValueError( + "JSON file sizes > %s not supported for naive parsing and embedding, requires Agents enabled" % JSON_SIZE_LIMIT) + loader = JSONLoader( + file_path=file, + # jq_schema='.messages[].content', + jq_schema=jq_schema, + text_content=False, + metadata_func=json_metadata_func) + doc1 = loader.load() + add_meta(doc1, file, parser='JSONLoader: %s' % jq_schema) + fix_json_meta(doc1) + elif file.lower().endswith('.jsonl'): + loader = JSONLoader( + file_path=file, + # jq_schema='.messages[].content', + jq_schema=jq_schema, + json_lines=True, + text_content=False, + metadata_func=json_metadata_func) + doc1 = loader.load() + add_meta(doc1, file, parser='JSONLoader: %s' % jq_schema) + fix_json_meta(doc1) + elif file.lower().endswith('.pdf'): + # migration + if isinstance(use_pymupdf, bool): + if use_pymupdf == False: + use_pymupdf = 'off' + if use_pymupdf == True: + use_pymupdf = 'on' + if isinstance(use_unstructured_pdf, bool): + if use_unstructured_pdf == False: + use_unstructured_pdf = 'off' + if use_unstructured_pdf == True: + use_unstructured_pdf = 'on' + if isinstance(use_pypdf, bool): + if use_pypdf == False: + use_pypdf = 'off' + if use_pypdf == True: + use_pypdf = 'on' + if isinstance(enable_pdf_ocr, bool): + if enable_pdf_ocr == False: + enable_pdf_ocr = 'off' + if enable_pdf_ocr == True: + enable_pdf_ocr = 'on' + if isinstance(try_pdf_as_html, bool): + if try_pdf_as_html == False: + try_pdf_as_html = 'off' + if try_pdf_as_html == True: + try_pdf_as_html = 'on' + + doc1 = [] + tried_others = False + handled = False + did_pymupdf = False + did_unstructured = False + e = None + if have_pymupdf and (len(doc1) == 0 and use_pymupdf == 'auto' or use_pymupdf == 'on'): + # GPL, only use if installed + from langchain.document_loaders import PyMuPDFLoader + # load() still chunks by pages, but every page has title at start to help + try: + doc1a = PyMuPDFLoader(file).load() + did_pymupdf = True + except BaseException as e0: + doc1a = [] + print("PyMuPDFLoader: %s" % str(e0), flush=True) + e = e0 + # remove empty documents + handled |= len(doc1a) > 0 + doc1a = [x for x in doc1a if x.page_content] + doc1a = clean_doc(doc1a) + add_parser(doc1a, 'PyMuPDFLoader') + doc1.extend(doc1a) + if len(doc1) == 0 and use_unstructured_pdf == 'auto' or use_unstructured_pdf == 'on': + tried_others = True + try: + doc1a = UnstructuredPDFLoader(file).load() + did_unstructured = True + except BaseException as e0: + doc1a = [] + print("UnstructuredPDFLoader: %s" % str(e0), flush=True) + e = e0 + handled |= len(doc1a) > 0 + # remove empty documents + doc1a = [x for x in doc1a if x.page_content] + add_parser(doc1a, 'UnstructuredPDFLoader') + # seems to not need cleaning in most cases + doc1.extend(doc1a) + if len(doc1) == 0 and use_pypdf == 'auto' or use_pypdf == 'on': + tried_others = True + # open-source fallback + # load() still chunks by pages, but every page has title at start to help + try: + doc1a = PyPDFLoader(file).load() + except BaseException as e0: + doc1a = [] + print("PyPDFLoader: %s" % str(e0), flush=True) + e = e0 + handled |= len(doc1a) > 0 + # remove empty documents + doc1a = [x for x in doc1a if x.page_content] + doc1a = clean_doc(doc1a) + add_parser(doc1a, 'PyPDFLoader') + doc1.extend(doc1a) + if not did_pymupdf and ((have_pymupdf and len(doc1) == 0) and tried_others): + # try again in case only others used, but only if didn't already try (2nd part of and) + # GPL, only use if installed + from langchain.document_loaders import PyMuPDFLoader + # load() still chunks by pages, but every page has title at start to help + try: + doc1a = PyMuPDFLoader(file).load() + except BaseException as e0: + doc1a = [] + print("PyMuPDFLoader: %s" % str(e0), flush=True) + e = e0 + handled |= len(doc1a) > 0 + # remove empty documents + doc1a = [x for x in doc1a if x.page_content] + doc1a = clean_doc(doc1a) + add_parser(doc1a, 'PyMuPDFLoader2') + doc1.extend(doc1a) + did_pdf_ocr = False + if len(doc1) == 0 and (enable_pdf_ocr == 'auto' and enable_pdf_doctr != 'on') or enable_pdf_ocr == 'on': + did_pdf_ocr = True + # no did_unstructured condition here because here we do OCR, and before we did not + # try OCR in end since slowest, but works on pure image pages well + doc1a = UnstructuredPDFLoader(file, strategy='ocr_only').load() + handled |= len(doc1a) > 0 + # remove empty documents + doc1a = [x for x in doc1a if x.page_content] + add_parser(doc1a, 'UnstructuredPDFLoader ocr_only') + # seems to not need cleaning in most cases + doc1.extend(doc1a) + # Some PDFs return nothing or junk from PDFMinerLoader + if len(doc1) == 0 and enable_pdf_doctr == 'auto' or enable_pdf_doctr == 'on': + if verbose: + print("BEGIN: DocTR", flush=True) + if model_loaders['doctr'] is not None and not isinstance(model_loaders['doctr'], (str, bool)): + model_loaders['doctr'].load_model() + else: + from image_doctr import H2OOCRLoader + model_loaders['doctr'] = H2OOCRLoader() + model_loaders['doctr'].set_document_paths([file]) + doc1a = model_loaders['doctr'].load() + doc1a = [x for x in doc1a if x.page_content] + add_meta(doc1a, file, parser='H2OOCRLoader: %s' % 'DocTR') + handled |= len(doc1a) > 0 + # caption didn't set source, so fix-up meta + for doci in doc1a: + doci.metadata['source'] = doci.metadata.get('document_path', file) + doci.metadata['hashid'] = hash_file(doci.metadata['source']) + doc1.extend(doc1a) + if verbose: + print("END: DocTR", flush=True) + if try_pdf_as_html in ['auto', 'on']: + doc1a = try_as_html(file) + add_parser(doc1a, 'try_as_html') + doc1.extend(doc1a) + + if len(doc1) == 0: + # if literally nothing, show failed to parse so user knows, since unlikely nothing in PDF at all. + if handled: + raise ValueError("%s had no valid text, but meta data was parsed" % file) + else: + raise ValueError("%s had no valid text and no meta data was parsed: %s" % (file, str(e))) + add_meta(doc1, file, parser='pdf') + doc1 = chunk_sources(doc1) + elif file.lower().endswith('.csv'): + CSV_SIZE_LIMIT = int(os.getenv('CSV_SIZE_LIMIT', str(10 * 1024 * 10 * 4))) + if os.path.getsize(file) > CSV_SIZE_LIMIT: + raise ValueError( + "CSV file sizes > %s not supported for naive parsing and embedding, requires Agents enabled" % CSV_SIZE_LIMIT) + doc1 = CSVLoader(file).load() + add_meta(doc1, file, parser='CSVLoader') + if isinstance(doc1, list): + # each row is a Document, identify + [x.metadata.update(dict(chunk_id=chunk_id)) for chunk_id, x in enumerate(doc1)] + if db_type in ['chroma', 'chroma_old']: + # then separate summarize list + sdoc1 = clone_documents(doc1) + [x.metadata.update(dict(chunk_id=-1)) for chunk_id, x in enumerate(sdoc1)] + doc1 = sdoc1 + doc1 + elif file.lower().endswith('.py'): + doc1 = PythonLoader(file).load() + add_meta(doc1, file, parser='PythonLoader') + doc1 = chunk_sources(doc1, language=Language.PYTHON) + elif file.lower().endswith('.toml'): + doc1 = TomlLoader(file).load() + add_meta(doc1, file, parser='TomlLoader') + doc1 = chunk_sources(doc1) + elif file.lower().endswith('.xml'): + from langchain.document_loaders import UnstructuredXMLLoader + loader = UnstructuredXMLLoader(file_path=file) + doc1 = loader.load() + add_meta(doc1, file, parser='UnstructuredXMLLoader') + elif file.lower().endswith('.urls'): + with open(file, "r") as f: + urls = f.readlines() + # recurse + doc1 = path_to_docs_func(None, url=urls) + elif file.lower().endswith('.zip'): + with zipfile.ZipFile(file, 'r') as zip_ref: + # don't put into temporary path, since want to keep references to docs inside zip + # so just extract in path where + zip_ref.extractall(base_path) + # recurse + doc1 = path_to_docs_func(base_path) + elif file.lower().endswith('.gz') or file.lower().endswith('.gzip'): + if file.lower().endswith('.gz'): + de_file = file.lower().replace('.gz', '') + else: + de_file = file.lower().replace('.gzip', '') + with gzip.open(file, 'rb') as f_in: + with open(de_file, 'wb') as f_out: + shutil.copyfileobj(f_in, f_out) + # recurse + doc1 = file_to_doc(de_file, + filei=filei, # single file, same file index as outside caller + base_path=base_path, verbose=verbose, fail_any_exception=fail_any_exception, + chunk=chunk, chunk_size=chunk_size, n_jobs=n_jobs, + is_url=is_url, is_txt=is_txt, + + # urls + use_unstructured=use_unstructured, + use_playwright=use_playwright, + use_selenium=use_selenium, + + # pdfs + use_pymupdf=use_pymupdf, + use_unstructured_pdf=use_unstructured_pdf, + use_pypdf=use_pypdf, + enable_pdf_ocr=enable_pdf_ocr, + enable_pdf_doctr=enable_pdf_doctr, + try_pdf_as_html=try_pdf_as_html, + + # images + enable_ocr=enable_ocr, + enable_doctr=enable_doctr, + enable_pix2struct=enable_pix2struct, + enable_captions=enable_captions, + captions_model=captions_model, + model_loaders=model_loaders, + + # json + jq_schema=jq_schema, + + headsize=headsize, + db_type=db_type, + selected_file_types=selected_file_types) + else: + raise RuntimeError("No file handler for %s" % os.path.basename(file)) + + # allow doc1 to be list or not. + if not isinstance(doc1, list): + # If not list, did not chunk yet, so chunk now + docs = chunk_sources([doc1]) + elif isinstance(doc1, list) and len(doc1) == 1: + # if list of length one, don't trust and chunk it, chunk_id's will still be correct if repeat + docs = chunk_sources(doc1) + else: + docs = doc1 + + assert isinstance(docs, list) + return docs + + +def path_to_doc1(file, + filei=0, + verbose=False, fail_any_exception=False, return_file=True, + chunk=True, chunk_size=512, + n_jobs=-1, + is_url=False, is_txt=False, + + # urls + use_unstructured=True, + use_playwright=False, + use_selenium=False, + + # pdfs + use_pymupdf='auto', + use_unstructured_pdf='auto', + use_pypdf='auto', + enable_pdf_ocr='auto', + enable_pdf_doctr='auto', + try_pdf_as_html='auto', + + # images + enable_ocr=False, + enable_doctr=False, + enable_pix2struct=False, + enable_captions=True, + captions_model=None, + model_loaders=None, + + # json + jq_schema='.[]', + + db_type=None, + selected_file_types=None): + assert db_type is not None + if verbose: + if is_url: + print("Ingesting URL: %s" % file, flush=True) + elif is_txt: + print("Ingesting Text: %s" % file, flush=True) + else: + print("Ingesting file: %s" % file, flush=True) + res = None + try: + # don't pass base_path=path, would infinitely recurse + res = file_to_doc(file, + filei=filei, + base_path=None, verbose=verbose, fail_any_exception=fail_any_exception, + chunk=chunk, chunk_size=chunk_size, + n_jobs=n_jobs, + is_url=is_url, is_txt=is_txt, + + # urls + use_unstructured=use_unstructured, + use_playwright=use_playwright, + use_selenium=use_selenium, + + # pdfs + use_pymupdf=use_pymupdf, + use_unstructured_pdf=use_unstructured_pdf, + use_pypdf=use_pypdf, + enable_pdf_ocr=enable_pdf_ocr, + enable_pdf_doctr=enable_pdf_doctr, + try_pdf_as_html=try_pdf_as_html, + + # images + enable_ocr=enable_ocr, + enable_doctr=enable_doctr, + enable_pix2struct=enable_pix2struct, + enable_captions=enable_captions, + captions_model=captions_model, + model_loaders=model_loaders, + + # json + jq_schema=jq_schema, + + db_type=db_type, + selected_file_types=selected_file_types) + except BaseException as e: + print("Failed to ingest %s due to %s" % (file, traceback.format_exc())) + if fail_any_exception: + raise + else: + exception_doc = Document( + page_content='', + metadata={"source": file, "exception": '%s Exception: %s' % (file, str(e)), + "traceback": traceback.format_exc()}) + res = [exception_doc] + if verbose: + if is_url: + print("DONE Ingesting URL: %s" % file, flush=True) + elif is_txt: + print("DONE Ingesting Text: %s" % file, flush=True) + else: + print("DONE Ingesting file: %s" % file, flush=True) + if return_file: + base_tmp = "temp_path_to_doc1" + if not os.path.isdir(base_tmp): + base_tmp = makedirs(base_tmp, exist_ok=True, tmp_ok=True, use_base=True) + filename = os.path.join(base_tmp, str(uuid.uuid4()) + ".tmp.pickle") + with open(filename, 'wb') as f: + pickle.dump(res, f) + return filename + return res + + +def path_to_docs(path_or_paths, verbose=False, fail_any_exception=False, n_jobs=-1, + chunk=True, chunk_size=512, + url=None, text=None, + + # urls + use_unstructured=True, + use_playwright=False, + use_selenium=False, + + # pdfs + use_pymupdf='auto', + use_unstructured_pdf='auto', + use_pypdf='auto', + enable_pdf_ocr='auto', + enable_pdf_doctr='auto', + try_pdf_as_html='auto', + + # images + enable_ocr=False, + enable_doctr=False, + enable_pix2struct=False, + enable_captions=True, + captions_model=None, + + caption_loader=None, + doctr_loader=None, + pix2struct_loader=None, + + # json + jq_schema='.[]', + + existing_files=[], + existing_hash_ids={}, + db_type=None, + selected_file_types=None, + ): + if verbose: + print("BEGIN Consuming path_or_paths=%s url=%s text=%s" % (path_or_paths, url, text), flush=True) + if selected_file_types is not None: + non_image_types1 = [x for x in non_image_types if x in selected_file_types] + image_types1 = [x for x in image_types if x in selected_file_types] + else: + non_image_types1 = non_image_types.copy() + image_types1 = image_types.copy() + + assert db_type is not None + # path_or_paths could be str, list, tuple, generator + globs_image_types = [] + globs_non_image_types = [] + if not path_or_paths and not url and not text: + return [] + elif url: + url = get_list_or_str(url) + globs_non_image_types = url if isinstance(url, (list, tuple, types.GeneratorType)) else [url] + elif text: + globs_non_image_types = text if isinstance(text, (list, tuple, types.GeneratorType)) else [text] + elif isinstance(path_or_paths, str) and os.path.isdir(path_or_paths): + # single path, only consume allowed files + path = path_or_paths + # Below globs should match patterns in file_to_doc() + [globs_image_types.extend(glob.glob(os.path.join(path, "./**/*.%s" % ftype), recursive=True)) + for ftype in image_types1] + globs_image_types = [os.path.normpath(x) for x in globs_image_types] + [globs_non_image_types.extend(glob.glob(os.path.join(path, "./**/*.%s" % ftype), recursive=True)) + for ftype in non_image_types1] + globs_non_image_types = [os.path.normpath(x) for x in globs_non_image_types] + else: + if isinstance(path_or_paths, str): + if os.path.isfile(path_or_paths) or os.path.isdir(path_or_paths): + path_or_paths = [path_or_paths] + else: + # path was deleted etc. + return [] + # list/tuple of files (consume what can, and exception those that selected but cannot consume so user knows) + assert isinstance(path_or_paths, (list, tuple, types.GeneratorType)), \ + "Wrong type for path_or_paths: %s %s" % (path_or_paths, type(path_or_paths)) + # reform out of allowed types + globs_image_types.extend( + flatten_list([[os.path.normpath(x) for x in path_or_paths if x.endswith(y)] for y in image_types1])) + # could do below: + # globs_non_image_types = flatten_list([[x for x in path_or_paths if x.endswith(y)] for y in non_image_types1]) + # But instead, allow fail so can collect unsupported too + set_globs_image_types = set(globs_image_types) + globs_non_image_types.extend([os.path.normpath(x) for x in path_or_paths if x not in set_globs_image_types]) + + # filter out any files to skip (e.g. if already processed them) + # this is easy, but too aggressive in case a file changed, so parent probably passed existing_files=[] + assert not existing_files, "DEV: assume not using this approach" + if existing_files: + set_skip_files = set(existing_files) + globs_image_types = [x for x in globs_image_types if x not in set_skip_files] + globs_non_image_types = [x for x in globs_non_image_types if x not in set_skip_files] + if existing_hash_ids: + # assume consistent with add_meta() use of hash_file(file) + # also assume consistent with get_existing_hash_ids for dict creation + # assume hashable values + existing_hash_ids_set = set(existing_hash_ids.items()) + hash_ids_all_image = set({x: hash_file(x) for x in globs_image_types}.items()) + hash_ids_all_non_image = set({x: hash_file(x) for x in globs_non_image_types}.items()) + # don't use symmetric diff. If file is gone, ignore and don't remove or something + # just consider existing files (key) having new hash or not (value) + new_files_image = set(dict(hash_ids_all_image - existing_hash_ids_set).keys()) + new_files_non_image = set(dict(hash_ids_all_non_image - existing_hash_ids_set).keys()) + globs_image_types = [x for x in globs_image_types if x in new_files_image] + globs_non_image_types = [x for x in globs_non_image_types if x in new_files_non_image] + + # could use generator, but messes up metadata handling in recursive case + if caption_loader and not isinstance(caption_loader, (bool, str)) and caption_loader.device != 'cpu' or \ + get_device() == 'cuda': + # to avoid deadlocks, presume was preloaded and so can't fork due to cuda context + # get_device() == 'cuda' because presume faster to process image from (temporarily) preloaded model + n_jobs_image = 1 + else: + n_jobs_image = n_jobs + if enable_doctr or enable_pdf_doctr in [True, 'auto', 'on']: + if doctr_loader and not isinstance(doctr_loader, (bool, str)) and doctr_loader.device != 'cpu': + # can't fork cuda context + n_jobs = 1 + + return_file = True # local choice + is_url = url is not None + is_txt = text is not None + model_loaders = dict(caption=caption_loader, + doctr=doctr_loader, + pix2struct=pix2struct_loader) + model_loaders0 = model_loaders.copy() + kwargs = dict(verbose=verbose, fail_any_exception=fail_any_exception, + return_file=return_file, + chunk=chunk, chunk_size=chunk_size, + n_jobs=n_jobs, + is_url=is_url, + is_txt=is_txt, + + # urls + use_unstructured=use_unstructured, + use_playwright=use_playwright, + use_selenium=use_selenium, + + # pdfs + use_pymupdf=use_pymupdf, + use_unstructured_pdf=use_unstructured_pdf, + use_pypdf=use_pypdf, + enable_pdf_ocr=enable_pdf_ocr, + enable_pdf_doctr=enable_pdf_doctr, + try_pdf_as_html=try_pdf_as_html, + + # images + enable_ocr=enable_ocr, + enable_doctr=enable_doctr, + enable_pix2struct=enable_pix2struct, + enable_captions=enable_captions, + captions_model=captions_model, + model_loaders=model_loaders, + + # json + jq_schema=jq_schema, + + db_type=db_type, + selected_file_types=selected_file_types, + ) + if n_jobs != 1 and len(globs_non_image_types) > 1: + # avoid nesting, e.g. upload 1 zip and then inside many files + # harder to handle if upload many zips with many files, inner parallel one will be disabled by joblib + documents = ProgressParallel(n_jobs=n_jobs, verbose=10 if verbose else 0, backend='multiprocessing')( + delayed(path_to_doc1)(file, filei=filei, **kwargs) for filei, file in enumerate(globs_non_image_types) + ) + else: + documents = [path_to_doc1(file, filei=filei, **kwargs) for filei, file in + enumerate(tqdm(globs_non_image_types))] + + # do images separately since can't fork after cuda in parent, so can't be parallel + if n_jobs_image != 1 and len(globs_image_types) > 1: + # avoid nesting, e.g. upload 1 zip and then inside many files + # harder to handle if upload many zips with many files, inner parallel one will be disabled by joblib + image_documents = ProgressParallel(n_jobs=n_jobs, verbose=10 if verbose else 0, backend='multiprocessing')( + delayed(path_to_doc1)(file, filei=filei, **kwargs) for filei, file in enumerate(globs_image_types) + ) + else: + image_documents = [path_to_doc1(file, filei=filei, **kwargs) for filei, file in + enumerate(tqdm(globs_image_types))] + + # unload loaders (image loaders, includes enable_pdf_doctr that uses same loader) + for name, loader in model_loaders.items(): + loader0 = model_loaders0[name] + real_model_initial = loader0 is not None and not isinstance(loader0, (str, bool)) + real_model_final = model_loaders[name] is not None and not isinstance(model_loaders[name], (str, bool)) + if not real_model_initial and real_model_final: + # clear off GPU newly added model + model_loaders[name].unload_model() + + # add image docs in + documents += image_documents + + if return_file: + # then documents really are files + files = documents.copy() + documents = [] + for fil in files: + with open(fil, 'rb') as f: + documents.extend(pickle.load(f)) + # remove temp pickle + remove(fil) + else: + documents = reduce(concat, documents) + + if verbose: + print("END consuming path_or_paths=%s url=%s text=%s" % (path_or_paths, url, text), flush=True) + return documents + + +def prep_langchain(persist_directory, + load_db_if_exists, + db_type, use_openai_embedding, + langchain_mode, langchain_mode_paths, langchain_mode_types, + hf_embedding_model, + migrate_embedding_model, + auto_migrate_db, + n_jobs=-1, kwargs_make_db={}, + verbose=False): + """ + do prep first time, involving downloads + # FIXME: Add github caching then add here + :return: + """ + if os.getenv("HARD_ASSERTS"): + assert langchain_mode not in ['MyData'], "Should not prep scratch/personal data" + + if langchain_mode in langchain_modes_intrinsic: + return None + + db_dir_exists = os.path.isdir(persist_directory) + user_path = langchain_mode_paths.get(langchain_mode) + + if db_dir_exists and user_path is None: + if verbose: + print("Prep: persist_directory=%s exists, using" % persist_directory, flush=True) + db, use_openai_embedding, hf_embedding_model = \ + get_existing_db(None, persist_directory, load_db_if_exists, + db_type, use_openai_embedding, + langchain_mode, langchain_mode_paths, langchain_mode_types, + hf_embedding_model, migrate_embedding_model, auto_migrate_db, + n_jobs=n_jobs) + else: + if db_dir_exists and user_path is not None: + if verbose: + print("Prep: persist_directory=%s exists, user_path=%s passed, adding any changed or new documents" % ( + persist_directory, user_path), flush=True) + elif not db_dir_exists: + if verbose: + print("Prep: persist_directory=%s does not exist, regenerating" % persist_directory, flush=True) + db = None + if langchain_mode in ['DriverlessAI docs']: + # FIXME: Could also just use dai_docs.pickle directly and upload that + get_dai_docs(from_hf=True) + + if langchain_mode in ['wiki']: + get_wiki_sources(first_para=kwargs_make_db['first_para'], text_limit=kwargs_make_db['text_limit']) + + langchain_kwargs = kwargs_make_db.copy() + langchain_kwargs.update(locals()) + db, num_new_sources, new_sources_metadata = make_db(**langchain_kwargs) + + return db + + +import posthog + +posthog.disabled = True + + +class FakeConsumer(object): + def __init__(self, *args, **kwargs): + pass + + def run(self): + pass + + def pause(self): + pass + + def upload(self): + pass + + def next(self): + pass + + def request(self, batch): + pass + + +posthog.Consumer = FakeConsumer + + +def check_update_chroma_embedding(db, + db_type, + use_openai_embedding, + hf_embedding_model, migrate_embedding_model, auto_migrate_db, + langchain_mode, langchain_mode_paths, langchain_mode_types, + n_jobs=-1): + changed_db = False + embed_tuple = load_embed(db=db) + if embed_tuple not in [(True, use_openai_embedding, hf_embedding_model), + (False, use_openai_embedding, hf_embedding_model)]: + print("Detected new embedding %s vs. %s %s, updating db: %s" % ( + use_openai_embedding, hf_embedding_model, embed_tuple, langchain_mode), flush=True) + # handle embedding changes + db_get = get_documents(db) + sources = [Document(page_content=result[0], metadata=result[1] or {}) + for result in zip(db_get['documents'], db_get['metadatas'])] + # delete index, has to be redone + persist_directory = db._persist_directory + shutil.move(persist_directory, persist_directory + "_" + str(uuid.uuid4()) + ".bak") + assert db_type in ['chroma', 'chroma_old'] + load_db_if_exists = False + db = get_db(sources, use_openai_embedding=use_openai_embedding, db_type=db_type, + persist_directory=persist_directory, load_db_if_exists=load_db_if_exists, + langchain_mode=langchain_mode, + langchain_mode_paths=langchain_mode_paths, + langchain_mode_types=langchain_mode_types, + collection_name=None, + hf_embedding_model=hf_embedding_model, + migrate_embedding_model=migrate_embedding_model, + auto_migrate_db=auto_migrate_db, + n_jobs=n_jobs, + ) + changed_db = True + print("Done updating db for new embedding: %s" % langchain_mode, flush=True) + + return db, changed_db + + +def migrate_meta_func(db, langchain_mode): + changed_db = False + db_get = get_documents(db) + # just check one doc + if len(db_get['metadatas']) > 0 and 'chunk_id' not in db_get['metadatas'][0]: + print("Detected old metadata, adding additional information", flush=True) + t0 = time.time() + # handle meta changes + [x.update(dict(chunk_id=x.get('chunk_id', 0))) for x in db_get['metadatas']] + client_collection = db._client.get_collection(name=db._collection.name, + embedding_function=db._collection._embedding_function) + client_collection.update(ids=db_get['ids'], metadatas=db_get['metadatas']) + # check + db_get = get_documents(db) + assert 'chunk_id' in db_get['metadatas'][0], "Failed to add meta" + changed_db = True + print("Done updating db for new meta: %s in %s seconds" % (langchain_mode, time.time() - t0), flush=True) + + return db, changed_db + + +def get_existing_db(db, persist_directory, + load_db_if_exists, db_type, use_openai_embedding, + langchain_mode, langchain_mode_paths, langchain_mode_types, + hf_embedding_model, + migrate_embedding_model, + auto_migrate_db=False, + verbose=False, check_embedding=True, migrate_meta=True, + n_jobs=-1): + if load_db_if_exists and db_type in ['chroma', 'chroma_old'] and os.path.isdir(persist_directory): + if os.path.isfile(os.path.join(persist_directory, 'chroma.sqlite3')): + must_migrate = False + elif os.path.isdir(os.path.join(persist_directory, 'index')): + must_migrate = True + else: + return db, use_openai_embedding, hf_embedding_model + chroma_settings = dict(is_persistent=True) + use_chromamigdb = False + if must_migrate: + if auto_migrate_db: + print("Detected chromadb<0.4 database, require migration, doing now....", flush=True) + from chroma_migrate.import_duckdb import migrate_from_duckdb + import chromadb + api = chromadb.PersistentClient(path=persist_directory) + did_migration = migrate_from_duckdb(api, persist_directory) + assert did_migration, "Failed to migrate chroma collection at %s, see https://docs.trychroma.com/migration for CLI tool" % persist_directory + elif have_chromamigdb: + print( + "Detected chroma<0.4 database but --auto_migrate_db=False, but detected chromamigdb package, so using old database that still requires duckdb", + flush=True) + chroma_settings = dict(chroma_db_impl="duckdb+parquet") + use_chromamigdb = True + else: + raise ValueError( + "Detected chromadb<0.4 database, require migration, but did not detect chromamigdb package or did not choose auto_migrate_db=False (see FAQ.md)") + + if db is None: + if verbose: + print("DO Loading db: %s" % langchain_mode, flush=True) + got_embedding, use_openai_embedding0, hf_embedding_model0 = load_embed(persist_directory=persist_directory) + if got_embedding: + use_openai_embedding, hf_embedding_model = use_openai_embedding0, hf_embedding_model0 + embedding = get_embedding(use_openai_embedding, hf_embedding_model=hf_embedding_model) + import logging + logging.getLogger("chromadb").setLevel(logging.ERROR) + if use_chromamigdb: + from chromamigdb.config import Settings + chroma_class = ChromaMig + else: + from chromadb.config import Settings + chroma_class = Chroma + client_settings = Settings(anonymized_telemetry=False, + **chroma_settings, + persist_directory=persist_directory) + db = chroma_class(persist_directory=persist_directory, embedding_function=embedding, + collection_name=langchain_mode.replace(' ', '_'), + client_settings=client_settings) + try: + db.similarity_search('') + except BaseException as e: + # migration when no embed_info + if 'Dimensionality of (768) does not match index dimensionality (384)' in str(e) or \ + 'Embedding dimension 768 does not match collection dimensionality 384' in str(e): + hf_embedding_model = "sentence-transformers/all-MiniLM-L6-v2" + embedding = get_embedding(use_openai_embedding, hf_embedding_model=hf_embedding_model) + db = chroma_class(persist_directory=persist_directory, embedding_function=embedding, + collection_name=langchain_mode.replace(' ', '_'), + client_settings=client_settings) + # should work now, let fail if not + db.similarity_search('') + save_embed(db, use_openai_embedding, hf_embedding_model) + else: + raise + + if verbose: + print("DONE Loading db: %s" % langchain_mode, flush=True) + else: + if not migrate_embedding_model: + # OVERRIDE embedding choices if could load embedding info when not migrating + got_embedding, use_openai_embedding, hf_embedding_model = load_embed(db=db) + if verbose: + print("USING already-loaded db: %s" % langchain_mode, flush=True) + if check_embedding: + db_trial, changed_db = check_update_chroma_embedding(db, + db_type, + use_openai_embedding, + hf_embedding_model, + migrate_embedding_model, + auto_migrate_db, + langchain_mode, + langchain_mode_paths, + langchain_mode_types, + n_jobs=n_jobs) + if changed_db: + db = db_trial + # only call persist if really changed db, else takes too long for large db + if db is not None: + db.persist() + clear_embedding(db) + save_embed(db, use_openai_embedding, hf_embedding_model) + if migrate_meta and db is not None: + db_trial, changed_db = migrate_meta_func(db, langchain_mode) + if changed_db: + db = db_trial + return db, use_openai_embedding, hf_embedding_model + return db, use_openai_embedding, hf_embedding_model + + +def clear_embedding(db): + if db is None: + return + # don't keep on GPU, wastes memory, push back onto CPU and only put back on GPU once again embed + try: + if hasattr(db._embedding_function, 'client') and hasattr(db._embedding_function.client, 'cpu'): + # only push back to CPU if each db/user has own embedding model, else if shared share on GPU + if hasattr(db._embedding_function.client, 'preload') and not db._embedding_function.client.preload: + db._embedding_function.client.cpu() + clear_torch_cache() + except RuntimeError as e: + print("clear_embedding error: %s" % ''.join(traceback.format_tb(e.__traceback__)), flush=True) + + +def make_db(**langchain_kwargs): + func_names = list(inspect.signature(_make_db).parameters) + missing_kwargs = [x for x in func_names if x not in langchain_kwargs] + defaults_db = {k: v.default for k, v in dict(inspect.signature(run_qa_db).parameters).items()} + for k in missing_kwargs: + if k in defaults_db: + langchain_kwargs[k] = defaults_db[k] + # final check for missing + missing_kwargs = [x for x in func_names if x not in langchain_kwargs] + assert not missing_kwargs, "Missing kwargs for make_db: %s" % missing_kwargs + # only keep actual used + langchain_kwargs = {k: v for k, v in langchain_kwargs.items() if k in func_names} + return _make_db(**langchain_kwargs) + + +embed_lock_name = 'embed.lock' + + +def get_embed_lock_file(db, persist_directory=None): + if hasattr(db, '_persist_directory') or persist_directory: + if persist_directory is None: + persist_directory = db._persist_directory + check_persist_directory(persist_directory) + base_path = os.path.join('locks', persist_directory) + base_path = makedirs(base_path, exist_ok=True, tmp_ok=True, use_base=True) + lock_file = os.path.join(base_path, embed_lock_name) + makedirs(os.path.dirname(lock_file)) + return lock_file + return None + + +def save_embed(db, use_openai_embedding, hf_embedding_model): + if hasattr(db, '_persist_directory'): + persist_directory = db._persist_directory + lock_file = get_embed_lock_file(db) + with filelock.FileLock(lock_file): + embed_info_file = os.path.join(persist_directory, 'embed_info') + with open(embed_info_file, 'wb') as f: + if isinstance(hf_embedding_model, str): + hf_embedding_model_save = hf_embedding_model + elif hasattr(hf_embedding_model, 'model_name'): + hf_embedding_model_save = hf_embedding_model.model_name + elif isinstance(hf_embedding_model, dict) and 'name' in hf_embedding_model: + hf_embedding_model_save = hf_embedding_model['name'] + elif isinstance(hf_embedding_model, dict) and 'name' in hf_embedding_model: + if os.getenv('HARD_ASSERTS'): + # unexpected in testing or normally + raise RuntimeError("HERE") + hf_embedding_model_save = 'hkunlp/instructor-large' + pickle.dump((use_openai_embedding, hf_embedding_model_save), f) + return use_openai_embedding, hf_embedding_model + + +def load_embed(db=None, persist_directory=None): + if hasattr(db, 'embeddings') and hasattr(db.embeddings, 'model_name'): + hf_embedding_model = db.embeddings.model_name if 'openai' not in db.embeddings.model_name.lower() else None + use_openai_embedding = hf_embedding_model is None + save_embed(db, use_openai_embedding, hf_embedding_model) + return True, use_openai_embedding, hf_embedding_model + if persist_directory is None: + persist_directory = db._persist_directory + embed_info_file = os.path.join(persist_directory, 'embed_info') + if os.path.isfile(embed_info_file): + lock_file = get_embed_lock_file(db, persist_directory=persist_directory) + with filelock.FileLock(lock_file): + with open(embed_info_file, 'rb') as f: + try: + use_openai_embedding, hf_embedding_model = pickle.load(f) + if not isinstance(hf_embedding_model, str): + # work-around bug introduced here: https://github.com/h2oai/h2ogpt/commit/54c4414f1ce3b5b7c938def651c0f6af081c66de + hf_embedding_model = 'hkunlp/instructor-large' + # fix file + save_embed(db, use_openai_embedding, hf_embedding_model) + got_embedding = True + except EOFError: + use_openai_embedding, hf_embedding_model = False, 'hkunlp/instructor-large' + got_embedding = False + if os.getenv('HARD_ASSERTS'): + # unexpected in testing or normally + raise + else: + # migration, assume defaults + use_openai_embedding, hf_embedding_model = False, "sentence-transformers/all-MiniLM-L6-v2" + got_embedding = False + assert isinstance(hf_embedding_model, str) + return got_embedding, use_openai_embedding, hf_embedding_model + + +def get_persist_directory(langchain_mode, langchain_type=None, db1s=None, dbs=None): + if langchain_mode in [LangChainMode.DISABLED.value, LangChainMode.LLM.value]: + # not None so join works but will fail to find db + return '', langchain_type + + userid = get_userid_direct(db1s) + username = get_username_direct(db1s) + + # sanity for bad code + assert userid != 'None' + assert username != 'None' + + dirid = username or userid + if langchain_type == LangChainTypes.SHARED.value and not dirid: + dirid = './' # just to avoid error + if langchain_type == LangChainTypes.PERSONAL.value and not dirid: + # e.g. from client when doing transient calls with MyData + if db1s is None: + # just trick to get filled locally + db1s = {LangChainMode.MY_DATA.value: [None, None, None]} + set_userid_direct(db1s, str(uuid.uuid4()), str(uuid.uuid4())) + userid = get_userid_direct(db1s) + username = get_username_direct(db1s) + dirid = username or userid + langchain_type = LangChainTypes.PERSONAL.value + + # deal with existing locations + user_base_dir = os.getenv('USERS_BASE_DIR', 'users') + persist_directory = os.path.join(user_base_dir, dirid, 'db_dir_%s' % langchain_mode) + if userid and \ + (os.path.isdir(persist_directory) or + db1s is not None and langchain_mode in db1s or + langchain_type == LangChainTypes.PERSONAL.value): + langchain_type = LangChainTypes.PERSONAL.value + persist_directory = makedirs(persist_directory, use_base=True) + check_persist_directory(persist_directory) + return persist_directory, langchain_type + + persist_directory = 'db_dir_%s' % langchain_mode + if (os.path.isdir(persist_directory) or + dbs is not None and langchain_mode in dbs or + langchain_type == LangChainTypes.SHARED.value): + # ensure consistent + langchain_type = LangChainTypes.SHARED.value + persist_directory = makedirs(persist_directory, use_base=True) + check_persist_directory(persist_directory) + return persist_directory, langchain_type + + # dummy return for prep_langchain() or full personal space + base_others = 'db_nonusers' + persist_directory = os.path.join(base_others, 'db_dir_%s' % str(uuid.uuid4())) + persist_directory = makedirs(persist_directory, use_base=True) + langchain_type = LangChainTypes.PERSONAL.value + + check_persist_directory(persist_directory) + return persist_directory, langchain_type + + +def check_persist_directory(persist_directory): + # deal with some cases when see intrinsic names being used as shared + for langchain_mode in langchain_modes_intrinsic: + if persist_directory == 'db_dir_%s' % langchain_mode: + raise RuntimeError("Illegal access to %s" % persist_directory) + + +def _make_db(use_openai_embedding=False, + hf_embedding_model=None, + migrate_embedding_model=False, + auto_migrate_db=False, + first_para=False, text_limit=None, + chunk=True, chunk_size=512, + + # urls + use_unstructured=True, + use_playwright=False, + use_selenium=False, + + # pdfs + use_pymupdf='auto', + use_unstructured_pdf='auto', + use_pypdf='auto', + enable_pdf_ocr='auto', + enable_pdf_doctr='auto', + try_pdf_as_html='auto', + + # images + enable_ocr=False, + enable_doctr=False, + enable_pix2struct=False, + enable_captions=True, + captions_model=None, + caption_loader=None, + doctr_loader=None, + pix2struct_loader=None, + + # json + jq_schema='.[]', + + langchain_mode=None, + langchain_mode_paths=None, + langchain_mode_types=None, + db_type='faiss', + load_db_if_exists=True, + db=None, + n_jobs=-1, + verbose=False): + assert hf_embedding_model is not None + user_path = langchain_mode_paths.get(langchain_mode) + langchain_type = langchain_mode_types.get(langchain_mode, LangChainTypes.EITHER.value) + persist_directory, langchain_type = get_persist_directory(langchain_mode, langchain_type=langchain_type) + langchain_mode_types[langchain_mode] = langchain_type + # see if can get persistent chroma db + db_trial, use_openai_embedding, hf_embedding_model = \ + get_existing_db(db, persist_directory, load_db_if_exists, db_type, + use_openai_embedding, + langchain_mode, langchain_mode_paths, langchain_mode_types, + hf_embedding_model, migrate_embedding_model, auto_migrate_db, verbose=verbose, + n_jobs=n_jobs) + if db_trial is not None: + db = db_trial + + sources = [] + if not db: + chunk_sources = functools.partial(_chunk_sources, chunk=chunk, chunk_size=chunk_size, db_type=db_type) + if langchain_mode in ['wiki_full']: + from read_wiki_full import get_all_documents + small_test = None + print("Generating new wiki", flush=True) + sources1 = get_all_documents(small_test=small_test, n_jobs=os.cpu_count() // 2) + print("Got new wiki", flush=True) + sources1 = chunk_sources(sources1, chunk=chunk) + print("Chunked new wiki", flush=True) + sources.extend(sources1) + elif langchain_mode in ['wiki']: + sources1 = get_wiki_sources(first_para=first_para, text_limit=text_limit) + sources1 = chunk_sources(sources1, chunk=chunk) + sources.extend(sources1) + elif langchain_mode in ['github h2oGPT']: + # sources = get_github_docs("dagster-io", "dagster") + sources1 = get_github_docs("h2oai", "h2ogpt") + # FIXME: always chunk for now + sources1 = chunk_sources(sources1) + sources.extend(sources1) + elif langchain_mode in ['DriverlessAI docs']: + sources1 = get_dai_docs(from_hf=True) + # FIXME: DAI docs are already chunked well, should only chunk more if over limit + sources1 = chunk_sources(sources1, chunk=False) + sources.extend(sources1) + if user_path: + # UserData or custom, which has to be from user's disk + if db is not None: + # NOTE: Ignore file names for now, only go by hash ids + # existing_files = get_existing_files(db) + existing_files = [] + existing_hash_ids = get_existing_hash_ids(db) + else: + # pretend no existing files so won't filter + existing_files = [] + existing_hash_ids = [] + # chunk internally for speed over multiple docs + # FIXME: If first had old Hash=None and switch embeddings, + # then re-embed, and then hit here and reload so have hash, and then re-embed. + sources1 = path_to_docs(user_path, n_jobs=n_jobs, chunk=chunk, chunk_size=chunk_size, + # urls + use_unstructured=use_unstructured, + use_playwright=use_playwright, + use_selenium=use_selenium, + + # pdfs + use_pymupdf=use_pymupdf, + use_unstructured_pdf=use_unstructured_pdf, + use_pypdf=use_pypdf, + enable_pdf_ocr=enable_pdf_ocr, + enable_pdf_doctr=enable_pdf_doctr, + try_pdf_as_html=try_pdf_as_html, + + # images + enable_ocr=enable_ocr, + enable_doctr=enable_doctr, + enable_pix2struct=enable_pix2struct, + enable_captions=enable_captions, + captions_model=captions_model, + caption_loader=caption_loader, + doctr_loader=doctr_loader, + pix2struct_loader=pix2struct_loader, + + # json + jq_schema=jq_schema, + + existing_files=existing_files, existing_hash_ids=existing_hash_ids, + db_type=db_type) + new_metadata_sources = set([x.metadata['source'] for x in sources1]) + if new_metadata_sources: + if os.getenv('NO_NEW_FILES') is not None: + raise RuntimeError("Expected no new files! %s" % new_metadata_sources) + print("Loaded %s new files as sources to add to %s" % (len(new_metadata_sources), langchain_mode), + flush=True) + if verbose: + print("Files added: %s" % '\n'.join(new_metadata_sources), flush=True) + sources.extend(sources1) + if len(sources) > 0 and os.getenv('NO_NEW_FILES') is not None: + raise RuntimeError("Expected no new files! %s" % langchain_mode) + if len(sources) == 0 and os.getenv('SHOULD_NEW_FILES') is not None: + raise RuntimeError("Expected new files! %s" % langchain_mode) + print("Loaded %s sources for potentially adding to %s" % (len(sources), langchain_mode), flush=True) + + # see if got sources + if not sources: + if verbose: + if db is not None: + print("langchain_mode %s has no new sources, nothing to add to db" % langchain_mode, flush=True) + else: + print("langchain_mode %s has no sources, not making new db" % langchain_mode, flush=True) + return db, 0, [] + if verbose: + if db is not None: + print("Generating db", flush=True) + else: + print("Adding to db", flush=True) + if not db: + if sources: + db = get_db(sources, use_openai_embedding=use_openai_embedding, db_type=db_type, + persist_directory=persist_directory, + langchain_mode=langchain_mode, + langchain_mode_paths=langchain_mode_paths, + langchain_mode_types=langchain_mode_types, + hf_embedding_model=hf_embedding_model, + migrate_embedding_model=migrate_embedding_model, + auto_migrate_db=auto_migrate_db, + n_jobs=n_jobs) + if verbose: + print("Generated db", flush=True) + elif langchain_mode not in langchain_modes_intrinsic: + print("Did not generate db for %s since no sources" % langchain_mode, flush=True) + new_sources_metadata = [x.metadata for x in sources] + elif user_path is not None: + print("Existing db, potentially adding %s sources from user_path=%s" % (len(sources), user_path), flush=True) + db, num_new_sources, new_sources_metadata = add_to_db(db, sources, db_type=db_type, + use_openai_embedding=use_openai_embedding, + hf_embedding_model=hf_embedding_model) + print("Existing db, added %s new sources from user_path=%s" % (num_new_sources, user_path), flush=True) + else: + new_sources_metadata = [x.metadata for x in sources] + + return db, len(new_sources_metadata), new_sources_metadata + + +def get_metadatas(db): + metadatas = [] + from langchain.vectorstores import FAISS + if isinstance(db, FAISS): + metadatas = [v.metadata for k, v in db.docstore._dict.items()] + elif isinstance(db, Chroma) or isinstance(db, ChromaMig) or ChromaMig.__name__ in str(db): + metadatas = get_documents(db)['metadatas'] + elif db is not None: + # FIXME: Hack due to https://github.com/weaviate/weaviate/issues/1947 + # seems no way to get all metadata, so need to avoid this approach for weaviate + metadatas = [x.metadata for x in db.similarity_search("", k=10000)] + return metadatas + + +def get_db_lock_file(db, lock_type='getdb'): + if hasattr(db, '_persist_directory'): + persist_directory = db._persist_directory + check_persist_directory(persist_directory) + base_path = os.path.join('locks', persist_directory) + base_path = makedirs(base_path, exist_ok=True, tmp_ok=True, use_base=True) + lock_file = os.path.join(base_path, "%s.lock" % lock_type) + makedirs(os.path.dirname(lock_file)) # ensure made + return lock_file + return None + + +def get_documents(db): + if hasattr(db, '_persist_directory'): + lock_file = get_db_lock_file(db) + with filelock.FileLock(lock_file): + # get segfaults and other errors when multiple threads access this + return _get_documents(db) + else: + return _get_documents(db) + + +def _get_documents(db): + from langchain.vectorstores import FAISS + if isinstance(db, FAISS): + documents = [v for k, v in db.docstore._dict.items()] + documents = dict(documents=documents) + elif isinstance(db, Chroma) or isinstance(db, ChromaMig) or ChromaMig.__name__ in str(db): + documents = db.get() + else: + # FIXME: Hack due to https://github.com/weaviate/weaviate/issues/1947 + # seems no way to get all metadata, so need to avoid this approach for weaviate + documents = [x for x in db.similarity_search("", k=10000)] + documents = dict(documents=documents) + return documents + + +def get_docs_and_meta(db, top_k_docs, filter_kwargs={}, text_context_list=None): + if hasattr(db, '_persist_directory'): + lock_file = get_db_lock_file(db) + with filelock.FileLock(lock_file): + return _get_docs_and_meta(db, top_k_docs, filter_kwargs=filter_kwargs, text_context_list=text_context_list) + else: + return _get_docs_and_meta(db, top_k_docs, filter_kwargs=filter_kwargs, text_context_list=text_context_list) + + +def _get_docs_and_meta(db, top_k_docs, filter_kwargs={}, text_context_list=None): + db_documents = [] + db_metadatas = [] + + if text_context_list: + db_documents += [x.page_content if hasattr(x, 'page_content') else x for x in text_context_list] + db_metadatas += [x.metadata if hasattr(x, 'metadata') else {} for x in text_context_list] + + from langchain.vectorstores import FAISS + if isinstance(db, Chroma) or isinstance(db, ChromaMig) or ChromaMig.__name__ in str(db): + db_get = db._collection.get(where=filter_kwargs.get('filter')) + db_metadatas += db_get['metadatas'] + db_documents += db_get['documents'] + elif isinstance(db, FAISS): + import itertools + db_metadatas += get_metadatas(db) + # FIXME: FAISS has no filter + if top_k_docs == -1: + db_documents += list(db.docstore._dict.values()) + else: + # slice dict first + db_documents += list(dict(itertools.islice(db.docstore._dict.items(), top_k_docs)).values()) + elif db is not None: + db_metadatas += get_metadatas(db) + db_documents += get_documents(db)['documents'] + + return db_documents, db_metadatas + + +def get_existing_files(db): + metadatas = get_metadatas(db) + metadata_sources = set([x['source'] for x in metadatas]) + return metadata_sources + + +def get_existing_hash_ids(db): + metadatas = get_metadatas(db) + # assume consistency, that any prior hashed source was single hashed file at the time among all source chunks + metadata_hash_ids = {os.path.normpath(x['source']): x.get('hashid') for x in metadatas} + return metadata_hash_ids + + +def run_qa_db(**kwargs): + func_names = list(inspect.signature(_run_qa_db).parameters) + # hard-coded defaults + kwargs['answer_with_sources'] = kwargs.get('answer_with_sources', True) + kwargs['show_rank'] = kwargs.get('show_rank', False) + kwargs['show_accordions'] = kwargs.get('show_accordions', True) + kwargs['show_link_in_sources'] = kwargs.get('show_link_in_sources', True) + kwargs['top_k_docs_max_show'] = kwargs.get('top_k_docs_max_show', 10) + kwargs['llamacpp_dict'] = {} # shouldn't be required unless from test using _run_qa_db + missing_kwargs = [x for x in func_names if x not in kwargs] + assert not missing_kwargs, "Missing kwargs for run_qa_db: %s" % missing_kwargs + # only keep actual used + kwargs = {k: v for k, v in kwargs.items() if k in func_names} + try: + return _run_qa_db(**kwargs) + finally: + clear_torch_cache() + + +def _run_qa_db(query=None, + iinput=None, + context=None, + use_openai_model=False, use_openai_embedding=False, + first_para=False, text_limit=None, top_k_docs=4, chunk=True, chunk_size=512, + + # urls + use_unstructured=True, + use_playwright=False, + use_selenium=False, + + # pdfs + use_pymupdf='auto', + use_unstructured_pdf='auto', + use_pypdf='auto', + enable_pdf_ocr='auto', + enable_pdf_doctr='auto', + try_pdf_as_html='auto', + + # images + enable_ocr=False, + enable_doctr=False, + enable_pix2struct=False, + enable_captions=True, + captions_model=None, + caption_loader=None, + doctr_loader=None, + pix2struct_loader=None, + + # json + jq_schema='.[]', + + langchain_mode_paths={}, + langchain_mode_types={}, + detect_user_path_changes_every_query=False, + db_type=None, + model_name=None, model=None, tokenizer=None, inference_server=None, + langchain_only_model=False, + hf_embedding_model=None, + migrate_embedding_model=False, + auto_migrate_db=False, + stream_output=False, + async_output=True, + num_async=3, + prompter=None, + prompt_type=None, + prompt_dict=None, + answer_with_sources=True, + append_sources_to_answer=True, + cut_distance=1.64, + add_chat_history_to_context=True, + add_search_to_context=False, + keep_sources_in_context=False, + memory_restriction_level=0, + system_prompt='', + sanitize_bot_response=False, + show_rank=False, + show_accordions=True, + show_link_in_sources=True, + top_k_docs_max_show=10, + use_llm_if_no_docs=True, + load_db_if_exists=False, + db=None, + do_sample=False, + temperature=0.1, + top_k=40, + top_p=0.7, + num_beams=1, + max_new_tokens=512, + min_new_tokens=1, + early_stopping=False, + max_time=180, + repetition_penalty=1.0, + num_return_sequences=1, + langchain_mode=None, + langchain_action=None, + langchain_agents=None, + document_subset=DocumentSubset.Relevant.name, + document_choice=[DocumentChoice.ALL.value], + pre_prompt_query=None, + prompt_query=None, + pre_prompt_summary=None, + prompt_summary=None, + text_context_list=None, + chat_conversation=None, + visible_models=None, + h2ogpt_key=None, + docs_ordering_type='reverse_ucurve_sort', + min_max_new_tokens=256, + + n_jobs=-1, + llamacpp_dict=None, + verbose=False, + cli=False, + lora_weights='', + auto_reduce_chunks=True, + max_chunks=100, + total_tokens_for_docs=None, + headsize=50, + ): + """ + + :param query: + :param use_openai_model: + :param use_openai_embedding: + :param first_para: + :param text_limit: + :param top_k_docs: + :param chunk: + :param chunk_size: + :param langchain_mode_paths: dict of langchain_mode -> user path to glob recursively from + :param db_type: 'faiss' for in-memory + 'chroma' (for chroma >= 0.4) + 'chroma_old' (for chroma < 0.4) + 'weaviate' for persisted on disk + :param model_name: model name, used to switch behaviors + :param model: pre-initialized model, else will make new one + :param tokenizer: pre-initialized tokenizer, else will make new one. Required not None if model is not None + :param answer_with_sources + :return: + """ + t_run = time.time() + if stream_output: + # threads and asyncio don't mix + async_output = False + if langchain_action in [LangChainAction.QUERY.value]: + # only summarization supported + async_output = False + + # in case None, e.g. lazy client, then set based upon actual model + pre_prompt_query, prompt_query, pre_prompt_summary, prompt_summary = \ + get_langchain_prompts(pre_prompt_query, prompt_query, + pre_prompt_summary, prompt_summary, + model_name, inference_server, + llamacpp_dict.get('model_path_llama')) + + assert db_type is not None + assert hf_embedding_model is not None + assert langchain_mode_paths is not None + assert langchain_mode_types is not None + if model is not None: + assert model_name is not None # require so can make decisions + assert query is not None + assert prompter is not None or prompt_type is not None or model is None # if model is None, then will generate + if prompter is not None: + prompt_type = prompter.prompt_type + prompt_dict = prompter.prompt_dict + if model is not None: + assert prompt_type is not None + if prompt_type == PromptType.custom.name: + assert prompt_dict is not None # should at least be {} or '' + else: + prompt_dict = '' + + if LangChainAgent.SEARCH.value in langchain_agents and 'llama' in model_name.lower(): + system_prompt = """You are a zero shot react agent. +Consider to prompt of Question that was original query from the user. +Respond to prompt of Thought with a thought that may lead to a reasonable new action choice. +Respond to prompt of Action with an action to take out of the tools given, giving exactly single word for the tool name. +Respond to prompt of Action Input with an input to give the tool. +Consider to prompt of Observation that was response from the tool. +Repeat this Thought, Action, Action Input, Observation, Thought sequence several times with new and different thoughts and actions each time, do not repeat. +Once satisfied that the thoughts, responses are sufficient to answer the question, then respond to prompt of Thought with: I now know the final answer +Respond to prompt of Final Answer with your final high-quality bullet list answer to the original query. +""" + prompter.system_prompt = system_prompt + + assert len(set(gen_hyper).difference(inspect.signature(get_llm).parameters)) == 0 + # pass in context to LLM directly, since already has prompt_type structure + # can't pass through langchain in get_chain() to LLM: https://github.com/hwchase17/langchain/issues/6638 + llm, model_name, streamer, prompt_type_out, async_output, only_new_text = \ + get_llm(use_openai_model=use_openai_model, model_name=model_name, + model=model, + tokenizer=tokenizer, + inference_server=inference_server, + langchain_only_model=langchain_only_model, + stream_output=stream_output, + async_output=async_output, + num_async=num_async, + do_sample=do_sample, + temperature=temperature, + top_k=top_k, + top_p=top_p, + num_beams=num_beams, + max_new_tokens=max_new_tokens, + min_new_tokens=min_new_tokens, + early_stopping=early_stopping, + max_time=max_time, + repetition_penalty=repetition_penalty, + num_return_sequences=num_return_sequences, + prompt_type=prompt_type, + prompt_dict=prompt_dict, + prompter=prompter, + context=context, + iinput=iinput, + sanitize_bot_response=sanitize_bot_response, + system_prompt=system_prompt, + visible_models=visible_models, + h2ogpt_key=h2ogpt_key, + min_max_new_tokens=min_max_new_tokens, + n_jobs=n_jobs, + llamacpp_dict=llamacpp_dict, + cli=cli, + verbose=verbose, + ) + # in case change, override original prompter + if hasattr(llm, 'prompter'): + prompter = llm.prompter + if hasattr(llm, 'pipeline') and hasattr(llm.pipeline, 'prompter'): + prompter = llm.pipeline.prompter + + if prompter is None: + if prompt_type is None: + prompt_type = prompt_type_out + # get prompter + chat = True # FIXME? + prompter = Prompter(prompt_type, prompt_dict, debug=False, chat=chat, stream_output=stream_output, + system_prompt=system_prompt) + + use_docs_planned = False + scores = [] + chain = None + + # basic version of prompt without docs etc. + data_point = dict(context=context, instruction=query, input=iinput) + prompt_basic = prompter.generate_prompt(data_point) + + if isinstance(document_choice, str): + # support string as well + document_choice = [document_choice] + + func_names = list(inspect.signature(get_chain).parameters) + sim_kwargs = {k: v for k, v in locals().items() if k in func_names} + missing_kwargs = [x for x in func_names if x not in sim_kwargs] + assert not missing_kwargs, "Missing: %s" % missing_kwargs + docs, chain, scores, \ + use_docs_planned, num_docs_before_cut, \ + use_llm_if_no_docs, llm_mode, top_k_docs_max_show = \ + get_chain(**sim_kwargs) + if document_subset in non_query_commands: + formatted_doc_chunks = '\n\n'.join([get_url(x) + '\n\n' + x.page_content for x in docs]) + if not formatted_doc_chunks and not use_llm_if_no_docs: + yield dict(prompt=prompt_basic, response="No sources", sources='', num_prompt_tokens=0) + return + # if no souces, outside gpt_langchain, LLM will be used with '' input + scores = [1] * len(docs) + get_answer_args = tuple([query, docs, formatted_doc_chunks, scores, show_rank, + answer_with_sources, + append_sources_to_answer]) + get_answer_kwargs = dict(show_accordions=show_accordions, + show_link_in_sources=show_link_in_sources, + top_k_docs_max_show=top_k_docs_max_show, + docs_ordering_type=docs_ordering_type, + num_docs_before_cut=num_docs_before_cut, + verbose=verbose) + ret, extra = get_sources_answer(*get_answer_args, **get_answer_kwargs) + yield dict(prompt=prompt_basic, response=formatted_doc_chunks, sources=extra, num_prompt_tokens=0) + return + if not use_llm_if_no_docs: + if not docs and langchain_action in [LangChainAction.SUMMARIZE_MAP.value, + LangChainAction.SUMMARIZE_ALL.value, + LangChainAction.SUMMARIZE_REFINE.value]: + ret = 'No relevant documents to summarize.' if num_docs_before_cut else 'No documents to summarize.' + extra = '' + yield dict(prompt=prompt_basic, response=ret, sources=extra, num_prompt_tokens=0) + return + if not docs and not llm_mode: + ret = 'No relevant documents to query (for chatting with LLM, pick Resources->Collections->LLM).' if num_docs_before_cut else 'No documents to query (for chatting with LLM, pick Resources->Collections->LLM).' + extra = '' + yield dict(prompt=prompt_basic, response=ret, sources=extra, num_prompt_tokens=0) + return + + if chain is None and not langchain_only_model: + # here if no docs at all and not HF type + # can only return if HF type + return + + # context stuff similar to used in evaluate() + import torch + device, torch_dtype, context_class = get_device_dtype() + conditional_type = hasattr(llm, 'pipeline') and hasattr(llm.pipeline, 'model') and hasattr(llm.pipeline.model, + 'conditional_type') and llm.pipeline.model.conditional_type + with torch.no_grad(): + have_lora_weights = lora_weights not in [no_lora_str, '', None] + context_class_cast = NullContext if device == 'cpu' or have_lora_weights else torch.autocast + if conditional_type: + # issues when casting to float16, can mess up t5 model, e.g. only when not streaming, or other odd behaviors + context_class_cast = NullContext + with context_class_cast(device): + if stream_output and streamer: + answer = None + import queue + bucket = queue.Queue() + thread = EThread(target=chain, streamer=streamer, bucket=bucket) + thread.start() + outputs = "" + try: + for new_text in streamer: + # print("new_text: %s" % new_text, flush=True) + if bucket.qsize() > 0 or thread.exc: + thread.join() + outputs += new_text + if prompter: # and False: # FIXME: pipeline can already use prompter + if conditional_type: + if prompter.botstr: + prompt = prompter.botstr + output_with_prompt = prompt + outputs + only_new_text = False + else: + prompt = None + output_with_prompt = outputs + only_new_text = True + else: + prompt = None # FIXME + output_with_prompt = outputs + # don't specify only_new_text here, use get_llm() value + output1 = prompter.get_response(output_with_prompt, prompt=prompt, + only_new_text=only_new_text, + sanitize_bot_response=sanitize_bot_response) + yield dict(prompt=prompt, response=output1, sources='', num_prompt_tokens=0) + else: + yield dict(prompt=prompt, response=outputs, sources='', num_prompt_tokens=0) + except BaseException: + # if any exception, raise that exception if was from thread, first + if thread.exc: + raise thread.exc + raise + finally: + # in case no exception and didn't join with thread yet, then join + if not thread.exc: + answer = thread.join() + if isinstance(answer, dict): + if 'output_text' in answer: + answer = answer['output_text'] + elif 'output' in answer: + answer = answer['output'] + # in case raise StopIteration or broke queue loop in streamer, but still have exception + if thread.exc: + raise thread.exc + else: + if async_output: + import asyncio + answer = asyncio.run(chain()) + else: + answer = chain() + if isinstance(answer, dict): + if 'output_text' in answer: + answer = answer['output_text'] + elif 'output' in answer: + answer = answer['output'] + + get_answer_args = tuple([query, docs, answer, scores, show_rank, + answer_with_sources, + append_sources_to_answer]) + get_answer_kwargs = dict(show_accordions=show_accordions, + show_link_in_sources=show_link_in_sources, + top_k_docs_max_show=top_k_docs_max_show, + docs_ordering_type=docs_ordering_type, + num_docs_before_cut=num_docs_before_cut, + verbose=verbose, + t_run=t_run, + count_input_tokens=llm.count_input_tokens + if hasattr(llm, 'count_input_tokens') else None, + count_output_tokens=llm.count_output_tokens + if hasattr(llm, 'count_output_tokens') else None) + + t_run = time.time() - t_run + + # for final yield, get real prompt used + if hasattr(llm, 'prompter') and llm.prompter.prompt is not None: + prompt = llm.prompter.prompt + else: + prompt = prompt_basic + num_prompt_tokens = get_token_count(prompt, tokenizer) + + if not use_docs_planned: + ret = answer + extra = '' + yield dict(prompt=prompt, response=ret, sources=extra, num_prompt_tokens=num_prompt_tokens) + elif answer is not None: + ret, extra = get_sources_answer(*get_answer_args, **get_answer_kwargs) + yield dict(prompt=prompt, response=ret, sources=extra, num_prompt_tokens=num_prompt_tokens) + return + + +def get_docs_with_score(query, k_db, filter_kwargs, db, db_type, text_context_list=None, verbose=False): + docs_with_score = [] + got_db_docs = False + + if text_context_list: + docs_with_score += [(x, x.metadata.get('score', 1.0)) for x in text_context_list] + + # deal with bug in chroma where if (say) 234 doc chunks and ask for 233+ then fails due to reduction misbehavior + if hasattr(db, '_embedding_function') and isinstance(db._embedding_function, FakeEmbeddings): + top_k_docs = -1 + # don't add text_context_list twice + db_documents, db_metadatas = get_docs_and_meta(db, top_k_docs, filter_kwargs=filter_kwargs, + text_context_list=None) + # sort by order given to parser (file_id) and any chunk_id if chunked + doc_file_ids = [x.get('file_id', 0) for x in db_metadatas] + doc_chunk_ids = [x.get('chunk_id', 0) for x in db_metadatas] + docs_with_score_fake = [(Document(page_content=result[0], metadata=result[1] or {}), 1.0) + for result in zip(db_documents, db_metadatas)] + docs_with_score_fake = [x for fx, cx, x in + sorted(zip(doc_file_ids, doc_chunk_ids, docs_with_score_fake), + key=lambda x: (x[0], x[1])) + ] + got_db_docs |= len(docs_with_score_fake) > 0 + docs_with_score += docs_with_score_fake + elif db is not None and db_type in ['chroma', 'chroma_old']: + while True: + try: + docs_with_score_chroma = db.similarity_search_with_score(query, k=k_db, **filter_kwargs) + break + except (RuntimeError, AttributeError) as e: + # AttributeError is for people with wrong version of langchain + if verbose: + print("chroma bug: %s" % str(e), flush=True) + if k_db == 1: + raise + if k_db > 500: + k_db -= 200 + elif k_db > 100: + k_db -= 50 + elif k_db > 10: + k_db -= 5 + else: + k_db -= 1 + k_db = max(1, k_db) + got_db_docs |= len(docs_with_score_chroma) > 0 + docs_with_score += docs_with_score_chroma + elif db is not None: + docs_with_score_other = db.similarity_search_with_score(query, k=k_db, **filter_kwargs) + got_db_docs |= len(docs_with_score_other) > 0 + docs_with_score += docs_with_score_other + + # set in metadata original order of docs + [x[0].metadata.update(orig_index=ii) for ii, x in enumerate(docs_with_score)] + + return docs_with_score, got_db_docs + + +def get_chain(query=None, + iinput=None, + context=None, # FIXME: https://github.com/hwchase17/langchain/issues/6638 + use_openai_model=False, use_openai_embedding=False, + first_para=False, text_limit=None, top_k_docs=4, chunk=True, chunk_size=512, + + # urls + use_unstructured=True, + use_playwright=False, + use_selenium=False, + + # pdfs + use_pymupdf='auto', + use_unstructured_pdf='auto', + use_pypdf='auto', + enable_pdf_ocr='auto', + enable_pdf_doctr='auto', + try_pdf_as_html='auto', + + # images + enable_ocr=False, + enable_doctr=False, + enable_pix2struct=False, + enable_captions=True, + captions_model=None, + caption_loader=None, + doctr_loader=None, + pix2struct_loader=None, + + # json + jq_schema='.[]', + + langchain_mode_paths=None, + langchain_mode_types=None, + detect_user_path_changes_every_query=False, + db_type='faiss', + model_name=None, + inference_server='', + max_new_tokens=None, + langchain_only_model=False, + hf_embedding_model=None, + migrate_embedding_model=False, + auto_migrate_db=False, + prompter=None, + prompt_type=None, + prompt_dict=None, + system_prompt=None, + cut_distance=1.1, + add_chat_history_to_context=True, # FIXME: https://github.com/hwchase17/langchain/issues/6638 + add_search_to_context=False, + keep_sources_in_context=False, + memory_restriction_level=0, + top_k_docs_max_show=10, + + load_db_if_exists=False, + db=None, + langchain_mode=None, + langchain_action=None, + langchain_agents=None, + document_subset=DocumentSubset.Relevant.name, + document_choice=[DocumentChoice.ALL.value], + pre_prompt_query=None, + prompt_query=None, + pre_prompt_summary=None, + prompt_summary=None, + text_context_list=None, + chat_conversation=None, + + n_jobs=-1, + # beyond run_db_query: + llm=None, + tokenizer=None, + verbose=False, + docs_ordering_type='reverse_ucurve_sort', + min_max_new_tokens=256, + stream_output=True, + async_output=True, + + # local + auto_reduce_chunks=True, + max_chunks=100, + total_tokens_for_docs=None, + use_llm_if_no_docs=None, + headsize=50, + ): + if inference_server is None: + inference_server = '' + assert hf_embedding_model is not None + assert langchain_agents is not None # should be at least [] + if text_context_list is None: + text_context_list = [] + + # default value: + llm_mode = langchain_mode in ['Disabled', 'LLM'] and len(text_context_list) == 0 + query_action = langchain_action == LangChainAction.QUERY.value + summarize_action = langchain_action in [LangChainAction.SUMMARIZE_MAP.value, + LangChainAction.SUMMARIZE_ALL.value, + LangChainAction.SUMMARIZE_REFINE.value] + + if len(text_context_list) > 0: + # turn into documents to make easy to manage and add meta + # try to account for summarization vs. query + chunk_id = 0 if query_action else -1 + text_context_list = [ + Document(page_content=x, metadata=dict(source='text_context_list', score=1.0, chunk_id=chunk_id)) for x + in text_context_list] + + if add_search_to_context: + params = { + "engine": "duckduckgo", + "gl": "us", + "hl": "en", + } + search = H2OSerpAPIWrapper(params=params) + # if doing search, allow more docs + docs_search, top_k_docs = search.get_search_documents(query, + query_action=query_action, + chunk=chunk, chunk_size=chunk_size, + db_type=db_type, + headsize=headsize, + top_k_docs=top_k_docs) + text_context_list = docs_search + text_context_list + add_search_to_context &= len(docs_search) > 0 + top_k_docs_max_show = max(top_k_docs_max_show, len(docs_search)) + + if len(text_context_list) > 0: + llm_mode = False + use_llm_if_no_docs = True + + from src.output_parser import H2OMRKLOutputParser + from langchain.agents import AgentType, load_tools, initialize_agent, create_vectorstore_agent, \ + create_pandas_dataframe_agent, create_json_agent, create_csv_agent + from langchain.agents.agent_toolkits import VectorStoreInfo, VectorStoreToolkit, create_python_agent, JsonToolkit + if LangChainAgent.SEARCH.value in langchain_agents: + output_parser = H2OMRKLOutputParser() + tools = load_tools(["serpapi"], llm=llm, serpapi_api_key=os.environ.get('SERPAPI_API_KEY')) + if inference_server.startswith('openai'): + agent_type = AgentType.OPENAI_FUNCTIONS + agent_executor_kwargs = {"handle_parsing_errors": True, 'output_parser': output_parser} + else: + agent_type = AgentType.ZERO_SHOT_REACT_DESCRIPTION + agent_executor_kwargs = {'output_parser': output_parser} + chain = initialize_agent(tools, llm, agent=agent_type, + agent_executor_kwargs=agent_executor_kwargs, + agent_kwargs=dict(output_parser=output_parser, + format_instructions=output_parser.get_format_instructions()), + output_parser=output_parser, + max_iterations=10, + verbose=True) + chain_kwargs = dict(input=query) + target = wrapped_partial(chain, chain_kwargs) + + docs = [] + scores = [] + use_docs_planned = False + num_docs_before_cut = 0 + use_llm_if_no_docs = True + return docs, target, scores, use_docs_planned, num_docs_before_cut, use_llm_if_no_docs, llm_mode, top_k_docs_max_show + + if LangChainAgent.COLLECTION.value in langchain_agents: + output_parser = H2OMRKLOutputParser() + vectorstore_info = VectorStoreInfo( + name=langchain_mode, + description="DataBase of text from PDFs, Image Captions, or web URL content", + vectorstore=db, + ) + toolkit = VectorStoreToolkit(vectorstore_info=vectorstore_info) + chain = create_vectorstore_agent(llm=llm, toolkit=toolkit, + agent_executor_kwargs=dict(output_parser=output_parser), + verbose=True) + + chain_kwargs = dict(input=query) + target = wrapped_partial(chain, chain_kwargs) + + docs = [] + scores = [] + use_docs_planned = False + num_docs_before_cut = 0 + use_llm_if_no_docs = True + return docs, target, scores, use_docs_planned, num_docs_before_cut, use_llm_if_no_docs, llm_mode, top_k_docs_max_show + + if LangChainAgent.PYTHON.value in langchain_agents and inference_server.startswith('openai'): + chain = create_python_agent( + llm=llm, + tool=PythonREPLTool(), + verbose=True, + agent_type=AgentType.OPENAI_FUNCTIONS, + agent_executor_kwargs={"handle_parsing_errors": True}, + ) + + chain_kwargs = dict(input=query) + target = wrapped_partial(chain, chain_kwargs) + + docs = [] + scores = [] + use_docs_planned = False + num_docs_before_cut = 0 + use_llm_if_no_docs = True + return docs, target, scores, use_docs_planned, num_docs_before_cut, use_llm_if_no_docs, llm_mode, top_k_docs_max_show + + if LangChainAgent.PANDAS.value in langchain_agents and inference_server.startswith('openai_chat'): + # FIXME: DATA + df = pd.DataFrame(None) + chain = create_pandas_dataframe_agent( + llm, + df, + verbose=True, + agent_type=AgentType.OPENAI_FUNCTIONS, + ) + + chain_kwargs = dict(input=query) + target = wrapped_partial(chain, chain_kwargs) + + docs = [] + scores = [] + use_docs_planned = False + num_docs_before_cut = 0 + use_llm_if_no_docs = True + return docs, target, scores, use_docs_planned, num_docs_before_cut, use_llm_if_no_docs, llm_mode, top_k_docs_max_show + + if isinstance(document_choice, str): + document_choice = [document_choice] + if document_choice and document_choice[0] == DocumentChoice.ALL.value: + document_choice_agent = document_choice[1:] + else: + document_choice_agent = document_choice + document_choice_agent = [x for x in document_choice_agent if x.endswith('.json')] + if LangChainAgent.JSON.value in \ + langchain_agents and \ + inference_server.startswith('openai_chat') and \ + len(document_choice_agent) == 1 and \ + document_choice_agent[0].endswith('.json'): + # with open('src/openai.yaml') as f: + # data = yaml.load(f, Loader=yaml.FullLoader) + with open(document_choice[0], 'rt') as f: + data = json.loads(f.read()) + json_spec = JsonSpec(dict_=data, max_value_length=4000) + json_toolkit = JsonToolkit(spec=json_spec) + + chain = create_json_agent( + llm=llm, toolkit=json_toolkit, verbose=True + ) + + chain_kwargs = dict(input=query) + target = wrapped_partial(chain, chain_kwargs) + + docs = [] + scores = [] + use_docs_planned = False + num_docs_before_cut = 0 + use_llm_if_no_docs = True + return docs, target, scores, use_docs_planned, num_docs_before_cut, use_llm_if_no_docs, llm_mode, top_k_docs_max_show + + if isinstance(document_choice, str): + document_choice = [document_choice] + if document_choice and document_choice[0] == DocumentChoice.ALL.value: + document_choice_agent = document_choice[1:] + else: + document_choice_agent = document_choice + document_choice_agent = [x for x in document_choice_agent if x.endswith('.csv')] + if LangChainAgent.CSV.value in langchain_agents and len(document_choice_agent) == 1 and document_choice_agent[ + 0].endswith( + '.csv'): + data_file = document_choice[0] + if inference_server.startswith('openai_chat'): + chain = create_csv_agent( + llm, + data_file, + verbose=True, + agent_type=AgentType.OPENAI_FUNCTIONS, + ) + else: + chain = create_csv_agent( + llm, + data_file, + verbose=True, + agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION, + ) + chain_kwargs = dict(input=query) + target = wrapped_partial(chain, chain_kwargs) + + docs = [] + scores = [] + use_docs_planned = False + num_docs_before_cut = 0 + use_llm_if_no_docs = True + return docs, target, scores, use_docs_planned, num_docs_before_cut, use_llm_if_no_docs, llm_mode, top_k_docs_max_show + + # determine whether use of context out of docs is planned + if not use_openai_model and prompt_type not in ['plain'] or langchain_only_model: + if llm_mode: + use_docs_planned = False + else: + use_docs_planned = True + else: + use_docs_planned = True + + # https://github.com/hwchase17/langchain/issues/1946 + # FIXME: Seems to way to get size of chroma db to limit top_k_docs to avoid + # Chroma collection MyData contains fewer than 4 elements. + # type logger error + if top_k_docs == -1: + k_db = 1000 if db_type in ['chroma', 'chroma_old'] else 100 + else: + # top_k_docs=100 works ok too + k_db = 1000 if db_type in ['chroma', 'chroma_old'] else top_k_docs + + # FIXME: For All just go over all dbs instead of a separate db for All + if not detect_user_path_changes_every_query and db is not None: + # avoid looking at user_path during similarity search db handling, + # if already have db and not updating from user_path every query + # but if db is None, no db yet loaded (e.g. from prep), so allow user_path to be whatever it was + if langchain_mode_paths is None: + langchain_mode_paths = {} + langchain_mode_paths = langchain_mode_paths.copy() + langchain_mode_paths[langchain_mode] = None + # once use_openai_embedding, hf_embedding_model passed in, possibly changed, + # but that's ok as not used below or in calling functions + db, num_new_sources, new_sources_metadata = make_db(use_openai_embedding=use_openai_embedding, + hf_embedding_model=hf_embedding_model, + migrate_embedding_model=migrate_embedding_model, + auto_migrate_db=auto_migrate_db, + first_para=first_para, text_limit=text_limit, + chunk=chunk, chunk_size=chunk_size, + + # urls + use_unstructured=use_unstructured, + use_playwright=use_playwright, + use_selenium=use_selenium, + + # pdfs + use_pymupdf=use_pymupdf, + use_unstructured_pdf=use_unstructured_pdf, + use_pypdf=use_pypdf, + enable_pdf_ocr=enable_pdf_ocr, + enable_pdf_doctr=enable_pdf_doctr, + try_pdf_as_html=try_pdf_as_html, + + # images + enable_ocr=enable_ocr, + enable_doctr=enable_doctr, + enable_pix2struct=enable_pix2struct, + enable_captions=enable_captions, + captions_model=captions_model, + caption_loader=caption_loader, + doctr_loader=doctr_loader, + pix2struct_loader=pix2struct_loader, + + # json + jq_schema=jq_schema, + + langchain_mode=langchain_mode, + langchain_mode_paths=langchain_mode_paths, + langchain_mode_types=langchain_mode_types, + db_type=db_type, + load_db_if_exists=load_db_if_exists, + db=db, + n_jobs=n_jobs, + verbose=verbose) + num_docs_before_cut = 0 + use_template = not use_openai_model and prompt_type not in ['plain'] or langchain_only_model + got_db_docs = False # not yet at least + template, template_if_no_docs, auto_reduce_chunks, query = \ + get_template(query, iinput, + pre_prompt_query, prompt_query, + pre_prompt_summary, prompt_summary, + langchain_action, + llm_mode, + use_docs_planned, + auto_reduce_chunks, + got_db_docs, + add_search_to_context) + + max_input_tokens = get_max_input_tokens(llm=llm, tokenizer=tokenizer, inference_server=inference_server, + model_name=model_name, max_new_tokens=max_new_tokens) + + if (db or text_context_list) and use_docs_planned: + if hasattr(db, '_persist_directory'): + lock_file = get_db_lock_file(db, lock_type='sim') + else: + base_path = 'locks' + base_path = makedirs(base_path, exist_ok=True, tmp_ok=True, use_base=True) + name_path = "sim.lock" + lock_file = os.path.join(base_path, name_path) + + if not (isinstance(db, Chroma) or isinstance(db, ChromaMig) or ChromaMig.__name__ in str(db)): + # only chroma supports filtering + filter_kwargs = {} + filter_kwargs_backup = {} + else: + import logging + logging.getLogger("chromadb").setLevel(logging.ERROR) + assert document_choice is not None, "Document choice was None" + if isinstance(db, Chroma): + filter_kwargs_backup = {} # shouldn't ever need backup + # chroma >= 0.4 + if len(document_choice) == 0 or len(document_choice) >= 1 and document_choice[ + 0] == DocumentChoice.ALL.value: + filter_kwargs = {"filter": {"chunk_id": {"$gte": 0}}} if query_action else \ + {"filter": {"chunk_id": {"$eq": -1}}} + else: + if document_choice[0] == DocumentChoice.ALL.value: + document_choice = document_choice[1:] + if len(document_choice) == 0: + filter_kwargs = {} + elif len(document_choice) > 1: + or_filter = [ + {"$and": [dict(source={"$eq": x}), dict(chunk_id={"$gte": 0})]} if query_action else { + "$and": [dict(source={"$eq": x}), dict(chunk_id={"$eq": -1})]} + for x in document_choice] + filter_kwargs = dict(filter={"$or": or_filter}) + else: + # still chromadb UX bug, have to do different thing for 1 vs. 2+ docs when doing filter + one_filter = \ + [{"source": {"$eq": x}, "chunk_id": {"$gte": 0}} if query_action else { + "source": {"$eq": x}, + "chunk_id": { + "$eq": -1}} + for x in document_choice][0] + + filter_kwargs = dict(filter={"$and": [dict(source=one_filter['source']), + dict(chunk_id=one_filter['chunk_id'])]}) + else: + # migration for chroma < 0.4 + if len(document_choice) == 0 or len(document_choice) >= 1 and document_choice[ + 0] == DocumentChoice.ALL.value: + filter_kwargs = {"filter": {"chunk_id": {"$gte": 0}}} if query_action else \ + {"filter": {"chunk_id": {"$eq": -1}}} + filter_kwargs_backup = {"filter": {"chunk_id": {"$gte": 0}}} + elif len(document_choice) >= 2: + if document_choice[0] == DocumentChoice.ALL.value: + document_choice = document_choice[1:] + or_filter = [ + {"source": {"$eq": x}, "chunk_id": {"$gte": 0}} if query_action else {"source": {"$eq": x}, + "chunk_id": { + "$eq": -1}} + for x in document_choice] + filter_kwargs = dict(filter={"$or": or_filter}) + or_filter_backup = [ + {"source": {"$eq": x}} if query_action else {"source": {"$eq": x}} + for x in document_choice] + filter_kwargs_backup = dict(filter={"$or": or_filter_backup}) + elif len(document_choice) == 1: + # degenerate UX bug in chroma + one_filter = \ + [{"source": {"$eq": x}, "chunk_id": {"$gte": 0}} if query_action else {"source": {"$eq": x}, + "chunk_id": { + "$eq": -1}} + for x in document_choice][0] + filter_kwargs = dict(filter=one_filter) + one_filter_backup = \ + [{"source": {"$eq": x}} if query_action else {"source": {"$eq": x}} + for x in document_choice][0] + filter_kwargs_backup = dict(filter=one_filter_backup) + else: + # shouldn't reach + filter_kwargs = {} + filter_kwargs_backup = {} + + if llm_mode: + docs = [] + scores = [] + elif document_subset == DocumentSubset.TopKSources.name or query in [None, '', '\n']: + db_documents, db_metadatas = get_docs_and_meta(db, top_k_docs, filter_kwargs=filter_kwargs, + text_context_list=text_context_list) + if len(db_documents) == 0 and filter_kwargs_backup: + db_documents, db_metadatas = get_docs_and_meta(db, top_k_docs, filter_kwargs=filter_kwargs_backup, + text_context_list=text_context_list) + + if top_k_docs == -1: + top_k_docs = len(db_documents) + # similar to langchain's chroma's _results_to_docs_and_scores + docs_with_score = [(Document(page_content=result[0], metadata=result[1] or {}), 0) + for result in zip(db_documents, db_metadatas)] + # set in metadata original order of docs + [x[0].metadata.update(orig_index=ii) for ii, x in enumerate(docs_with_score)] + + # order documents + doc_hashes = [x.get('doc_hash', 'None') for x in db_metadatas] + if query_action: + doc_chunk_ids = [x.get('chunk_id', 0) for x in db_metadatas] + docs_with_score2 = [x for hx, cx, x in + sorted(zip(doc_hashes, doc_chunk_ids, docs_with_score), key=lambda x: (x[0], x[1])) + if cx >= 0] + else: + assert summarize_action + doc_chunk_ids = [x.get('chunk_id', -1) for x in db_metadatas] + docs_with_score2 = [x for hx, cx, x in + sorted(zip(doc_hashes, doc_chunk_ids, docs_with_score), key=lambda x: (x[0], x[1])) + if cx == -1 + ] + if len(docs_with_score2) == 0 and len(docs_with_score) > 0: + # old database without chunk_id, migration added 0 but didn't make -1 as that would be expensive + # just do again and relax filter, let summarize operate on actual chunks if nothing else + docs_with_score2 = [x for hx, cx, x in + sorted(zip(doc_hashes, doc_chunk_ids, docs_with_score), + key=lambda x: (x[0], x[1])) + ] + docs_with_score = docs_with_score2 + + docs_with_score = docs_with_score[:top_k_docs] + docs = [x[0] for x in docs_with_score] + scores = [x[1] for x in docs_with_score] + num_docs_before_cut = len(docs) + else: + with filelock.FileLock(lock_file): + docs_with_score, got_db_docs = get_docs_with_score(query, k_db, filter_kwargs, db, db_type, + text_context_list=text_context_list, + verbose=verbose) + if len(docs_with_score) == 0 and filter_kwargs_backup: + docs_with_score, got_db_docs = get_docs_with_score(query, k_db, filter_kwargs_backup, db, + db_type, + text_context_list=text_context_list, + verbose=verbose) + + tokenizer = get_tokenizer(db=db, llm=llm, tokenizer=tokenizer, inference_server=inference_server, + use_openai_model=use_openai_model, + db_type=db_type) + # NOTE: if map_reduce, then no need to auto reduce chunks + if query_action and (top_k_docs == -1 or auto_reduce_chunks): + top_k_docs_tokenize = 100 + docs_with_score = docs_with_score[:top_k_docs_tokenize] + + prompt_no_docs = template.format(context='', question=query) + + model_max_length = tokenizer.model_max_length + chat = True # FIXME? + + # first docs_with_score are most important with highest score + full_prompt, \ + instruction, iinput, context, \ + num_prompt_tokens, max_new_tokens, \ + num_prompt_tokens0, num_prompt_tokens_actual, \ + chat_index, top_k_docs_trial, one_doc_size = \ + get_limited_prompt(prompt_no_docs, + iinput, + tokenizer, + prompter=prompter, + inference_server=inference_server, + prompt_type=prompt_type, + prompt_dict=prompt_dict, + chat=chat, + max_new_tokens=max_new_tokens, + system_prompt=system_prompt, + context=context, + chat_conversation=chat_conversation, + text_context_list=[x[0].page_content for x in docs_with_score], + keep_sources_in_context=keep_sources_in_context, + model_max_length=model_max_length, + memory_restriction_level=memory_restriction_level, + langchain_mode=langchain_mode, + add_chat_history_to_context=add_chat_history_to_context, + min_max_new_tokens=min_max_new_tokens, + ) + # avoid craziness + if 0 < top_k_docs_trial < max_chunks: + # avoid craziness + if top_k_docs == -1: + top_k_docs = top_k_docs_trial + else: + top_k_docs = min(top_k_docs, top_k_docs_trial) + elif top_k_docs_trial >= max_chunks: + top_k_docs = max_chunks + if top_k_docs > 0: + docs_with_score = docs_with_score[:top_k_docs] + elif one_doc_size is not None: + docs_with_score = [docs_with_score[0][:one_doc_size]] + else: + docs_with_score = [] + else: + if total_tokens_for_docs is not None: + # used to limit tokens for summarization, e.g. public instance + top_k_docs, one_doc_size, num_doc_tokens = \ + get_docs_tokens(tokenizer, + text_context_list=[x[0].page_content for x in docs_with_score], + max_input_tokens=total_tokens_for_docs) + + docs_with_score = docs_with_score[:top_k_docs] + + # put most relevant chunks closest to question, + # esp. if truncation occurs will be "oldest" or "farthest from response" text that is truncated + # BUT: for small models, e.g. 6_9 pythia, if sees some stuff related to h2oGPT first, it can connect that and not listen to rest + if docs_ordering_type in ['best_first']: + pass + elif docs_ordering_type in ['best_near_prompt', 'reverse_sort']: + docs_with_score.reverse() + elif docs_ordering_type in ['', None, 'reverse_ucurve_sort']: + docs_with_score = reverse_ucurve_list(docs_with_score) + else: + raise ValueError("No such docs_ordering_type=%s" % docs_ordering_type) + + # cut off so no high distance docs/sources considered + num_docs_before_cut = len(docs_with_score) + docs = [x[0] for x in docs_with_score if x[1] < cut_distance] + scores = [x[1] for x in docs_with_score if x[1] < cut_distance] + if len(scores) > 0 and verbose: + print("Distance: min: %s max: %s mean: %s median: %s" % + (scores[0], scores[-1], np.mean(scores), np.median(scores)), flush=True) + else: + docs = [] + scores = [] + + if not docs and use_docs_planned and not langchain_only_model: + # if HF type and have no docs, can bail out + return docs, None, [], False, num_docs_before_cut, use_llm_if_no_docs, llm_mode, top_k_docs_max_show + + if document_subset in non_query_commands: + # no LLM use + return docs, None, [], False, num_docs_before_cut, use_llm_if_no_docs, llm_mode, top_k_docs_max_show + + # FIXME: WIP + common_words_file = "data/NGSL_1.2_stats.csv.zip" + if False and os.path.isfile(common_words_file) and langchain_action == LangChainAction.QUERY.value: + df = pd.read_csv("data/NGSL_1.2_stats.csv.zip") + import string + reduced_query = query.translate(str.maketrans(string.punctuation, ' ' * len(string.punctuation))).strip() + reduced_query_words = reduced_query.split(' ') + set_common = set(df['Lemma'].values.tolist()) + num_common = len([x.lower() in set_common for x in reduced_query_words]) + frac_common = num_common / len(reduced_query) if reduced_query else 0 + # FIXME: report to user bad query that uses too many common words + if verbose: + print("frac_common: %s" % frac_common, flush=True) + + if len(docs) == 0: + # avoid context == in prompt then + use_docs_planned = False + template = template_if_no_docs + + got_db_docs = got_db_docs and len(text_context_list) < len(docs) + # update template in case situation changed or did get docs + # then no new documents from database or not used, redo template + # got template earlier as estimate of template token size, here is final used version + template, template_if_no_docs, auto_reduce_chunks, query = \ + get_template(query, iinput, + pre_prompt_query, prompt_query, + pre_prompt_summary, prompt_summary, + langchain_action, + llm_mode, + use_docs_planned, + auto_reduce_chunks, + got_db_docs, + add_search_to_context) + + if langchain_action == LangChainAction.QUERY.value: + if use_template: + # instruct-like, rather than few-shot prompt_type='plain' as default + # but then sources confuse the model with how inserted among rest of text, so avoid + prompt = PromptTemplate( + # input_variables=["summaries", "question"], + input_variables=["context", "question"], + template=template, + ) + chain = load_qa_chain(llm, prompt=prompt, verbose=verbose) + else: + # only if use_openai_model = True, unused normally except in testing + chain = load_qa_with_sources_chain(llm) + if not use_docs_planned: + chain_kwargs = dict(input_documents=[], question=query) + else: + chain_kwargs = dict(input_documents=docs, question=query) + target = wrapped_partial(chain, chain_kwargs) + elif langchain_action in [LangChainAction.SUMMARIZE_MAP.value, + LangChainAction.SUMMARIZE_REFINE, + LangChainAction.SUMMARIZE_ALL.value]: + if async_output: + return_intermediate_steps = False + else: + return_intermediate_steps = True + from langchain.chains.summarize import load_summarize_chain + if langchain_action == LangChainAction.SUMMARIZE_MAP.value: + prompt = PromptTemplate(input_variables=["text"], template=template) + chain = load_summarize_chain(llm, chain_type="map_reduce", + map_prompt=prompt, combine_prompt=prompt, + return_intermediate_steps=return_intermediate_steps, + token_max=max_input_tokens, verbose=verbose) + if async_output: + chain_func = chain.arun + else: + chain_func = chain + target = wrapped_partial(chain_func, {"input_documents": docs}) # , return_only_outputs=True) + elif langchain_action == LangChainAction.SUMMARIZE_ALL.value: + assert use_template + prompt = PromptTemplate(input_variables=["text"], template=template) + chain = load_summarize_chain(llm, chain_type="stuff", prompt=prompt, + return_intermediate_steps=return_intermediate_steps, verbose=verbose) + if async_output: + chain_func = chain.arun + else: + chain_func = chain + target = wrapped_partial(chain_func) + elif langchain_action == LangChainAction.SUMMARIZE_REFINE.value: + chain = load_summarize_chain(llm, chain_type="refine", + return_intermediate_steps=return_intermediate_steps, verbose=verbose) + if async_output: + chain_func = chain.arun + else: + chain_func = chain + target = wrapped_partial(chain_func) + else: + raise RuntimeError("No such langchain_action=%s" % langchain_action) + else: + raise RuntimeError("No such langchain_action=%s" % langchain_action) + + return docs, target, scores, use_docs_planned, num_docs_before_cut, use_llm_if_no_docs, llm_mode, top_k_docs_max_show + + +def get_max_model_length(llm=None, tokenizer=None, inference_server=None, model_name=None): + if hasattr(tokenizer, 'model_max_length'): + return tokenizer.model_max_length + elif inference_server in ['openai', 'openai_azure']: + return llm.modelname_to_contextsize(model_name) + elif inference_server in ['openai_chat', 'openai_azure_chat']: + return model_token_mapping[model_name] + elif isinstance(tokenizer, FakeTokenizer): + # GGML + return tokenizer.model_max_length + else: + return 2048 + + +def get_max_input_tokens(llm=None, tokenizer=None, inference_server=None, model_name=None, max_new_tokens=None): + model_max_length = get_max_model_length(llm=llm, tokenizer=tokenizer, inference_server=inference_server, + model_name=model_name) + + if any([inference_server.startswith(x) for x in + ['openai', 'openai_azure', 'openai_chat', 'openai_azure_chat', 'vllm']]): + # openai can't handle tokens + max_new_tokens > max_tokens even if never generate those tokens + # and vllm uses OpenAI API with same limits + max_input_tokens = model_max_length - max_new_tokens + elif isinstance(tokenizer, FakeTokenizer): + # don't trust that fake tokenizer (e.g. GGML) will make lots of tokens normally, allow more input + max_input_tokens = model_max_length - min(256, max_new_tokens) + else: + if 'falcon' in model_name or inference_server.startswith('http'): + # allow for more input for falcon, assume won't make as long outputs as default max_new_tokens + # Also allow if TGI or Gradio, because we tell it input may be same as output, even if model can't actually handle + max_input_tokens = model_max_length - min(256, max_new_tokens) + else: + # trust that maybe model will make so many tokens, so limit input + max_input_tokens = model_max_length - max_new_tokens + + return max_input_tokens + + +def get_tokenizer(db=None, llm=None, tokenizer=None, inference_server=None, use_openai_model=False, + db_type='chroma'): + if hasattr(llm, 'pipeline') and hasattr(llm.pipeline, 'tokenizer'): + # more accurate + return llm.pipeline.tokenizer + elif hasattr(llm, 'tokenizer'): + # e.g. TGI client mode etc. + return llm.tokenizer + elif inference_server in ['openai', 'openai_chat', 'openai_azure', + 'openai_azure_chat']: + return tokenizer + elif isinstance(tokenizer, FakeTokenizer): + return tokenizer + elif use_openai_model: + return FakeTokenizer() + elif (hasattr(db, '_embedding_function') and + hasattr(db._embedding_function, 'client') and + hasattr(db._embedding_function.client, 'tokenize')): + # in case model is not our pipeline with HF tokenizer + return db._embedding_function.client.tokenize + else: + # backup method + if os.getenv('HARD_ASSERTS'): + assert db_type in ['faiss', 'weaviate'] + # use tiktoken for faiss since embedding called differently + return FakeTokenizer() + + +def get_template(query, iinput, + pre_prompt_query, prompt_query, + pre_prompt_summary, prompt_summary, + langchain_action, + llm_mode, + use_docs_planned, + auto_reduce_chunks, + got_db_docs, + add_search_to_context): + if got_db_docs and add_search_to_context: + # modify prompts, assumes patterns like in predefined prompts. If user customizes, then they'd need to account for that. + prompt_query = prompt_query.replace('information in the document sources', + 'information in the document and web search sources (and their source dates and website source)') + prompt_summary = prompt_summary.replace('information in the document sources', + 'information in the document and web search sources (and their source dates and website source)') + elif got_db_docs and not add_search_to_context: + pass + elif not got_db_docs and add_search_to_context: + # modify prompts, assumes patterns like in predefined prompts. If user customizes, then they'd need to account for that. + prompt_query = prompt_query.replace('information in the document sources', + 'information in the web search sources (and their source dates and website source)') + prompt_summary = prompt_summary.replace('information in the document sources', + 'information in the web search sources (and their source dates and website source)') + + if langchain_action == LangChainAction.QUERY.value: + if iinput: + query = "%s\n%s" % (query, iinput) + if llm_mode or not use_docs_planned: + template_if_no_docs = template = """{context}{question}""" + else: + template = """%s +\"\"\" +{context} +\"\"\" +%s{question}""" % (pre_prompt_query, prompt_query) + template_if_no_docs = """{context}{question}""" + elif langchain_action in [LangChainAction.SUMMARIZE_ALL.value, LangChainAction.SUMMARIZE_MAP.value]: + none = ['', '\n', None] + + # modify prompt_summary if user passes query or iinput + if query not in none and iinput not in none: + prompt_summary = "Focusing on %s, %s, %s" % (query, iinput, prompt_summary) + elif query not in none: + prompt_summary = "Focusing on %s, %s" % (query, prompt_summary) + # don't auto reduce + auto_reduce_chunks = False + if langchain_action == LangChainAction.SUMMARIZE_MAP.value: + fstring = '{text}' + else: + fstring = '{input_documents}' + template = """%s: +\"\"\" +%s +\"\"\"\n%s""" % (pre_prompt_summary, fstring, prompt_summary) + template_if_no_docs = "Exactly only say: There are no documents to summarize." + elif langchain_action in [LangChainAction.SUMMARIZE_REFINE]: + template = '' # unused + template_if_no_docs = '' # unused + else: + raise RuntimeError("No such langchain_action=%s" % langchain_action) + + return template, template_if_no_docs, auto_reduce_chunks, query + + +def get_sources_answer(query, docs, answer, scores, show_rank, + answer_with_sources, append_sources_to_answer, + show_accordions=True, + show_link_in_sources=True, + top_k_docs_max_show=10, + docs_ordering_type='reverse_ucurve_sort', + num_docs_before_cut=0, + verbose=False, + t_run=None, + count_input_tokens=None, count_output_tokens=None): + if verbose: + print("query: %s" % query, flush=True) + print("answer: %s" % answer, flush=True) + + if len(docs) == 0: + extra = '' + ret = answer + extra + return ret, extra + + if answer_with_sources == -1: + extra = [dict(score=score, content=get_doc(x), source=get_source(x), orig_index=x.metadata.get('orig_index', 0)) + for score, x in zip(scores, docs)][ + :top_k_docs_max_show] + if append_sources_to_answer: + extra_str = [str(x) for x in extra] + ret = answer + '\n\n' + '\n'.join(extra_str) + else: + ret = answer + return ret, extra + + # link + answer_sources = [(max(0.0, 1.5 - score) / 1.5, + get_url(doc, font_size=font_size), + get_accordion(doc, font_size=font_size, head_acc=head_acc)) for score, doc in + zip(scores, docs)] + if not show_accordions: + answer_sources_dict = defaultdict(list) + [answer_sources_dict[url].append(score) for score, url in answer_sources] + answers_dict = {} + for url, scores_url in answer_sources_dict.items(): + answers_dict[url] = np.max(scores_url) + answer_sources = [(score, url) for url, score in answers_dict.items()] + answer_sources.sort(key=lambda x: x[0], reverse=True) + if show_rank: + # answer_sources = ['%d | %s' % (1 + rank, url) for rank, (score, url) in enumerate(answer_sources)] + # sorted_sources_urls = "Sources [Rank | Link]:
" + "
".join(answer_sources) + answer_sources = ['%s' % url for rank, (score, url) in enumerate(answer_sources)] + answer_sources = answer_sources[:top_k_docs_max_show] + sorted_sources_urls = "Ranked Sources:
" + "
".join(answer_sources) + else: + if show_accordions: + if show_link_in_sources: + answer_sources = ['

  • %.2g | %s
  • %s' % (font_size, score, url, accordion) + for score, url, accordion in answer_sources] + else: + answer_sources = ['
  • %.2g
  • %s
    ' % (font_size, score, accordion) + for score, url, accordion in answer_sources] + else: + if show_link_in_sources: + answer_sources = ['
  • %.2g | %s
  • ' % (font_size, score, url) + for score, url in answer_sources] + else: + answer_sources = ['
  • %.2g
  • ' % (font_size, score) + for score, url in answer_sources] + answer_sources = answer_sources[:top_k_docs_max_show] + if show_accordions: + sorted_sources_urls = f"{source_prefix}