id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
167,062
import ast import contextlib import functools import gc import getpass import hashlib import inspect import json import os import pathlib import pickle import platform import random import shutil import subprocess import sys import threading import time import traceback import zipfile import tarfile from concurrent.futures import ProcessPoolExecutor from datetime import datetime from typing import Tuple, Callable, Dict from queue import Queue, Empty from concurrent.futures import ThreadPoolExecutor import filelock import fire import numpy as np import pandas as pd import requests import uuid import tabulate from fire import inspectutils from joblib import Parallel from tqdm.auto import tqdm from src.utils_procs import reulimit from importlib.metadata import distribution, PackageNotFoundError import distutils.spawn import os def get_size(start_path='.'): total_size = 0 for dirpath, dirnames, filenames in os.walk(start_path): for f in filenames: fp = os.path.join(dirpath, f) # skip if it is symbolic link if not os.path.islink(fp): total_size += os.path.getsize(fp) return total_size
null
167,063
import ast import contextlib import functools import gc import getpass import hashlib import inspect import json import os import pathlib import pickle import platform import random import shutil import subprocess import sys import threading import time import traceback import zipfile import tarfile from concurrent.futures import ProcessPoolExecutor from datetime import datetime from typing import Tuple, Callable, Dict from queue import Queue, Empty from concurrent.futures import ThreadPoolExecutor import filelock import fire import numpy as np import pandas as pd import requests import uuid import tabulate from fire import inspectutils from joblib import Parallel from tqdm.auto import tqdm from src.utils_procs import reulimit def sanitize_filename(name, file_length_limit=250): from importlib.metadata import distribution, PackageNotFoundError import distutils.spawn import os def get_test_name_core(): tn = os.environ['PYTEST_CURRENT_TEST'].split(':')[-1] tn = "_".join(tn.split(' ')[:-1]) # skip (call) at end return sanitize_filename(tn)
null
167,064
import ast import contextlib import functools import gc import getpass import hashlib import inspect import json import os import pathlib import pickle import platform import random import shutil import subprocess import sys import threading import time import traceback import zipfile import tarfile from concurrent.futures import ProcessPoolExecutor from datetime import datetime from typing import Tuple, Callable, Dict from queue import Queue, Empty from concurrent.futures import ThreadPoolExecutor import filelock import fire import numpy as np import pandas as pd import requests import uuid import tabulate from fire import inspectutils from joblib import Parallel from tqdm.auto import tqdm from src.utils_procs import reulimit def remove(path: str): try: if path is not None and os.path.exists(path): if os.path.isdir(path): shutil_rmtree(path, ignore_errors=True) else: with contextlib.suppress(FileNotFoundError): os.remove(path) except: pass def makedirs(path, exist_ok=True, tmp_ok=False, use_base=False): """ Avoid some inefficiency in os.makedirs() :param path: :param exist_ok: :param tmp_ok: use /tmp if can't write locally :param use_base: :return: """ if path is None: return path # if base path set, make relative to that, unless user_path absolute path if use_base: if os.path.normpath(path) == os.path.normpath(os.path.abspath(path)): pass else: if os.getenv('H2OGPT_BASE_PATH') is not None: base_dir = os.path.normpath(os.getenv('H2OGPT_BASE_PATH')) path = os.path.normpath(path) if not path.startswith(base_dir): path = os.path.join(os.getenv('H2OGPT_BASE_PATH', ''), path) path = os.path.normpath(path) if os.path.isdir(path) and os.path.exists(path): assert exist_ok, "Path already exists" return path try: os.makedirs(path, exist_ok=exist_ok) return path except FileExistsError: # e.g. soft link return path except PermissionError: if tmp_ok: path0 = path path = os.path.join('/tmp/', path) print("Permission denied to %s, using %s instead" % (path0, path), flush=True) os.makedirs(path, exist_ok=exist_ok) return path else: raise from importlib.metadata import distribution, PackageNotFoundError import distutils.spawn import os The provided code snippet includes necessary dependencies for implementing the `create_relative_symlink` function. Write a Python function `def create_relative_symlink(target, link_name)` to solve the following problem: Creates a relative symlink to a target from a link location, ensuring parent directories exist. The target can be either a file or a directory. Parameters: - target: The path to the target file or directory. This can be an absolute or a relative path. - link_name: The path where the symlink will be created. This should include the name of the symlink itself. Raises: - ValueError: If the target does not exist. Here is the function: def create_relative_symlink(target, link_name): """ Creates a relative symlink to a target from a link location, ensuring parent directories exist. The target can be either a file or a directory. Parameters: - target: The path to the target file or directory. This can be an absolute or a relative path. - link_name: The path where the symlink will be created. This should include the name of the symlink itself. Raises: - ValueError: If the target does not exist. """ # Ensure the target exists if not os.path.exists(target): raise ValueError("Target does not exist: " + target) # Calculate the absolute paths target_abs = os.path.abspath(target) link_dir = os.path.dirname(os.path.abspath(link_name)) # Ensure the parent directory of the link exists os.makedirs(link_dir, exist_ok=True) # Calculate the relative path for the symlink relative_path = os.path.relpath(target_abs, link_dir) # Remove the link if it already exists if os.path.exists(link_name) or os.path.islink(link_name): os.remove(link_name) # Create the symlink os.symlink(relative_path, link_name) print(f"Symlink created: {link_name} -> {relative_path}")
Creates a relative symlink to a target from a link location, ensuring parent directories exist. The target can be either a file or a directory. Parameters: - target: The path to the target file or directory. This can be an absolute or a relative path. - link_name: The path where the symlink will be created. This should include the name of the symlink itself. Raises: - ValueError: If the target does not exist.
167,065
import ast import contextlib import functools import gc import getpass import hashlib import inspect import json import os import pathlib import pickle import platform import random import shutil import subprocess import sys import threading import time import traceback import zipfile import tarfile from concurrent.futures import ProcessPoolExecutor from datetime import datetime from typing import Tuple, Callable, Dict from queue import Queue, Empty from concurrent.futures import ThreadPoolExecutor import filelock import fire import numpy as np import pandas as pd import requests import uuid import tabulate from fire import inspectutils from joblib import Parallel from tqdm.auto import tqdm from src.utils_procs import reulimit from importlib.metadata import distribution, PackageNotFoundError import distutils.spawn import os def get_is_gradio_h2oai(): try: import gradio as gr return gr.__h2oai__ except: return False
null
167,066
import ast import contextlib import functools import gc import getpass import hashlib import inspect import json import os import pathlib import pickle import platform import random import shutil import subprocess import sys import threading import time import traceback import zipfile import tarfile from concurrent.futures import ProcessPoolExecutor from datetime import datetime from typing import Tuple, Callable, Dict from queue import Queue, Empty from concurrent.futures import ThreadPoolExecutor import filelock import fire import numpy as np import pandas as pd import requests import uuid import tabulate from fire import inspectutils from joblib import Parallel from tqdm.auto import tqdm from src.utils_procs import reulimit from importlib.metadata import distribution, PackageNotFoundError import distutils.spawn import os def split_list(input_list, split_size): for i in range(0, len(input_list), split_size): yield input_list[i:i + split_size]
null
167,067
import ast import contextlib import functools import gc import getpass import hashlib import inspect import json import os import pathlib import pickle import platform import random import shutil import subprocess import sys import threading import time import traceback import zipfile import tarfile from concurrent.futures import ProcessPoolExecutor from datetime import datetime from typing import Tuple, Callable, Dict from queue import Queue, Empty from concurrent.futures import ThreadPoolExecutor import filelock import fire import numpy as np import pandas as pd import requests import uuid import tabulate from fire import inspectutils from joblib import Parallel from tqdm.auto import tqdm from src.utils_procs import reulimit def makedirs(path, exist_ok=True, tmp_ok=False, use_base=False): from importlib.metadata import distribution, PackageNotFoundError import distutils.spawn import os def get_lock_file(name): lock_type = name base_path = os.path.join('locks', '%s_locks' % name) 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
null
167,068
import ast import contextlib import functools import gc import getpass import hashlib import inspect import json import os import pathlib import pickle import platform import random import shutil import subprocess import sys import threading import time import traceback import zipfile import tarfile from concurrent.futures import ProcessPoolExecutor from datetime import datetime from typing import Tuple, Callable, Dict from queue import Queue, Empty from concurrent.futures import ThreadPoolExecutor import filelock import fire import numpy as np import pandas as pd import requests import uuid import tabulate from fire import inspectutils from joblib import Parallel from tqdm.auto import tqdm from src.utils_procs import reulimit from importlib.metadata import distribution, PackageNotFoundError import distutils.spawn import os def merge_dict(dict1, dict2): ret = dict1.copy() ret.update(dict2) return ret
null
167,074
import os from functools import wraps import psutil def rlimitproc(pp, rlim): limit_nofile = 131071 def psfunc(func, *args, **kwargs): def get_file_limit(pid=None): if pid is None: pid = os.getpid() ps = psfunc(psutil.Process, pid) if ps is not None: nofile = rlimitproc(ps, psutil.RLIMIT_NOFILE) # (soft, hard) else: nofile = (-1, -1) nofile = list(nofile) if nofile[0] == -1: nofile[0] = limit_nofile if nofile[1] == -1: nofile[1] = limit_nofile return tuple(nofile)
null
167,076
import os import numpy as np from scipy.stats import mode from src.utils import have_cv2, have_pillow def align_image(img_file): import cv2 from imutils.perspective import four_point_transform try: # Load the image # img_file = '/home/jon/Downloads/fastfood.jpg' # img_file = "/home/jon/Documents/reciept.jpg" image = file_to_cv2(img_file) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (5, 5), 0) # Edge detection edges = cv2.Canny(blur, 50, 150, apertureSize=3) # Find contours contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # Find the largest contour largest = largest_contour(contours) if largest is not None and is_contour_acceptable(largest, image): # Approximate the contour to a polygon peri = cv2.arcLength(largest, True) approx = cv2.approxPolyDP(largest, 0.02 * peri, True) # If the approximated contour has four points, assume it is a quadrilateral if len(approx) == 4: warped = four_point_transform(image, approx.reshape(4, 2)) out_file = img_file + "_aligned.jpg" cv2.imwrite(out_file, warped) return out_file else: print("Contour is not a quadrilateral.") return img_file else: print("No acceptable contours found.") return img_file except Exception as e: print("Error in align_image:", e, flush=True) return img_file def correct_rotation(img_file, border_size=50): import cv2 # Function to rotate the image to the correct orientation # Load the image image = file_to_cv2(img_file) # Convert the image to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Detect edges in the image edges = cv2.Canny(gray, 50, 150, apertureSize=3) # Detect points that form a line using HoughLinesP lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold=80, minLineLength=100, maxLineGap=10) if lines is None or len(lines) == 0: return img_file # Initialize list of angles angles = [] # Loop over the lines and compute the angle of each line for line in lines: x1, y1, x2, y2 = line[0] angle = np.degrees(np.arctan2(y2 - y1, x2 - x1)) angles.append(angle) # Calculate the most frequent angle in the image most_frequent_angle = mode(np.round(angles)).mode # Assuming the receipt is horizontal, the text should be near 0 or -180/180 degrees # We need to bring the angle to the range (-45, 45) to minimize rotation and keep the text upright if most_frequent_angle < -45: most_frequent_angle += 90 elif most_frequent_angle > 45: most_frequent_angle -= 90 # Rotate the original image by the most frequent angle to correct its orientation (h, w) = image.shape[:2] center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, most_frequent_angle, 1.0) corrected_image = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE) # Crop the image (removing specified pixels from each border) after rotation remove_border_final = False if remove_border_final: cropped_rotated_image = corrected_image[border_size:-border_size, border_size:-border_size] else: cropped_rotated_image = corrected_image # Save the corrected image out_file = img_file + "_rotated.jpg" cv2.imwrite(out_file, cropped_rotated_image) return out_file def pad_resize_image_file(img_file): import cv2 image = file_to_cv2(img_file) image = pad_resize_image(image, return_none_if_no_change=True) if image is None: new_file = img_file else: new_file = img_file + "_pad_resized.png" cv2.imwrite(new_file, image) return new_file def fix_image_file(file, do_align=False, do_rotate=False, do_pad=False): # always try to fix rotation/alignment since OCR better etc. in that case if have_cv2: if do_align: aligned_image = align_image(file) if aligned_image is not None and os.path.isfile(aligned_image): file = aligned_image if do_rotate: derotated_image = correct_rotation(file) if derotated_image is not None and os.path.isfile(derotated_image): file = derotated_image if do_pad: file = pad_resize_image_file(file) return file
null
167,077
import os import numpy as np from scipy.stats import mode from src.utils import have_cv2, have_pillow def get_image_types(): 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} image_types0 = sorted(image_types0) image_types0 = [x[1:] if x.startswith('.') else x for x in image_types0] else: image_types0 = [] return image_types0 def get_image_file(image_file, image_control, document_choice): if image_control is not None: img_file = image_control elif image_file is not None: img_file = image_file else: image_types = get_image_types() img_file = [x for x in document_choice if any(x.endswith('.' + y) for y in image_types)] if document_choice else [] img_file = img_file[0] if img_file else None return img_file
null
167,079
import textwrap import re from src.utils import flatten_list, have_emoji, have_langid def init_sentence_state(): sentence_state = dict(sentence_list=[], index=0) return sentence_state
null
167,080
import textwrap import re from src.utils import flatten_list, have_emoji, have_langid def unpack_state(sentence_state): def pack_state(sentence_state, *args): def _get_sentences(response, verbose=False, min_start=15, max_length=250): def clean_sentence(sentence, verbose=False): def get_sentence(response, sentence_state, is_final=False, verbose=False): # get state items sentence_list, index = unpack_state(sentence_state) sentences = _get_sentences(response[index:], min_start=15 if index == 0 else 0, verbose=verbose) if len(sentences) >= 2: # detected new completed sentence # find new index index_delta = response[index:].index(sentences[0]) index += index_delta + len(sentences[0]) sentence_list.append(sentences[0]) # only clean for result, to avoid mis-handling of sentences index cleaned_sentence = clean_sentence(sentences[0], verbose=verbose) return cleaned_sentence, pack_state(sentence_state, sentence_list, index), False elif is_final: # then just return last sentence cleaned_sentence = clean_sentence(' '.join(sentences), verbose=verbose) sentence_list.append(' '.join(sentences)) return cleaned_sentence, pack_state(sentence_state, sentence_list, index), True else: return None, pack_state(sentence_state, sentence_list, index), True
null
167,081
import textwrap import re from src.utils import flatten_list, have_emoji, have_langid def detect_language(prompt, supported_languages, verbose=False): if not have_langid: # if no package, just return english return "en" import langid # Fast language autodetection if len(prompt) > 15: language_predicted = langid.classify(prompt)[0].strip() # strip need as there is space at end! if language_predicted == "zh": # we use zh-cn on xtts language_predicted = "zh-cn" if language_predicted not in supported_languages: print(f"Detected a language not supported by xtts :{language_predicted}, switching to english for now") language = "en" else: language = language_predicted if verbose: print(f"Language: Predicted sentence language:{language_predicted} , using language for xtts:{language}") else: # Hard to detect language fast in short sentence, use english default language = "en" if verbose: print(f"Language: Prompt is short or autodetect language disabled using english for xtts") return language
null
167,084
import copy import json import os import types import uuid from typing import Any, Dict, List, Union, Optional, Tuple, Mapping import time import queue import pathlib from datetime import datetime from langchain.schema import BasePromptTemplate from langchain.chains import LLMChain from langchain.chains import MapReduceDocumentsChain, StuffDocumentsChain, ReduceDocumentsChain from langchain.chains.combine_documents.base import BaseCombineDocumentsChain from langchain.chains.summarize import map_reduce_prompt, LoadingCallable, _load_stuff_chain, _load_map_reduce_chain, \ _load_refine_chain from langchain.schema.language_model import BaseLanguageModel from langchain_community.embeddings import HuggingFaceHubEmbeddings from src.utils import hash_file, get_sha, split_list from langchain.callbacks.base import BaseCallbackHandler, Callbacks from langchain.schema import LLMResult from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.docstore.document import Document import logging from typing import Any, Dict, Optional from langchain_core.pydantic_v1 import BaseModel, root_validator def _chunk_sources(sources, chunk=True, chunk_size=512, language=None, db_type=None): assert db_type is not None if not isinstance(sources, (list, tuple, types.GeneratorType)) and not callable(sources): # if just one document sources = [sources] if not chunk: [x.metadata.update(dict(chunk_id=0)) for chunk_id, x in enumerate(sources)] if db_type in ['chroma', 'chroma_old']: # make copy so can have separate summarize case source_chunks = [Document(page_content=x.page_content, metadata=copy.deepcopy(x.metadata) or {}) for x in sources] else: source_chunks = sources # just same thing else: if language and False: # Bug in langchain, keep separator=True not working # https://github.com/hwchase17/langchain/issues/2836 # so avoid this for now keep_separator = True separators = RecursiveCharacterTextSplitter.get_separators_for_language(language) else: separators = ["\n\n", "\n", " ", ""] keep_separator = False splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=0, keep_separator=keep_separator, separators=separators) source_chunks = splitter.split_documents(sources) # currently in order, but when pull from db won't be, so mark order and document by hash [x.metadata.update(dict(chunk_id=chunk_id)) for chunk_id, x in enumerate(source_chunks)] if db_type in ['chroma', 'chroma_old']: # also keep original source for summarization and other tasks # assign chunk_id=-1 for original content # this assumes, as is currently true, that splitter makes new documents and list and metadata is deepcopy [x.metadata.update(dict(chunk_id=-1)) for chunk_id, x in enumerate(sources)] # in some cases sources is generator, so convert to list return list(sources) + source_chunks else: return source_chunks
null
167,085
import copy import json import os import types import uuid from typing import Any, Dict, List, Union, Optional, Tuple, Mapping import time import queue import pathlib from datetime import datetime from langchain.schema import BasePromptTemplate from langchain.chains import LLMChain from langchain.chains import MapReduceDocumentsChain, StuffDocumentsChain, ReduceDocumentsChain from langchain.chains.combine_documents.base import BaseCombineDocumentsChain from langchain.chains.summarize import map_reduce_prompt, LoadingCallable, _load_stuff_chain, _load_map_reduce_chain, \ _load_refine_chain from langchain.schema.language_model import BaseLanguageModel from langchain_community.embeddings import HuggingFaceHubEmbeddings from src.utils import hash_file, get_sha, split_list from langchain.callbacks.base import BaseCallbackHandler, Callbacks from langchain.schema import LLMResult from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.docstore.document import Document import logging from typing import Any, Dict, Optional from langchain_core.pydantic_v1 import BaseModel, root_validator def add_parser(docs1, parser): [x.metadata.update(dict(parser=x.metadata.get('parser', parser))) for x in docs1]
null
167,086
import copy import json import os import types import uuid from typing import Any, Dict, List, Union, Optional, Tuple, Mapping import time import queue import pathlib from datetime import datetime from langchain.schema import BasePromptTemplate from langchain.chains import LLMChain from langchain.chains import MapReduceDocumentsChain, StuffDocumentsChain, ReduceDocumentsChain from langchain.chains.combine_documents.base import BaseCombineDocumentsChain from langchain.chains.summarize import map_reduce_prompt, LoadingCallable, _load_stuff_chain, _load_map_reduce_chain, \ _load_refine_chain from langchain.schema.language_model import BaseLanguageModel from langchain_community.embeddings import HuggingFaceHubEmbeddings from src.utils import hash_file, get_sha, split_list from langchain.callbacks.base import BaseCallbackHandler, Callbacks from langchain.schema import LLMResult from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.docstore.document import Document import logging from typing import Any, Dict, Optional from langchain_core.pydantic_v1 import BaseModel, root_validator def get_sha(value): return hashlib.md5(str(value).encode('utf-8')).hexdigest() def hash_file(file): try: import hashlib # BUF_SIZE is totally arbitrary, change for your app! BUF_SIZE = 65536 # lets read stuff in 64kb chunks! md5 = hashlib.md5() # sha1 = hashlib.sha1() if not os.path.isfile(file): md5.update(file.encode(encoding='UTF-8')) else: with open(file, 'rb') as f: while True: data = f.read(BUF_SIZE) if not data: break md5.update(data) # sha1.update(data) except BaseException as e: print("Cannot hash %s due to %s" % (file, str(e))) traceback.print_exc() return '' return md5.hexdigest() def _add_meta(docs1, file, headsize=50, filei=0, parser='NotSet', file_as_source=False): if os.path.isfile(file): file_extension = pathlib.Path(file).suffix hashid = hash_file(file) else: file_extension = str(file) # not file, just show full thing hashid = get_sha(file) doc_hash = str(uuid.uuid4())[:10] if not isinstance(docs1, (list, tuple, types.GeneratorType)): docs1 = [docs1] [x.metadata.update(dict(input_type=file_extension, parser=x.metadata.get('parser', parser), date=str(datetime.now()), time=time.time(), order_id=order_id, hashid=hashid, doc_hash=doc_hash, file_id=filei, head=x.page_content[:headsize].strip())) for order_id, x in enumerate(docs1)] if file_as_source: [x.metadata.update(dict(source=file)) for order_id, x in enumerate(docs1)]
null
167,087
import copy import json import os import types import uuid from typing import Any, Dict, List, Union, Optional, Tuple, Mapping import time import queue import pathlib from datetime import datetime from langchain.schema import BasePromptTemplate from langchain.chains import LLMChain from langchain.chains import MapReduceDocumentsChain, StuffDocumentsChain, ReduceDocumentsChain from langchain.chains.combine_documents.base import BaseCombineDocumentsChain from langchain.chains.summarize import map_reduce_prompt, LoadingCallable, _load_stuff_chain, _load_map_reduce_chain, \ _load_refine_chain from langchain.schema.language_model import BaseLanguageModel from langchain_community.embeddings import HuggingFaceHubEmbeddings from src.utils import hash_file, get_sha, split_list from langchain.callbacks.base import BaseCallbackHandler, Callbacks from langchain.schema import LLMResult from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.docstore.document import Document import logging from typing import Any, Dict, Optional from langchain_core.pydantic_v1 import BaseModel, root_validator def fix_json_meta(docs1): if not isinstance(docs1, (list, tuple, types.GeneratorType)): docs1 = [docs1] # fix meta, chroma doesn't like None, only str, int, float for values [x.metadata.update(dict(sender_name=x.metadata.get('sender_name') or '')) for x in docs1] [x.metadata.update(dict(timestamp_ms=x.metadata.get('timestamp_ms') or '')) for x in docs1]
null
167,088
import copy import json import os import types import uuid from typing import Any, Dict, List, Union, Optional, Tuple, Mapping import time import queue import pathlib from datetime import datetime from langchain.schema import BasePromptTemplate from langchain.chains import LLMChain from langchain.chains import MapReduceDocumentsChain, StuffDocumentsChain, ReduceDocumentsChain from langchain.chains.combine_documents.base import BaseCombineDocumentsChain from langchain.chains.summarize import map_reduce_prompt, LoadingCallable, _load_stuff_chain, _load_map_reduce_chain, \ _load_refine_chain from langchain.schema.language_model import BaseLanguageModel from langchain_community.embeddings import HuggingFaceHubEmbeddings from src.utils import hash_file, get_sha, split_list from langchain.callbacks.base import BaseCallbackHandler, Callbacks from langchain.schema import LLMResult from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.docstore.document import Document def _load_map_chain( llm: BaseLanguageModel, map_prompt: BasePromptTemplate = map_reduce_prompt.PROMPT, combine_prompt: BasePromptTemplate = map_reduce_prompt.PROMPT, combine_document_variable_name: str = "text", map_reduce_document_variable_name: str = "text", collapse_prompt: Optional[BasePromptTemplate] = None, reduce_llm: Optional[BaseLanguageModel] = None, collapse_llm: Optional[BaseLanguageModel] = None, verbose: Optional[bool] = None, token_max: int = 3000, callbacks: Callbacks = None, **kwargs: Any, ) -> H2OMapReduceDocumentsChain: map_chain = LLMChain( llm=llm, prompt=map_prompt, verbose=verbose, callbacks=callbacks ) _reduce_llm = reduce_llm or llm reduce_chain = LLMChain( llm=_reduce_llm, prompt=combine_prompt, verbose=verbose, callbacks=callbacks ) # TODO: document prompt combine_documents_chain = StuffDocumentsChain( llm_chain=reduce_chain, document_variable_name=combine_document_variable_name, verbose=verbose, callbacks=callbacks, ) if collapse_prompt is None: collapse_chain = None if collapse_llm is not None: raise ValueError( "collapse_llm provided, but collapse_prompt was not: please " "provide one or stop providing collapse_llm." ) else: _collapse_llm = collapse_llm or llm collapse_chain = StuffDocumentsChain( llm_chain=LLMChain( llm=_collapse_llm, prompt=collapse_prompt, verbose=verbose, callbacks=callbacks, ), document_variable_name=combine_document_variable_name, ) reduce_documents_chain = ReduceDocumentsChain( combine_documents_chain=combine_documents_chain, collapse_documents_chain=collapse_chain, token_max=token_max, verbose=verbose, callbacks=callbacks, ) return H2OMapReduceDocumentsChain( llm_chain=map_chain, reduce_documents_chain=reduce_documents_chain, document_variable_name=map_reduce_document_variable_name, verbose=verbose, callbacks=callbacks, **kwargs, ) import logging from typing import Any, Dict, Optional from langchain_core.pydantic_v1 import BaseModel, root_validator The provided code snippet includes necessary dependencies for implementing the `load_general_summarization_chain` function. Write a Python function `def load_general_summarization_chain( llm: BaseLanguageModel, chain_type: str = "stuff", verbose: Optional[bool] = None, **kwargs: Any, ) -> BaseCombineDocumentsChain` to solve the following problem: Load summarizing chain. Args: llm: Language Model to use in the chain. chain_type: Type of document combining chain to use. Should be one of "stuff", "map_reduce", and "refine". verbose: Whether chains should be run in verbose mode or not. Note that this applies to all chains that make up the final chain. Returns: A chain to use for summarizing. Here is the function: def load_general_summarization_chain( llm: BaseLanguageModel, chain_type: str = "stuff", verbose: Optional[bool] = None, **kwargs: Any, ) -> BaseCombineDocumentsChain: """Load summarizing chain. Args: llm: Language Model to use in the chain. chain_type: Type of document combining chain to use. Should be one of "stuff", "map_reduce", and "refine". verbose: Whether chains should be run in verbose mode or not. Note that this applies to all chains that make up the final chain. Returns: A chain to use for summarizing. """ loader_mapping: Mapping[str, LoadingCallable] = { "stuff": _load_stuff_chain, "map_reduce": _load_map_reduce_chain, "refine": _load_refine_chain, "map": _load_map_chain, } if chain_type not in loader_mapping: raise ValueError( f"Got unsupported chain type: {chain_type}. " f"Should be one of {loader_mapping.keys()}" ) return loader_mapping[chain_type](llm, verbose=verbose, **kwargs)
Load summarizing chain. Args: llm: Language Model to use in the chain. chain_type: Type of document combining chain to use. Should be one of "stuff", "map_reduce", and "refine". verbose: Whether chains should be run in verbose mode or not. Note that this applies to all chains that make up the final chain. Returns: A chain to use for summarizing.
167,089
from io import IOBase from typing import Any, Dict, List, Optional, Sequence, Tuple, Union from langchain._api import warn_deprecated from langchain.agents import AgentExecutor, BaseSingleActionAgent from langchain_experimental.agents.agent_toolkits.pandas.prompt import ( FUNCTIONS_WITH_DF, FUNCTIONS_WITH_MULTI_DF, MULTI_DF_PREFIX, MULTI_DF_PREFIX_FUNCTIONS, PREFIX, PREFIX_FUNCTIONS, SUFFIX_NO_DF, SUFFIX_WITH_DF, SUFFIX_WITH_MULTI_DF, ) from langchain.agents.mrkl.base import ZeroShotAgent from langchain.agents.mrkl.prompt import FORMAT_INSTRUCTIONS from langchain.agents.openai_functions_agent.base import OpenAIFunctionsAgent from langchain.agents.types import AgentType from langchain.callbacks.base import BaseCallbackManager from langchain.chains.llm import LLMChain from langchain.schema import BasePromptTemplate from langchain.schema.language_model import BaseLanguageModel from langchain.schema.messages import SystemMessage from langchain.tools import BaseTool from langchain_experimental.tools.python.tool import PythonAstREPLTool def create_pandas_dataframe_agent( llm: BaseLanguageModel, df: Any, agent_type: AgentType = AgentType.ZERO_SHOT_REACT_DESCRIPTION, callback_manager: Optional[BaseCallbackManager] = None, prefix: Optional[str] = None, suffix: Optional[str] = None, input_variables: Optional[List[str]] = None, verbose: bool = False, return_intermediate_steps: bool = False, max_iterations: Optional[int] = 15, max_execution_time: Optional[float] = None, early_stopping_method: str = "force", agent_executor_kwargs: Optional[Dict[str, Any]] = None, include_df_in_prompt: Optional[bool] = True, number_of_head_rows: int = 5, extra_tools: Sequence[BaseTool] = (), format_instructions="", **kwargs: Any, ) -> AgentExecutor: """Construct a pandas agent from an LLM and dataframe.""" warn_deprecated( since="0.0.314", message=( "On 2023-10-27 this module will be be deprecated from langchain, and " "will be available from the langchain-experimental package." "This code is already available in langchain-experimental." "See https://github.com/langchain-ai/langchain/discussions/11680." ), pending=True, ) agent: BaseSingleActionAgent if agent_type == AgentType.ZERO_SHOT_REACT_DESCRIPTION: prompt, base_tools = _get_prompt_and_tools( df, prefix=prefix, suffix=suffix, input_variables=input_variables, include_df_in_prompt=include_df_in_prompt, number_of_head_rows=number_of_head_rows, format_instructions=format_instructions, ) tools = base_tools + list(extra_tools) llm_chain = LLMChain( llm=llm, prompt=prompt, callback_manager=callback_manager, ) tool_names = [tool.name for tool in tools] agent = ZeroShotAgent( llm_chain=llm_chain, allowed_tools=tool_names, callback_manager=callback_manager, **kwargs, ) elif agent_type == AgentType.OPENAI_FUNCTIONS: _prompt, base_tools = _get_functions_prompt_and_tools( df, prefix=prefix, suffix=suffix, input_variables=input_variables, include_df_in_prompt=include_df_in_prompt, number_of_head_rows=number_of_head_rows, ) tools = base_tools + list(extra_tools) agent = OpenAIFunctionsAgent( llm=llm, prompt=_prompt, tools=tools, callback_manager=callback_manager, **kwargs, ) else: raise ValueError(f"Agent type {agent_type} not supported at the moment.") return AgentExecutor.from_agent_and_tools( agent=agent, tools=tools, callback_manager=callback_manager, verbose=verbose, return_intermediate_steps=return_intermediate_steps, max_iterations=max_iterations, max_execution_time=max_execution_time, early_stopping_method=early_stopping_method, **(agent_executor_kwargs or {}), ) The provided code snippet includes necessary dependencies for implementing the `create_csv_agent` function. Write a Python function `def create_csv_agent( llm: BaseLanguageModel, path: Union[str, IOBase, List[Union[str, IOBase]]], pandas_kwargs: Optional[dict] = None, **kwargs: Any, ) -> AgentExecutor` to solve the following problem: Create csv agent by loading to a dataframe and using pandas agent. Here is the function: def create_csv_agent( llm: BaseLanguageModel, path: Union[str, IOBase, List[Union[str, IOBase]]], pandas_kwargs: Optional[dict] = None, **kwargs: Any, ) -> AgentExecutor: """Create csv agent by loading to a dataframe and using pandas agent.""" try: import pandas as pd except ImportError: raise ImportError( "pandas package not found, please install with `pip install pandas`" ) _kwargs = pandas_kwargs or {} if isinstance(path, (str, IOBase)): df = pd.read_csv(path, **_kwargs) elif isinstance(path, list): df = [] for item in path: if not isinstance(item, (str, IOBase)): raise ValueError(f"Expected str or file-like object, got {type(path)}") df.append(pd.read_csv(item, **_kwargs)) else: raise ValueError(f"Expected str, list, or file-like object, got {type(path)}") return create_pandas_dataframe_agent(llm, df, **kwargs)
Create csv agent by loading to a dataframe and using pandas agent.
167,091
from enum import Enum openai_supports_functiontools = ["gpt-4-0613", "gpt-4-32k-0613", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-16k-0613", "gpt-4-1106-preview", "gpt-35-turbo-1106"] def does_support_functiontools(inference_server, model_name): if any([inference_server.startswith(x) for x in ['openai_azure', 'openai_azure_chat']]): return model_name.lower() in openai_supports_functiontools elif any([inference_server.startswith(x) for x in ['openai', 'openai_chat']]): # assume OpenAI serves updated models return True else: return False
null
167,092
from enum import Enum openai_supports_json_mode = ["gpt-4-1106-preview", "gpt-35-turbo-1106"] def does_support_json_mode(inference_server, model_name): if any([inference_server.startswith(x) for x in ['openai_azure', 'openai_azure_chat']]): return model_name.lower() in openai_supports_json_mode elif any([inference_server.startswith(x) for x in ['openai', 'openai_chat']]): # assume OpenAI serves updated models return True else: return False
null
167,093
from enum import Enum 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()
null
167,094
from enum import Enum def get_langchain_prompts(pre_prompt_query, prompt_query, pre_prompt_summary, prompt_summary, hyde_llm_prompt, model_name, inference_server, model_path_llama, doc_json_mode, prompt_query_type='simple'): if prompt_query_type == 'advanced': 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." prompt_query1 = "According to (primarily) the information in the document sources provided within context above, write an insightful and well-structured response to: " else: # older smaller models get confused by this prompt, should use "" instead, but not focusing on such old models anymore, complicates code too much pre_prompt_query1 = "Pay attention and remember the information below, which will help to answer the question or imperative after the context ends." prompt_query1 = "According to only the information in the document sources provided within the context above, write an insightful and well-structured response to: " pre_prompt_summary1 = """In order to write a concise single-paragraph or bulleted list summary, pay attention to the following text.""" prompt_summary1 = "Using only the information in the document sources above, write a condensed and concise summary of key results (preferably as bullet points)." hyde_llm_prompt1 = "Answer this question with vibrant details in order for some NLP embedding model to use that answer as better query than original question: " 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 if hyde_llm_prompt is None: hyde_llm_prompt = hyde_llm_prompt1 return pre_prompt_query, prompt_query, pre_prompt_summary, prompt_summary, hyde_llm_prompt
null
167,095
from enum import Enum def gr_to_lg(image_audio_loaders, pdf_loaders, url_loaders, use_pymupdf=None, use_unstructured_pdf=None, use_pypdf=None, enable_pdf_ocr=None, enable_pdf_doctr=None, try_pdf_as_html=None, **kwargs, ): assert use_pymupdf is not None assert use_unstructured_pdf is not None assert use_pypdf is not None assert enable_pdf_ocr is not None assert enable_pdf_doctr is not None assert try_pdf_as_html is not None if image_audio_loaders is None: image_audio_loaders = kwargs['image_audio_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, use_scrapeplaywright='ScrapeWithPlayWright' in url_loaders, use_scrapehttp='ScrapeWithHttp' in url_loaders, # pdfs # ... else condition uses default from command line, by default auto, so others can be used as backup # make sure pass 'off' for those if really want fully disabled. use_pymupdf='on' if 'PyMuPDF' in pdf_loaders else use_pymupdf, use_unstructured_pdf='on' if 'Unstructured' in pdf_loaders else use_unstructured_pdf, use_pypdf='on' if 'PyPDF' in pdf_loaders else use_pypdf, enable_pdf_ocr='on' if 'OCR' in pdf_loaders else enable_pdf_ocr, enable_pdf_doctr='on' if 'DocTR' in pdf_loaders else enable_pdf_doctr, try_pdf_as_html='on' if 'TryHTML' in pdf_loaders else try_pdf_as_html, # images and audio enable_ocr='OCR' in image_audio_loaders, enable_doctr='DocTR' in image_audio_loaders, enable_pix2struct='Pix2Struct' in image_audio_loaders, enable_captions='Caption' in image_audio_loaders or 'CaptionBlip2' in image_audio_loaders, enable_transcriptions="ASR" in image_audio_loaders or 'ASRLarge' in image_audio_loaders, enable_llava='LLaVa' in image_audio_loaders, ) if 'CaptionBlip2' in image_audio_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'] if 'ASRLarge' in image_audio_loaders: # just override, don't actually do both even if user chose both asr_model = "openai/whisper-large-v3" else: asr_model = kwargs['asr_model'] return ret, captions_model, asr_model
null
167,100
import uuid from enums import LangChainMode def length_db1(): # For MyData: # 0: db # 1: userid and dbid # 2: username # For others: # 0: db # 1: dbid # 2: None return 3 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" def set_userid(db1s, requests_state1, get_userid_auth, guest_name=''): force = requests_state1 and 'username' in requests_state1 db1 = db1s[LangChainMode.MY_DATA.value] assert db1 is not None and len(db1) == length_db1() if not db1[1] or force: db1[1] = get_userid_auth(requests_state1, id0=db1[1]) if not db1[2] or force: username1 = None if 'username' in requests_state1: username1 = requests_state1['username'] if username1 == guest_name: username1 += ':' + str(uuid.uuid4()) requests_state1['username'] = username1 db1[2] = username1
null
167,101
import uuid from enums import LangChainMode 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" def set_userid_direct(db1s, userid, username): db1 = db1s[LangChainMode.MY_DATA.value] db1[1] = userid db1[2] = username
null
167,102
import uuid from enums import LangChainMode 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" def get_userid_direct(db1s): return db1s[LangChainMode.MY_DATA.value][1] if db1s is not None else ''
null
167,103
import uuid from enums import LangChainMode 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" def get_username_direct(db1s): return db1s[LangChainMode.MY_DATA.value][2] if db1s is not None else ''
null
167,104
import uuid from enums import LangChainMode def get_dbid(db1): return db1[1]
null
167,105
import uuid from enums import LangChainMode def length_db1(): # For MyData: # 0: db # 1: userid and dbid # 2: username # For others: # 0: db # 1: dbid # 2: None return 3 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())
null
167,109
import ast import glob import pickle import uuid from typing import List, Optional import os import bz2 import csv import numpy as np import pandas as pd import pytest from matplotlib import pyplot as plt from langchain.docstore.document import Document from langchain.document_loaders import MWDumpLoader def unescape(x): from joblib import Parallel, delayed def get_views(): # views = pd.read_csv('wiki_page_views_more_1000month.csv') views = pd.read_csv('wiki_page_views_more_5000month.csv') views.index = views['title'] views = views['views'] views = views.to_dict() views = {str(unescape(str(k))): v for k, v in views.items()} views2 = {k.replace('_', ' '): v for k, v in views.items()} # views has _ but pages has " " views.update(views2) return views
null
167,111
import ast import copy import functools import inspect import queue import sys import os import time import traceback import typing import uuid import warnings from datetime import datetime import httpx 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 from src.image_utils import get_image_file 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' 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, docs_joiner_default, \ docs_ordering_types_default, docs_token_handling_default, max_input_tokens_public, max_total_input_tokens_public, \ max_top_k_docs_public, max_top_k_docs_default, max_total_input_tokens_public_api, max_top_k_docs_public_api, \ max_input_tokens_public_api, model_token_mapping_outputs, anthropic_mapping, anthropic_mapping_outputs, \ user_prompt_for_fake_system_prompt, base_langchain_actions, google_mapping, google_mapping_outputs, generic_prefix, \ generic_postfix, mistralai_mapping, mistralai_mapping_outputs, langchain_modes_intrinsic 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, \ url_alive, have_wavio, have_soundfile, have_deepspeed, have_doctr, have_librosa, have_TTS, have_flash_attention_2, \ have_diffusers, sanitize_filename, get_gradio_tmp, get_is_gradio_h2oai 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, \ openai_gpts, get_vllm_extra_dict, anthropic_gpts, google_gpts, mistralai_gpts, is_vision_model from stopping import get_stopping def url_alive(url): if not isinstance(url, str): return False try: response = requests.head(url) except Exception as e: return False else: if response.status_code in [200, 301, 302, 307]: return True else: return False def switch_a_roo_llama(base_model, model_path_llama, load_gptq, load_awq, n_gqa, llamacpp_path): # from TheBloke HF link is_gguf = 'GGUF'.lower() in base_model.lower() is_ggml = 'GGML'.lower() in base_model.lower() postfix = '-GGUF' if is_gguf else '-GGML' file_postfix = postfix.lower().replace('-', '.') model_split = base_model.split('TheBloke/') if base_model.lower().startswith('TheBloke'.lower()) and (is_gguf or is_ggml) and len(model_split) == 2: # auto-switch-a-roo to support GGUF/GGML put into base model in UI just_model_split = model_split[1].split(postfix) if postfix.lower() in base_model.lower() and \ file_postfix not in base_model and \ len(just_model_split) == 2: just_model = just_model_split[0] lower_model = just_model.lower() download_postfix = '?download=true' base_model0 = 'https://huggingface.co/%s/resolve/main/%s.Q5_K_M%s%s' % ( base_model, lower_model, file_postfix, download_postfix) if url_alive(base_model0): base_model = base_model0 model_path_llama = base_model base_model = 'llama' elif (base_model.lower().startswith('https://huggingface.co/TheBloke'.lower()) or base_model.lower().startswith('http://huggingface.co/TheBloke'.lower())) \ and (is_gguf or is_ggml) and len(model_split) == 2: # auto-switch-a-roo to support GGUF/GGML put into base model in UI just_model_split = model_split[1].split(postfix) if postfix.lower() in base_model.lower() and \ file_postfix not in base_model and \ len(just_model_split) == 2: just_model = just_model_split[0] lower_model = just_model.lower() download_postfix = '?download=true' base_model0 = '%s/resolve/main/%s.Q5_K_M%s%s' % ( base_model, lower_model, file_postfix, download_postfix) if url_alive(base_model0): base_model = base_model0 model_path_llama = base_model base_model = 'llama' elif base_model.endswith('.gguf') or base_model.endswith('.ggml') or base_model.endswith( '.gguf?download=true') or base_model.endswith('.ggml?download=true'): # from resolved url if base_model.lower().startswith( 'https://huggingface.co/') and 'resolve/main/' in base_model.lower() and url_alive(base_model): model_path_llama = base_model base_model = 'llama' # from file elif os.path.isfile(base_model): # then file but still either gguf or ggml model_path_llama = base_model base_model = 'llama' elif os.path.isfile(os.path.join(llamacpp_path, base_model)): # then file but still either gguf or ggml model_path_llama = os.path.join(llamacpp_path, base_model) base_model = 'llama' # some auto things for TheBloke models: if 'TheBloke' in base_model and '-GPTQ' in base_model: load_gptq = load_gptq or 'model' elif 'TheBloke' in base_model and '-AWQ' in base_model: load_awq = load_awq or 'model' elif '2-70B-GGUF' in model_path_llama: n_gqa = n_gqa or 8 return base_model, model_path_llama, load_gptq, load_awq, n_gqa
null
167,112
import ast import copy import functools import inspect import queue import sys import os import time import traceback import typing import uuid import warnings from datetime import datetime import httpx 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 from src.image_utils import get_image_file 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, docs_joiner_default, \ docs_ordering_types_default, docs_token_handling_default, max_input_tokens_public, max_total_input_tokens_public, \ max_top_k_docs_public, max_top_k_docs_default, max_total_input_tokens_public_api, max_top_k_docs_public_api, \ max_input_tokens_public_api, model_token_mapping_outputs, anthropic_mapping, anthropic_mapping_outputs, \ user_prompt_for_fake_system_prompt, base_langchain_actions, google_mapping, google_mapping_outputs, generic_prefix, \ generic_postfix, mistralai_mapping, mistralai_mapping_outputs, langchain_modes_intrinsic 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, \ url_alive, have_wavio, have_soundfile, have_deepspeed, have_doctr, have_librosa, have_TTS, have_flash_attention_2, \ have_diffusers, sanitize_filename, get_gradio_tmp, get_is_gradio_h2oai 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, \ openai_gpts, get_vllm_extra_dict, anthropic_gpts, google_gpts, mistralai_gpts, is_vision_model from stopping import get_stopping def get_model( load_8bit: bool = False, load_4bit: bool = False, low_bit_mode: int = 1, load_half: bool = True, use_flash_attention_2: bool = True, load_gptq: str = '', use_autogptq: bool = False, load_awq: str = '', load_exllama: bool = False, use_safetensors: bool = False, revision: str = None, use_gpu_id: bool = True, base_model: str = '', inference_server: str = "", regenerate_clients: bool = True, regenerate_gradio_clients: bool = False, tokenizer_base_model: str = '', lora_weights: str = "", gpu_id: int = 0, n_jobs=None, n_gpus=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, max_output_seq_len: int = None, compile_model: bool = False, llamacpp_path=None, llamacpp_dict=None, exllama_dict=None, gptq_dict=None, hf_model_dict={}, 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 use_autogptq: Use AutoGPTQ (True) or HF transformers (False) :param load_awq: AWQ 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 n_gpus: number of GPUs (-1 for all) :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_output_seq_len: :param compile_model: whether to compile torch model :param llamacpp_path: Path to download llama.cpp and GPT4All models to :param llamacpp_dict: dict of llama.cpp and GPT4All model options :param exllama_dict: dict of exllama options :param gptq_dict: dict of AutoGPTQ options :param attention_sinks: whether to use attention_sinks :param sink_dict: dict of attention sinks options :param truncation_generation: whether to truncate generation in torch case to max_seq_len :param hf_model_dict :param verbose: :return: """ print("Starting get_model: %s %s" % (base_model, inference_server), flush=True) model = None 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) if base_model == 'llama': # in case max_seq_len = None, try to auto-set config = None else: 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 os.getenv("listen_llama") is None: # only old models need this, avoid unless override with ENV 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', '') loader_kwargs = dict(model_name=base_model, reward_type=reward_type, llama_type=llama_type, load_gptq=load_gptq, use_autogptq=use_autogptq, load_awq=load_awq, 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, exllama_dict=exllama_dict, gptq_dict=gptq_dict, hf_model_dict=hf_model_dict) model_loader, tokenizer_loader, conditional_type = get_loaders(**loader_kwargs) if not tokenizer_base_model: tokenizer_base_model = base_model config_tokenizer = config # ignore sequence length of tokenizer elif tokenizer_base_model == 'tiktoken': tokenizer_base_model = 'tiktoken' config_tokenizer = None else: # get tokenizer specific objects config_tokenizer, _, max_seq_len_tokenizer = get_config(tokenizer_base_model, **config_kwargs, raise_exception=False) if config is None: assert max_seq_len, "Must set max_seq_len if passing different tokenizer than model that cannot be found (config is None) e.g. because a private model" loader_kwargs_tokenizer = loader_kwargs.copy() loader_kwargs_tokenizer['model_name'] = tokenizer_base_model _, tokenizer_loader, _ = get_loaders(**loader_kwargs_tokenizer) tokenizer_kwargs = dict(local_files_only=local_files_only, resume_download=resume_download, token=use_auth_token, trust_remote_code=trust_remote_code, offload_folder=offload_folder, revision=revision, padding_side='left', config=config_tokenizer, ) if load_exllama: tokenizer = tokenizer_loader elif tokenizer_base_model == 'tiktoken': assert max_seq_len is not None, "Please pass --max_seq_len=<max_seq_len> for unknown or tiktoken tokenizer for model %s" % base_model tokenizer = FakeTokenizer(model_max_length=max_seq_len - 50, is_openai=True) if max_output_seq_len is not None: tokenizer.max_output_len = max_output_seq_len elif config_tokenizer is not None and tokenizer_loader is not None and not isinstance(tokenizer_loader, str): if load_exllama: assert base_model == tokenizer_base_model 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 = int(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) model = gr_client or hf_client if tokenizer is not None: return model, tokenizer, inference_server # tokenizer may still be None if not HF model if base_model in openai_gpts and not inference_server: raise ValueError("Must select inference server when choosing OpenAI models") if base_model in anthropic_gpts and not inference_server: raise ValueError("Must select inference server when choosing Anthropic models") if base_model in google_gpts and not inference_server: raise ValueError("Must select inference server when choosing Google models") if base_model in mistralai_gpts and not inference_server: raise ValueError("Must select inference server when choosing MistralAI models") # see if we can set max_seq_len and tokenizer for non-HF models or check at least if set when required inf_server_for_max_seq_len_handling = isinstance(inference_server, str) and ( inference_server.startswith('openai') or inference_server.startswith('vllm') or inference_server.startswith('replicate') or inference_server.startswith('sagemaker') or inference_server.startswith('anthropic') ) if inference_server.startswith('vllm') or inference_server.startswith('openai'): t0 = time.time() client, async_client, inf_type, deployment_type, base_url, api_version, api_key = \ set_openai(inference_server, model_name=base_model) if not regenerate_clients: model = dict(client=client, async_client=async_client, inf_type=inf_type, deployment_type=deployment_type, base_url=base_url, api_version=api_version, api_key=api_key) if verbose: print("Duration client %s: %s" % (base_model, time.time() - t0), flush=True) if inference_server.startswith('anthropic'): t0 = time.time() import anthropic base_url = os.getenv("ANTHROPIC_API_URL", "https://api.anthropic.com") api_key = os.getenv('ANTHROPIC_API_KEY') timeout = 600 anthropic_kwargs = dict(base_url=base_url, api_key=api_key, timeout=timeout) client = anthropic.Anthropic(**anthropic_kwargs) async_client = anthropic.AsyncAnthropic(**anthropic_kwargs) if not regenerate_clients: model = dict(client=client, async_client=async_client, inf_type='anthropic', base_url=base_url, api_key=api_key, timeout=timeout) if verbose: print("Duration client %s: %s" % (base_model, time.time() - t0), flush=True) if inference_server.startswith('google'): t0 = time.time() import google.generativeai as genai see_model = False models = [] for m in genai.list_models(): if 'generateContent' in m.supported_generation_methods: name_split = m.name.split('models/') if len(name_split) >= 2: name = name_split[1] models.append(name) if name not in google_mapping: if os.getenv('HARD_ASSERTS'): raise ValueError("%s not in google_mapping" % name) google_mapping[name] = 8192 # estimate see_model |= base_model == name assert see_model, "Did not find model=%s in API access: %s" % (base_model, models) api_key = os.getenv('GOOGLE_API_KEY') assert api_key, "Missing Google Gemini API key" genai.configure(api_key=api_key) client = genai.GenerativeModel(base_model) async_client = genai.GenerativeModel(base_model) timeout = 600 if not regenerate_clients: model = dict(client=client, async_client=async_client, inf_type='google', base_url=None, api_key=api_key, timeout=timeout) if verbose: print("Duration client %s: %s" % (base_model, time.time() - t0), flush=True) if inference_server.startswith('mistralai'): t0 = time.time() from mistralai.client import MistralClient from mistralai.async_client import MistralAsyncClient api_key = os.environ["MISTRAL_API_KEY"] assert api_key, "Missing MistralAI API key" client = MistralClient(api_key=api_key) list_models_response = client.list_models() see_model = False models = [x.id for x in dict(list_models_response)['data']] for name in models: see_model |= base_model == name if name not in mistralai_mapping: if os.getenv('HARD_ASSERTS'): raise ValueError("%s not in mistralai_mapping" % name) mistralai_mapping[name] = 31768 # estimate assert see_model, "Did not find model=%s in API access: %s" % (base_model, models) async_client = MistralAsyncClient(api_key=api_key) timeout = 600 if not regenerate_clients: model = dict(client=client, async_client=async_client, inf_type='mistralai', base_url=None, api_key=api_key, timeout=timeout) if verbose: print("Duration client %s: %s" % (base_model, time.time() - t0), flush=True) if inf_server_for_max_seq_len_handling or \ inference_server.startswith('openai') or \ base_model in openai_gpts or \ inference_server.startswith('anthropic') or \ base_model in anthropic_gpts or \ inference_server.startswith('google') or \ base_model in google_gpts or \ inference_server.startswith('mistralai') or \ base_model in mistralai_gpts: max_output_len = None if inference_server.startswith('openai') or base_model in openai_gpts: if inference_server.startswith('openai') and base_model in openai_gpts: client, async_client, inf_type, deployment_type, base_url, api_version, api_key = \ set_openai(inference_server, model_name=base_model) assert api_key, "No OpenAI key detected. Set environment for OPENAI_API_KEY or add to inference server line: %s" % inference_server # Don't return None, None for model, tokenizer so triggers if base_model in model_token_mapping: max_seq_len = model_token_mapping[base_model] else: print("Using unknown (or proxy) OpenAI model: %s for inference_server=%s" % ( base_model, inference_server)) if base_model in model_token_mapping_outputs: max_output_len = model_token_mapping_outputs[base_model] else: if os.getenv('HARD_ASSERTS'): assert max_output_seq_len is not None, "Must set max_output_seq_len" else: max_output_seq_len = 8192 # estimate max_output_len = max_output_seq_len if inference_server.startswith('anthropic') or base_model in anthropic_gpts: if inference_server.startswith('anthropic'): assert os.getenv('ANTHROPIC_API_KEY'), "Set environment for ANTHROPIC_API_KEY" # Don't return None, None for model, tokenizer so triggers # include small token cushion if base_model in anthropic_mapping: max_seq_len = anthropic_mapping[base_model] else: raise ValueError("Invalid base_model=%s for inference_server=%s" % (base_model, inference_server)) if base_model in anthropic_mapping_outputs: max_output_len = anthropic_mapping_outputs[base_model] else: if os.getenv('HARD_ASSERTS'): assert max_output_seq_len is not None, "Must set max_output_seq_len" else: max_output_seq_len = 4096 # estimate max_output_len = max_output_seq_len if inference_server.startswith('google') or base_model in google_gpts: if inference_server.startswith('google'): assert os.getenv('GOOGLE_API_KEY'), "Set environment for GOOGLE_API_KEY" # Don't return None, None for model, tokenizer so triggers # include small token cushion if base_model in google_mapping: max_seq_len = google_mapping[base_model] else: raise ValueError("Invalid base_model=%s for inference_server=%s" % (base_model, inference_server)) if base_model in google_mapping_outputs: max_output_len = google_mapping_outputs[base_model] else: if os.getenv('HARD_ASSERTS'): assert max_output_seq_len is not None, "Must set max_output_seq_len" else: max_output_seq_len = 8192 # estimate max_output_len = max_output_seq_len if inference_server.startswith('mistralai') or base_model in mistralai_gpts: if inference_server.startswith('mistralai'): assert os.getenv('MISTRAL_API_KEY'), "Set environment for MISTRAL_API_KEY" # Don't return None, None for model, tokenizer so triggers # include small token cushion if base_model in mistralai_mapping: max_seq_len = mistralai_mapping[base_model] else: raise ValueError("Invalid base_model=%s for inference_server=%s" % (base_model, inference_server)) if base_model in mistralai_mapping_outputs: max_output_len = mistralai_mapping_outputs[base_model] else: if os.getenv('HARD_ASSERTS'): assert max_output_seq_len is not None, "Must set max_output_seq_len" else: max_output_seq_len = 31768 # estimate max_output_len = max_output_seq_len 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=<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:<endpoint name>:<region>, 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 \ base_model in openai_gpts or \ inference_server.startswith('anthropic') or \ base_model in anthropic_gpts or \ inference_server.startswith('google') or \ base_model in google_gpts or \ inference_server.startswith('mistralai') or \ base_model in mistralai_gpts: # must be set by now assert max_seq_len is not None, "max_seq_len should have been set for OpenAI or Anthropic or Google or MistralAI models by now." if tokenizer is None: # don't use fake (tiktoken) tokenizer for vLLM//replicate if know actual model with actual tokenizer # NOTE: Google reaches here because they only provide API to count tokens, no local code. assert max_seq_len is not None, "Please set max_seq_len in UI for context length, or pass to CLI --max_seq_len=<max_seq_len>" tokenizer = FakeTokenizer(model_max_length=max_seq_len - 50, is_openai=True) if max_output_len is not None: tokenizer.max_output_len = max_output_len if model is None: # if model None, means native inference server (and no concern about slowness of regenerating client) model = inference_server return model, tokenizer, inference_server if max_output_seq_len is not None: tokenizer.max_output_len = max_output_seq_len if inference_server and base_model in non_hf_types and tokenizer is None: assert max_seq_len is not None, "Please pass --max_seq_len=<max_seq_len> for non-HF model %s" % base_model tokenizer = FakeTokenizer(model_max_length=max_seq_len - 50, is_openai=True) return model, tokenizer, inference_server if inference_server and tokenizer is None: # for new openai, claude, etc. models assert max_seq_len is not None, "Please pass --max_seq_len=<max_seq_len> for non-HF model %s" % base_model tokenizer = FakeTokenizer(model_max_length=max_seq_len - 50, is_openai=True) return model, tokenizer, inference_server # shouldn't reach here if had 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, gpu_id=gpu_id, n_gpus=n_gpus, max_seq_len=max_seq_len, llamacpp_dict=llamacpp_dict, llamacpp_path=llamacpp_path) return model, tokenizer, device if load_exllama: return model_loader, tokenizer, 'cuda' if n_gpus != 0 else 'cpu' # 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, use_flash_attention_2=use_flash_attention_2, load_gptq=load_gptq, use_autogptq=use_autogptq, load_awq=load_awq, 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, n_gpus=n_gpus, 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, loader_kwargs=loader_kwargs, gptq_dict=gptq_dict, hf_model_dict=hf_model_dict, verbose=verbose) def clear_torch_cache(allow_skip=False): if allow_skip and os.getenv('CLEAR_CLEAR_TORCH', '2') == '1' or os.getenv('CLEAR_CLEAR_TORCH', '2') == '0': return try: import torch if torch.cuda.is_available(): torch.cuda.empty_cache() torch.cuda.ipc_collect() gc.collect() except RuntimeError as e: print("clear_torch_cache error: %s" % ''.join(traceback.format_tb(e.__traceback__)), flush=True) def get_model_retry(**kwargs): model1, tokenizer1, device1 = None, None, None trials = 4 for trial in range(trials): try: model1, tokenizer1, device1 = get_model(**kwargs) break except Exception as e: stre = str(e) if 'Exllama kernel does not support' in stre: # help user a bit kwargs['gptq_dict'].update( {'inject_fused_attention': False, 'disable_exllama': True}) if 'Could not find model' in stre or \ 'Could not a find model' in stre or \ 'safetensors' in stre or \ 'not appear to have a file named pytorch_model.bin' in stre: kwargs['use_safetensors'] = True if 'current architecture does not support Flash Attention 2' in stre: kwargs['use_flash_attention_2'] = False clear_torch_cache() if trial >= trials - 1: raise return model1, tokenizer1, device1
null
167,113
import ast import copy import functools import inspect import queue import sys import os import time import traceback import typing import uuid import warnings from datetime import datetime import httpx 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 from src.image_utils import get_image_file 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' 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, docs_joiner_default, \ docs_ordering_types_default, docs_token_handling_default, max_input_tokens_public, max_total_input_tokens_public, \ max_top_k_docs_public, max_top_k_docs_default, max_total_input_tokens_public_api, max_top_k_docs_public_api, \ max_input_tokens_public_api, model_token_mapping_outputs, anthropic_mapping, anthropic_mapping_outputs, \ user_prompt_for_fake_system_prompt, base_langchain_actions, google_mapping, google_mapping_outputs, generic_prefix, \ generic_postfix, mistralai_mapping, mistralai_mapping_outputs, langchain_modes_intrinsic 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, \ url_alive, have_wavio, have_soundfile, have_deepspeed, have_doctr, have_librosa, have_TTS, have_flash_attention_2, \ have_diffusers, sanitize_filename, get_gradio_tmp, get_is_gradio_h2oai 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, \ openai_gpts, get_vllm_extra_dict, anthropic_gpts, google_gpts, mistralai_gpts, is_vision_model from stopping import get_stopping def get_client_from_inference_server(inference_server, base_model=None, raise_connection_exception=False): inference_server, headers = get_hf_server(inference_server) gr_client = None hf_client = None if base_model and is_vision_model(base_model): from gradio_utils.grclient import GradioClient gr_client = GradioClient(inference_server, check_hash=False, serialize=True) gr_client.setup() elif headers is None: try: # preload client since slow for gradio case especially from gradio_utils.grclient import GradioClient 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).setup() 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, httpx.LocalProtocolError) 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_root_url(url): from urllib.parse import urlparse # Parse the URL to extract its components parsed_url = urlparse(url) # Extracted parts: scheme, hostname, and port scheme = parsed_url.scheme hostname = parsed_url.hostname port = parsed_url.port # Will be None if the port is not explicitly specified in the URL # Conditionally add the port to the reassembled URL only if it was explicitly specified if port: reassembled_url = f"{scheme}://{hostname}:{port}/" else: reassembled_url = f"{scheme}://{hostname}/" # For displaying as separate parts http_part = scheme ip_part = hostname port_part = port if port else "Not specified" # Display 'Not specified' or similar if there's no port # Output the reassembled URL return reassembled_url anthropic_mapping = { "claude-2.1": 200000, "claude-2": 100000, "claude-2.0": 100000, "claude-instant-1.2": 100000, "claude-3-opus-20240229": 200000, "claude-3-sonnet-20240229": 200000, } def set_openai(inference_server, model_name=None): if inference_server.startswith('vllm'): api_key = "EMPTY" inf_type = inference_server.split(':')[0].strip() ip_port_vllm = ':'.join(inference_server.split(':')[1:]) if ip_port_vllm.startswith('https://'): http_prefix = 'https://' ip_port_vllm = ip_port_vllm[len(http_prefix):] auto_v1 = False elif ip_port_vllm.startswith('http://'): http_prefix = 'http://' ip_port_vllm = ip_port_vllm[len(http_prefix):] auto_v1 = False else: http_prefix = 'http://' auto_v1 = True address = ':'.join(ip_port_vllm.split(':')[0:1]).strip() api_base = http_prefix + address if len(ip_port_vllm.split(':')) >= 2: port_vllm = ip_port_vllm.split(':')[1].strip() if port_vllm not in [None, 'None']: api_base += ':' + port_vllm if len(ip_port_vllm.split(':')) >= 3: # if not there, use EMPTY as default url_path = ip_port_vllm.split(':')[2].strip() if url_path not in [None, 'None']: api_base += url_path # assume includes prefix of / and /v1 if auto_v1 and not api_base.endswith('/v1'): api_base += '/v1' if len(ip_port_vllm.split(':')) >= 4: # if not there, use EMPTY as default api_key = ip_port_vllm.split(':')[3].strip() from openai import OpenAI, AsyncOpenAI client_args = dict(base_url=api_base, api_key=api_key) client = OpenAI(**client_args) async_client = AsyncOpenAI(**client_args) return client, async_client, inf_type, None, api_base, None, api_key else: api_key = os.getenv("OPENAI_API_KEY") base_url = None deployment_type = None api_version = None inf_type = inference_server.split(':')[0].strip() if len(inference_server.split(':')) >= 2: deployment_type = inference_server.split(':')[1].strip() if len(inference_server.split(':')) >= 3: base_url = inference_server.split(':')[2].strip() base_url = 'https://' + base_url if len(inference_server.split(':')) >= 4: api_version = inference_server.split(':')[3].strip() if inference_server.startswith('openai_azure'): if api_version in ['None', None]: # for function tools support # https://github.com/Azure/azure-rest-api-specs/tree/main/specification/cognitiveservices/data-plane/AzureOpenAI/inference/preview/2023-12-01-preview api_version = "2023-12-01-preview" if os.getenv('OPENAI_AZURE_KEY') is not None: # use this instead if exists api_key = os.getenv("OPENAI_AZURE_KEY") elif api_version in ['None', None]: api_version = None if len(inference_server.split(':')) >= 5: api_key0 = inference_server.split(':')[4].strip() if api_key0 not in ['None', None]: api_key = api_key0 if deployment_type == 'None': deployment_type = None if base_url == 'None': base_url = None if base_url == 'None': base_url = None # cannot use non-chat model, uses old openai. stuff if go through to H2OOpenAI with chat model if model_name: chat_model = (model_name.startswith("gpt-3.5-turbo") or model_name.startswith( "gpt-4")) and "-instruct" not in model_name if chat_model and inf_type == 'openai_azure': inf_type = 'openai_azure_chat' if chat_model and inf_type == 'openai': inf_type = 'openai_chat' from openai import OpenAI, AzureOpenAI, AsyncOpenAI, AsyncAzureOpenAI if inf_type in ['openai_azure', 'openai_azure_chat']: client_args = dict(azure_deployment=deployment_type, azure_endpoint=base_url, api_version=api_version, api_key=api_key) client = AzureOpenAI(**client_args) async_client = AsyncAzureOpenAI(**client_args) else: client_args = dict(base_url=base_url, api_key=api_key) client = OpenAI(**client_args) async_client = AsyncOpenAI(**client_args) return client, async_client, inf_type, deployment_type, base_url, api_version, api_key def get_inf_models(inference_server): models = [] if inference_server.startswith('google'): import google.generativeai as genai for m in genai.list_models(): if 'generateContent' in m.supported_generation_methods: name_split = m.name.split('models/') if len(name_split) >= 2: name = name_split[1] models.append(name) elif inference_server.startswith('mistralai'): from mistralai.client import MistralClient from mistralai.async_client import MistralAsyncClient api_key = os.environ["MISTRAL_API_KEY"] assert api_key, "Missing MistralAI API key" client = MistralClient(api_key=api_key) list_models_response = client.list_models() models.extend([x.id for x in dict(list_models_response)['data']]) elif inference_server.startswith('openai') or inference_server.startswith('vllm'): openai_client, openai_async_client, \ inf_type, deployment_type, base_url, api_version, api_key = \ set_openai(inference_server) # List models try: models.extend([x.id for x in openai_client.models.list()]) except Exception as e: print("Can't get OpenAI/vLLM model list, trying ollama: %s" % str(e)) # in case ollama import requests root_url = get_root_url(base_url) if not root_url.endswith('/'): root_url += '/' import json response = json.loads(requests.get("%sapi/tags" % root_url).text) # Print the response content if 'models' in response: models.extend([x['name'] for x in response['models']]) elif inference_server.startswith('replicate'): pass elif inference_server.startswith('sagemaker'): pass elif inference_server.startswith('anthropic'): models.extend(list(anthropic_mapping.keys())) elif inference_server.startswith('http'): inference_server, gr_client, hf_client = get_client_from_inference_server(inference_server) if gr_client is not None: res = gr_client.predict(api_name='/model_names') models.extend({x['base_model']: x['max_seq_len'] for x in ast.literal_eval(res)}) return models
null
167,114
import ast import copy import functools import inspect import queue import sys import os import time import traceback import typing import uuid import warnings from datetime import datetime import httpx 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 from src.image_utils import get_image_file 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, docs_joiner_default, \ docs_ordering_types_default, docs_token_handling_default, max_input_tokens_public, max_total_input_tokens_public, \ max_top_k_docs_public, max_top_k_docs_default, max_total_input_tokens_public_api, max_top_k_docs_public_api, \ max_input_tokens_public_api, model_token_mapping_outputs, anthropic_mapping, anthropic_mapping_outputs, \ user_prompt_for_fake_system_prompt, base_langchain_actions, google_mapping, google_mapping_outputs, generic_prefix, \ generic_postfix, mistralai_mapping, mistralai_mapping_outputs, langchain_modes_intrinsic 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, \ url_alive, have_wavio, have_soundfile, have_deepspeed, have_doctr, have_librosa, have_TTS, have_flash_attention_2, \ have_diffusers, sanitize_filename, get_gradio_tmp, get_is_gradio_h2oai 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, \ openai_gpts, get_vllm_extra_dict, anthropic_gpts, google_gpts, mistralai_gpts, is_vision_model from stopping import get_stopping def get_model( load_8bit: bool = False, load_4bit: bool = False, low_bit_mode: int = 1, load_half: bool = True, use_flash_attention_2: bool = True, load_gptq: str = '', use_autogptq: bool = False, load_awq: str = '', load_exllama: bool = False, use_safetensors: bool = False, revision: str = None, use_gpu_id: bool = True, base_model: str = '', inference_server: str = "", regenerate_clients: bool = True, regenerate_gradio_clients: bool = False, tokenizer_base_model: str = '', lora_weights: str = "", gpu_id: int = 0, n_jobs=None, n_gpus=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, max_output_seq_len: int = None, compile_model: bool = False, llamacpp_path=None, llamacpp_dict=None, exllama_dict=None, gptq_dict=None, hf_model_dict={}, verbose: bool = False, ): def get_kwargs(func, exclude_names=None, **kwargs): def get_score_model(score_model: str = None, load_8bit: bool = False, load_4bit: bool = False, low_bit_mode=1, load_half: bool = True, use_flash_attention_2: bool = True, load_gptq: str = '', use_autogptq: bool = False, load_awq: 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, n_gpus=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_path: str = None, llamacpp_dict: typing.Dict = None, exllama_dict: typing.Dict = None, gptq_dict: typing.Dict = None, attention_sinks: bool = False, sink_dict: typing.Dict = None, truncation_generation: bool = False, hf_model_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 use_flash_attention_2 = False load_gptq = '' use_autogptq = False load_awq = '' load_exllama = False use_safetensors = False revision = None base_model = score_model.strip() tokenizer_base_model = '' lora_weights = '' inference_server = '' regenerate_clients = True regenerate_gradio_clients = False llama_type = False max_seq_len = None max_output_seq_len = None rope_scaling = {} compile_model = False llamacpp_path = None llamacpp_dict = {} exllama_dict = {} gptq_dict = {} attention_sinks = False sink_dict = {} truncation_generation = False hf_model_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
null
167,115
import ast import copy import functools import inspect import queue import sys import os import time import traceback import typing import uuid import warnings from datetime import datetime import httpx 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 from src.image_utils import get_image_file 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, docs_joiner_default, \ docs_ordering_types_default, docs_token_handling_default, max_input_tokens_public, max_total_input_tokens_public, \ max_top_k_docs_public, max_top_k_docs_default, max_total_input_tokens_public_api, max_top_k_docs_public_api, \ max_input_tokens_public_api, model_token_mapping_outputs, anthropic_mapping, anthropic_mapping_outputs, \ user_prompt_for_fake_system_prompt, base_langchain_actions, google_mapping, google_mapping_outputs, generic_prefix, \ generic_postfix, mistralai_mapping, mistralai_mapping_outputs, langchain_modes_intrinsic 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, \ url_alive, have_wavio, have_soundfile, have_deepspeed, have_doctr, have_librosa, have_TTS, have_flash_attention_2, \ have_diffusers, sanitize_filename, get_gradio_tmp, get_is_gradio_h2oai 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, \ openai_gpts, get_vllm_extra_dict, anthropic_gpts, google_gpts, mistralai_gpts, is_vision_model from stopping import get_stopping invalid_key_msg = 'Invalid Access Key, request access key from sales@h2o.ai or jon.mckinney@h2o.ai, pass API key through API calls, or set API key in Login tab for UI' def evaluate_fake(*args, **kwargs): yield dict(response=invalid_key_msg, sources='', save_dict=dict(extra_dict=dict(base_model='')), llm_answers={}, response_no_refs='', sources_str='', audio=None, prompt_raw='') return
null
167,116
import ast import copy import functools import inspect import queue import sys import os import time import traceback import typing import uuid import warnings from datetime import datetime import httpx 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 from src.image_utils import get_image_file 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' 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, docs_joiner_default, \ docs_ordering_types_default, docs_token_handling_default, max_input_tokens_public, max_total_input_tokens_public, \ max_top_k_docs_public, max_top_k_docs_default, max_total_input_tokens_public_api, max_top_k_docs_public_api, \ max_input_tokens_public_api, model_token_mapping_outputs, anthropic_mapping, anthropic_mapping_outputs, \ user_prompt_for_fake_system_prompt, base_langchain_actions, google_mapping, google_mapping_outputs, generic_prefix, \ generic_postfix, mistralai_mapping, mistralai_mapping_outputs, langchain_modes_intrinsic 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, \ url_alive, have_wavio, have_soundfile, have_deepspeed, have_doctr, have_librosa, have_TTS, have_flash_attention_2, \ have_diffusers, sanitize_filename, get_gradio_tmp, get_is_gradio_h2oai SEED = 1236 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, \ openai_gpts, get_vllm_extra_dict, anthropic_gpts, google_gpts, mistralai_gpts, is_vision_model 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 get_client_from_inference_server(inference_server, base_model=None, raise_connection_exception=False): inference_server, headers = get_hf_server(inference_server) gr_client = None hf_client = None if base_model and is_vision_model(base_model): from gradio_utils.grclient import GradioClient gr_client = GradioClient(inference_server, check_hash=False, serialize=True) gr_client.setup() elif headers is None: try: # preload client since slow for gradio case especially from gradio_utils.grclient import GradioClient 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).setup() 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, httpx.LocalProtocolError) 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 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 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 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))) or not kwargs.get('truncation_generation', False): if hasattr(model_state['tokenizer'], 'max_output_len'): max_max_new_tokens = model_state['tokenizer'].max_output_len elif hasattr(model_state['tokenizer'], 'model_max_length'): max_max_new_tokens = model_state['tokenizer'].model_max_length else: # e.g. fast up, no model max_max_new_tokens = None else: max_max_new_tokens = None if kwargs['max_max_new_tokens'] is not None and max_max_new_tokens is not None: if kwargs.get('truncation_generation', False): return min(max_max_new_tokens, kwargs['max_max_new_tokens']) else: # listen to max_max_new_tokens, ignore model limit return max(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, from_ui): label_top_k_docs = "Number of document chunks (query) or pages/parts (summarize)" if is_public: min_top_k_docs = 1 if from_ui: max_top_k_docs = max_top_k_docs_public else: max_top_k_docs = max_top_k_docs_public_api else: min_top_k_docs = -1 max_top_k_docs = 1000 label_top_k_docs = label_top_k_docs + " (-1 = auto fill model context, all pages/docs for summarize)" return min_top_k_docs, max_top_k_docs, label_top_k_docs def gradio_to_llm(x, bot=False): gradio_tmp = get_gradio_tmp() # handle if gradio tuples in messages if x is None: x = '' if isinstance(x, (tuple, list)) and len(x) > 0: x = list(x) for insti, inst in enumerate(x): if isinstance(inst, str) and \ (inst.startswith('/tmp/gradio') or inst.startswith(gradio_tmp)) and \ os.path.isfile(inst): # below so if put into context gets rendered not as broken file if bot: x[ insti] = 'Image Generated (in MarkDown that can be shown directly to user): ![image](file=' + inst + ')' else: x[insti] = 'file=' + inst if len(x) == 1: x = x[0] x = str(x) if all(isinstance(x, str) for x in x) else '' return x def get_limited_prompt(instruction, iinput, tokenizer, estimated_instruction=None, prompter=None, inference_server=None, prompt_type=None, prompt_dict=None, max_new_tokens=None, system_prompt='', allow_chat_system_prompt=None, context='', chat_conversation=None, text_context_list=None, keep_sources_in_context=False, gradio_errors_to_chatbot=True, model_max_length=None, memory_restriction_level=0, langchain_mode=None, add_chat_history_to_context=True, verbose=False, doc_importance=0.5, hyde_level=None, min_max_new_tokens=512, max_input_tokens=-1, max_total_input_tokens=-1, truncation_generation=False, gradio_server=False, attention_sinks=False, ): if gradio_server or not inference_server: # can listen to truncation_generation pass else: # these don't support allowing going beyond total context truncation_generation = True # for templates, use estimated for counting, but adjust instruction as output if estimated_instruction is None: estimated_instruction = instruction if chat_conversation is None: chat_conversation = [] if not attention_sinks: if max_input_tokens >= 0: # max_input_tokens is used to runtime (via client/UI) to control actual filling of context max_input_tokens = min(model_max_length - min_max_new_tokens, max_input_tokens) else: max_input_tokens = model_max_length - min_max_new_tokens else: if max_input_tokens < 0: max_input_tokens = model_max_length if prompter: prompt_type = prompter.prompt_type prompt_dict = prompter.prompt_dict stream_output = prompter.stream_output system_prompt = prompter.system_prompt can_handle_system_prompt = prompter.can_handle_system_prompt else: can_handle_system_prompt = True # assume can so no extra conversation added if don't know generate_prompt_type = prompt_type external_handle_chat_conversation = False if inference_server and (any( inference_server.startswith(x) for x in ['openai_chat', 'openai_azure_chat', 'vllm_chat', 'anthropic', 'google'])) or gradio_server: # Chat APIs do not take prompting # Replicate does not need prompting if no chat history, but in general can take prompting # if using prompter, prompter.system_prompt will already be filled with automatic (e.g. from llama-2), # so if replicate final prompt with system prompt still correct because only access prompter.system_prompt that was already set # below already true for openai, # but not vllm by default as that can be any model and handled by FastChat API inside vLLM itself # claude is unique also, by not allowing system prompt, but as conversation # Also in list above, because get_limited_prompt called too late for it in gpt_langchain.py # So needs to be added directly in the get_llm for anthropic there, so used in ExtraChat generate_prompt_type = 'plain' # Chat APIs don't handle chat history via single prompt, but in messages, assumed to be handled outside this function # but we will need to compute good history for external use external_handle_chat_conversation = True chat_system_prompt = not external_handle_chat_conversation and \ not can_handle_system_prompt and \ allow_chat_system_prompt if chat_system_prompt and system_prompt: chat_conversation_system_prompt = [[user_prompt_for_fake_system_prompt, system_prompt]] else: chat_conversation_system_prompt = [] chat_conversation = chat_conversation_system_prompt + chat_conversation # 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=generate_prompt_type, prompt_dict=prompt_dict, model_max_length=max_input_tokens, memory_restriction_level=memory_restriction_level, keep_sources_in_context=keep_sources_in_context, system_prompt=system_prompt, hyde_level=hyde_level, gradio_errors_to_chatbot=gradio_errors_to_chatbot, min_max_new_tokens=min_max_new_tokens) from openai_server.backend_utils import structure_to_messages use_chat_template = prompt_type in [None, '', 'plain'] and \ (hasattr(tokenizer, 'chat_template') and tokenizer.chat_template not in [None, ''] or hasattr(tokenizer, 'default_chat_template') and tokenizer.default_chat_template not in [None, ''] ) if use_chat_template: messages = structure_to_messages(instruction, system_prompt if system_prompt not in [None, '', 'auto'] else None, history) context2 = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) iinput = '' context = '' else: context2 = history_to_context_func(history) context1 = context if context1 is None: context1 = '' # get how many more tokens in templated instruction, somewhat of estimate at fine level num_instruction_tokens = get_token_count(instruction, tokenizer) num_estimated_instruction_tokens = get_token_count(estimated_instruction, tokenizer) delta_instruction = max(0, num_estimated_instruction_tokens - num_instruction_tokens) # get estimated templated instruction tokens for counting purposes from h2oai_pipeline import H2OTextGenerationPipeline estimated_instruction, num_estimated_instruction_tokens = H2OTextGenerationPipeline.limit_prompt( estimated_instruction, tokenizer, max_prompt_length=max_input_tokens) data_point_just_instruction = dict(context='', instruction=estimated_instruction, input='') prompt_just_estimated_instruction = prompter.generate_prompt(data_point_just_instruction) num_instruction_tokens = get_token_count(prompt_just_estimated_instruction, tokenizer) # get actual instruction, limited by template limitation instruction, _ = H2OTextGenerationPipeline.limit_prompt(instruction, tokenizer, max_prompt_length=max_input_tokens - delta_instruction) context1, num_context1_tokens = H2OTextGenerationPipeline.limit_prompt(context1, tokenizer, max_prompt_length=max_input_tokens) context2_trial, num_context2_tokens = H2OTextGenerationPipeline.limit_prompt(context2, tokenizer, max_prompt_length=max_input_tokens) if not use_chat_template: context2 = context2_trial iinput, num_iinput_tokens = H2OTextGenerationPipeline.limit_prompt(iinput, tokenizer, max_prompt_length=max_input_tokens) # leave bit for instruction regardless of system prompt system_prompt, num_system_tokens = H2OTextGenerationPipeline.limit_prompt(system_prompt, tokenizer, max_prompt_length=int( max_input_tokens * 0.9)) # limit system prompt if prompter: prompter.system_prompt = system_prompt if external_handle_chat_conversation: pass else: # already accounted for in instruction num_system_tokens = 0 if text_context_list is None: text_context_list = [] num_doc_tokens = sum([get_token_count(x + docs_joiner_default, tokenizer) for x in text_context_list]) num_prompt_tokens0 = (num_system_tokens or 0) + \ (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 history_to_use_final = history.copy() # 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(max_input_tokens - num_non_doc_tokens, int(doc_importance * max_input_tokens)) 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(max_input_tokens - num_doc_tokens, int((1.0 - doc_importance) * max_input_tokens)) 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 # 5) limit system prompt diff1 = non_doc_max_length - ( num_system_tokens + num_instruction_tokens + num_context1_tokens + num_context2_tokens) diff2 = non_doc_max_length - (num_system_tokens + num_instruction_tokens + num_context1_tokens) diff3 = non_doc_max_length - (num_system_tokens + num_instruction_tokens) diff4 = non_doc_max_length - int(num_system_tokens + max_input_tokens * 0.1) diff5 = non_doc_max_length 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 history_to_use_final = [] low, high = 0, len(history) - 1 best_index = -1 # Keep track of the best index that satisfies the condition chat_index = 0 while low <= high: chat_index = (low + high) // 2 # Find the middle index if chat_system_prompt and history: # should always have history[0] but just protection in case # Don't ever lose system prompt if putting into chat history_to_use = [history[0]] + history[1 + chat_index:] else: history_to_use = history[0 + chat_index:] if use_chat_template: messages = structure_to_messages(instruction, system_prompt, history_to_use) context2 = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) else: context2 = history_to_context_func(history_to_use) num_context2_tokens = get_token_count(context2, tokenizer) diff1 = non_doc_max_length - ( num_system_tokens + num_instruction_tokens + num_context1_tokens + num_context2_tokens) if diff1 > 0: best_index = chat_index # Update best index # Condition met, try to find if there's a smaller history that still meets the condition history_to_use_final = history_to_use.copy() high = chat_index - 1 else: # Condition not met, need to include more history low = chat_index + 1 # i.e. if chat_index == len(history), then nothing can be consumed if best_index != -1: chat_index = best_index if chat_system_prompt and history: history_to_use_final = [history[0]] + history[1 + best_index:] else: history_to_use_final = history[0 + best_index:] else: history_to_use_final = history.copy() if verbose: print("chat_conversation used %d out of %d" % (chat_index, len(history)), flush=True) elif not use_chat_template and 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) elif not use_chat_template: # 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 max_prompt_length = max(0, diff4 - delta_instruction) instruction, _ = H2OTextGenerationPipeline.limit_prompt(instruction, tokenizer, max_prompt_length=max_prompt_length) # get actual instruction tokens data_point_just_instruction = dict(context='', instruction=instruction, input='') prompt_just_instruction = prompter.generate_prompt(data_point_just_instruction) num_instruction_tokens = get_token_count(prompt_just_instruction, tokenizer) + delta_instruction # update full context # avoid including chat_conversation if handled externally, only used above for computations of prompt context = context1 + context2 if not external_handle_chat_conversation else context1 # update token counts (docs + non-docs, all tokens) num_prompt_tokens = (num_system_tokens or 0) + \ (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 # 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 if truncation_generation: max_new_tokens = min(max_new_tokens, model_max_length - num_prompt_tokens) if os.getenv('HARD_ASSERTS'): if max_new_tokens < min_max_new_tokens: raise ValueError("Invalid max_new_tokens=%s" % max_new_tokens) if prompter is None: # get prompter debug = False stream_output = False # doesn't matter prompter = Prompter(prompt_type, prompt_dict, debug=debug, stream_output=stream_output, system_prompt=system_prompt) if prompt_type != generate_prompt_type: # override just this attribute, keep system_prompt etc. from original prompt_type prompter.prompt_type = generate_prompt_type if not use_chat_template: 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 # if used history -> context2, then already have (if exists) system prompt etc., just get rest of reduced prompt reduced = context_from_history prompt = prompter.generate_prompt(data_point, context_from_history=context_from_history, reduced=reduced) else: prompt = context 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, \ history_to_use_final, external_handle_chat_conversation, \ top_k_docs, one_doc_size, truncation_generation, system_prompt def model_name_to_prompt_type(model_name, model_name0=None, llamacpp_dict={}, prompt_type_old=None): model_lower0 = model_name0.strip().lower() if model_name0 is not None else '' model_lower = model_name.strip().lower() llama_lower = llamacpp_dict.get('model_path_llama', '').lower() if llamacpp_dict is not None else '' llama_lower_hf = get_llama_lower_hf(llama_lower) llama_lower_base = os.path.basename(llama_lower) if llama_lower_hf and llama_lower_hf in inv_prompt_type_to_model_lower: prompt_type1 = inv_prompt_type_to_model_lower[llama_lower_hf] elif llama_lower_base and llama_lower_base in inv_prompt_type_to_model_lower: prompt_type1 = inv_prompt_type_to_model_lower[llama_lower_base] elif model_lower0 and model_lower0 in inv_prompt_type_to_model_lower: prompt_type1 = inv_prompt_type_to_model_lower[model_lower0] elif model_lower and model_lower in inv_prompt_type_to_model_lower: prompt_type1 = inv_prompt_type_to_model_lower[model_lower] else: prompt_type1 = prompt_type_old or '' return prompt_type1 def get_image_file(image_file, image_control, document_choice): if image_control is not None: img_file = image_control elif image_file is not None: img_file = image_file else: image_types = get_image_types() img_file = [x for x in document_choice if any(x.endswith('.' + y) for y in image_types)] if document_choice else [] img_file = img_file[0] if img_file else None return img_file 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', 'document_source_substrings', 'document_source_substrings_op', 'document_content_substrings', 'document_content_substrings_op', 'pre_prompt_query', 'prompt_query', 'pre_prompt_summary', 'prompt_summary', 'hyde_llm_prompt', 'system_prompt', ] + \ reader_names + \ ['visible_models', 'h2ogpt_key', 'add_search_to_context', 'chat_conversation', 'text_context_list', 'docs_ordering_type', 'min_max_new_tokens', 'max_input_tokens', 'max_total_input_tokens', 'docs_token_handling', 'docs_joiner', 'hyde_level', 'hyde_template', 'hyde_show_only_final', 'doc_json_mode', 'metadata_in_context', 'chatbot_role', 'speaker', 'tts_language', 'tts_speed', 'image_file', 'image_control', ] class DocumentSubset(Enum): Relevant = 0 RelSources = 1 TopKSources = 2 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 LangChainAction(Enum): """LangChain action""" QUERY = "Query" # WIP: # SUMMARIZE_MAP = "Summarize_map_reduce" SUMMARIZE_MAP = "Summarize" SUMMARIZE_ALL = "Summarize_all" SUMMARIZE_REFINE = "Summarize_refine" EXTRACT = "Extract" IMAGE_GENERATE = "ImageGen" IMAGE_GENERATE_HIGH = "ImageGenHigh" IMAGE_CHANGE = "ImageChange" IMAGE_QUERY = "ImageQuery" 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 gr_to_lg(image_audio_loaders, pdf_loaders, url_loaders, use_pymupdf=None, use_unstructured_pdf=None, use_pypdf=None, enable_pdf_ocr=None, enable_pdf_doctr=None, try_pdf_as_html=None, **kwargs, ): assert use_pymupdf is not None assert use_unstructured_pdf is not None assert use_pypdf is not None assert enable_pdf_ocr is not None assert enable_pdf_doctr is not None assert try_pdf_as_html is not None if image_audio_loaders is None: image_audio_loaders = kwargs['image_audio_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, use_scrapeplaywright='ScrapeWithPlayWright' in url_loaders, use_scrapehttp='ScrapeWithHttp' in url_loaders, # pdfs # ... else condition uses default from command line, by default auto, so others can be used as backup # make sure pass 'off' for those if really want fully disabled. use_pymupdf='on' if 'PyMuPDF' in pdf_loaders else use_pymupdf, use_unstructured_pdf='on' if 'Unstructured' in pdf_loaders else use_unstructured_pdf, use_pypdf='on' if 'PyPDF' in pdf_loaders else use_pypdf, enable_pdf_ocr='on' if 'OCR' in pdf_loaders else enable_pdf_ocr, enable_pdf_doctr='on' if 'DocTR' in pdf_loaders else enable_pdf_doctr, try_pdf_as_html='on' if 'TryHTML' in pdf_loaders else try_pdf_as_html, # images and audio enable_ocr='OCR' in image_audio_loaders, enable_doctr='DocTR' in image_audio_loaders, enable_pix2struct='Pix2Struct' in image_audio_loaders, enable_captions='Caption' in image_audio_loaders or 'CaptionBlip2' in image_audio_loaders, enable_transcriptions="ASR" in image_audio_loaders or 'ASRLarge' in image_audio_loaders, enable_llava='LLaVa' in image_audio_loaders, ) if 'CaptionBlip2' in image_audio_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'] if 'ASRLarge' in image_audio_loaders: # just override, don't actually do both even if user chose both asr_model = "openai/whisper-large-v3" else: asr_model = kwargs['asr_model'] return ret, captions_model, asr_model docs_ordering_types_default = 'best_near_prompt' docs_token_handling_default = 'split_or_merge' docs_joiner_default = '\n\n' max_input_tokens_public = 3100 max_input_tokens_public_api = 2 * max_input_tokens_public max_total_input_tokens_public = 4096 * 2 max_total_input_tokens_public_api = 2 * max_total_input_tokens_public def clear_torch_cache(allow_skip=False): if allow_skip and os.getenv('CLEAR_CLEAR_TORCH', '2') == '1' or os.getenv('CLEAR_CLEAR_TORCH', '2') == '0': return try: import torch if torch.cuda.is_available(): torch.cuda.empty_cache() torch.cuda.ipc_collect() gc.collect() except RuntimeError as e: print("clear_torch_cache error: %s" % ''.join(traceback.format_tb(e.__traceback__)), flush=True) class NullContext(threading.local): """No-op context manager, executes block without doing any additional processing. Used as a stand-in if a particular block of code is only sometimes used with a normal context manager: """ def __init__(self, *args, **kwargs): pass def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_traceback): self.finally_act() def finally_act(self): pass def wrapped_partial(func, *args, **kwargs): """ Give partial properties of normal function, like __name__ attribute etc. :param func: :param args: :param kwargs: :return: """ partial_func = functools.partial(func, *args, **kwargs) functools.update_wrapper(partial_func, func) return partial_func class EThread(threading.Thread): # Function that raises the custom exception def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None, streamer=None, bucket=None): self.bucket = bucket self.streamer = streamer self.exc = None self._return = None super().__init__(group=group, target=target, name=name, args=args, kwargs=kwargs, daemon=daemon) def run(self): # Variable that stores the exception, if raised by someFunction try: if self._target is not None: self._return = self._target(*self._args, **self._kwargs) except BaseException as e: print("thread exception: %s" % str(sys.exc_info())) self.bucket.put(sys.exc_info()) self.exc = e if self.streamer: print("make stop: %s" % str(sys.exc_info()), flush=True) self.streamer.do_stop = True finally: # Avoid a refcycle if the thread is running a function with # an argument that has a member that points to the thread. del self._target, self._args, self._kwargs def join(self, timeout=None): threading.Thread.join(self) # Since join() returns in caller thread # we re-raise the caught exception # if any was caught if self.exc: raise self.exc return self._return def sanitize_filename(name, file_length_limit=250): """ Sanitize file *base* names. :param name: name to sanitize :param file_length_limit: bit smaller than 256 for safety :return: """ bad_chars = ['[', ']', ',', '/', '\\', '\\w', '\\s', '-', '+', '\"', '\'', '>', '<', ' ', '=', ')', '(', ':', '^'] for char in bad_chars: name = name.replace(char, "_") length = len(name) sha_length = 32 real_length_limit = file_length_limit - (sha_length + 2) assert real_length_limit > 0, "Bad file limit length: %s %s" % (file_length_limit, real_length_limit) if length > file_length_limit: sha = get_sha(name) half_real_length_limit = max(1, int(real_length_limit / 2)) name = name[0:half_real_length_limit] + "_" + sha + "_" + name[length - half_real_length_limit:length] return name def get_hf_server(inference_server): inf_split = inference_server.split(" ") assert len(inf_split) == 1 or len(inf_split) == 3 inference_server = inf_split[0] if len(inf_split) == 3: headers = {"authorization": "%s %s" % (inf_split[1], inf_split[2])} else: headers = None return inference_server, headers def set_openai(inference_server, model_name=None): if inference_server.startswith('vllm'): api_key = "EMPTY" inf_type = inference_server.split(':')[0].strip() ip_port_vllm = ':'.join(inference_server.split(':')[1:]) if ip_port_vllm.startswith('https://'): http_prefix = 'https://' ip_port_vllm = ip_port_vllm[len(http_prefix):] auto_v1 = False elif ip_port_vllm.startswith('http://'): http_prefix = 'http://' ip_port_vllm = ip_port_vllm[len(http_prefix):] auto_v1 = False else: http_prefix = 'http://' auto_v1 = True address = ':'.join(ip_port_vllm.split(':')[0:1]).strip() api_base = http_prefix + address if len(ip_port_vllm.split(':')) >= 2: port_vllm = ip_port_vllm.split(':')[1].strip() if port_vllm not in [None, 'None']: api_base += ':' + port_vllm if len(ip_port_vllm.split(':')) >= 3: # if not there, use EMPTY as default url_path = ip_port_vllm.split(':')[2].strip() if url_path not in [None, 'None']: api_base += url_path # assume includes prefix of / and /v1 if auto_v1 and not api_base.endswith('/v1'): api_base += '/v1' if len(ip_port_vllm.split(':')) >= 4: # if not there, use EMPTY as default api_key = ip_port_vllm.split(':')[3].strip() from openai import OpenAI, AsyncOpenAI client_args = dict(base_url=api_base, api_key=api_key) client = OpenAI(**client_args) async_client = AsyncOpenAI(**client_args) return client, async_client, inf_type, None, api_base, None, api_key else: api_key = os.getenv("OPENAI_API_KEY") base_url = None deployment_type = None api_version = None inf_type = inference_server.split(':')[0].strip() if len(inference_server.split(':')) >= 2: deployment_type = inference_server.split(':')[1].strip() if len(inference_server.split(':')) >= 3: base_url = inference_server.split(':')[2].strip() base_url = 'https://' + base_url if len(inference_server.split(':')) >= 4: api_version = inference_server.split(':')[3].strip() if inference_server.startswith('openai_azure'): if api_version in ['None', None]: # for function tools support # https://github.com/Azure/azure-rest-api-specs/tree/main/specification/cognitiveservices/data-plane/AzureOpenAI/inference/preview/2023-12-01-preview api_version = "2023-12-01-preview" if os.getenv('OPENAI_AZURE_KEY') is not None: # use this instead if exists api_key = os.getenv("OPENAI_AZURE_KEY") elif api_version in ['None', None]: api_version = None if len(inference_server.split(':')) >= 5: api_key0 = inference_server.split(':')[4].strip() if api_key0 not in ['None', None]: api_key = api_key0 if deployment_type == 'None': deployment_type = None if base_url == 'None': base_url = None if base_url == 'None': base_url = None # cannot use non-chat model, uses old openai. stuff if go through to H2OOpenAI with chat model if model_name: chat_model = (model_name.startswith("gpt-3.5-turbo") or model_name.startswith( "gpt-4")) and "-instruct" not in model_name if chat_model and inf_type == 'openai_azure': inf_type = 'openai_azure_chat' if chat_model and inf_type == 'openai': inf_type = 'openai_chat' from openai import OpenAI, AzureOpenAI, AsyncOpenAI, AsyncAzureOpenAI if inf_type in ['openai_azure', 'openai_azure_chat']: client_args = dict(azure_deployment=deployment_type, azure_endpoint=base_url, api_version=api_version, api_key=api_key) client = AzureOpenAI(**client_args) async_client = AsyncAzureOpenAI(**client_args) else: client_args = dict(base_url=base_url, api_key=api_key) client = OpenAI(**client_args) async_client = AsyncOpenAI(**client_args) return client, async_client, inf_type, deployment_type, base_url, api_version, api_key def str_to_list(x, allow_none=False): if isinstance(x, str): if len(x.strip()) > 0: if x.strip().startswith('['): x = ast.literal_eval(x.strip()) else: raise ValueError("Invalid str_to_list for %s" % x) else: x = [] elif x is None and not allow_none: x = [] if allow_none: assert isinstance(x, (type(None), list)) else: assert isinstance(x, list) return x def str_to_dict(x): if isinstance(x, str): if len(x.strip()) > 0: if x.strip().startswith('{'): x = ast.literal_eval(x.strip()) else: raise ValueError("Invalid str_to_dict for %s" % x) else: x = {} elif x is None: x = {} assert isinstance(x, dict) return x def get_gradio_tmp(): gradio_tmp = '/tmp/gradio' makedirs(gradio_tmp, exist_ok=True) # won't hurt if soft link if exists gradio_tmp = os.path.realpath(gradio_tmp) return gradio_tmp non_hf_types = ['gpt4all_llama', 'llama', 'gptj'] def is_vision_model(base_model): return base_model.startswith('llava-') or \ base_model.startswith('liuhaotian/llava-') or \ base_model.startswith('Qwen-VL') or \ base_model.startswith('Qwen/Qwen-VL') def generate_prompt(data_point, prompt_type, prompt_dict, reduced, making_context, system_prompt=None, histi=-1): context = data_point.get('context') if context is None: context = '' instruction = data_point.get('instruction') input = data_point.get('input') output = data_point.get('output') prompt_type = data_point.get('prompt_type', prompt_type) prompt_dict = data_point.get('prompt_dict', prompt_dict) assert prompt_type in prompt_types, "Bad prompt type: %s" % prompt_type promptA, promptB, PreInstruct, PreInput, PreResponse, \ terminate_response, chat_sep, chat_turn_sep, humanstr, botstr, \ generates_leading_space, system_prompt, can_handle_system_prompt = \ get_prompt(prompt_type, prompt_dict, context, reduced, making_context, system_prompt=system_prompt, histi=histi) # could avoid if reduce=True, but too complex for parent functions to handle prompt = context if input and promptA: prompt += f"""{promptA}""" elif promptB: prompt += f"""{promptB}""" if instruction and PreInstruct is not None and input and PreInput is not None: prompt += f"""{PreInstruct}{instruction}{PreInput}{input}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) elif instruction and input and PreInstruct is None and PreInput is not None: prompt += f"""{PreInput}{instruction} {input}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) elif input and instruction and PreInput is None and PreInstruct is not None: prompt += f"""{PreInstruct}{instruction} {input}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) elif instruction and PreInstruct is not None: prompt += f"""{PreInstruct}{instruction}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) elif input and PreInput is not None: prompt += f"""{PreInput}{input}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) elif input and instruction and PreInput is not None: prompt += f"""{PreInput}{instruction}{input}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) elif input and instruction and PreInstruct is not None: prompt += f"""{PreInstruct}{instruction}{input}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) elif input and instruction: # i.e. for simple_instruct prompt += f"""{instruction}: {input}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) elif input: prompt += f"""{input}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) elif instruction: prompt += f"""{instruction}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) if PreResponse is not None: prompt += f"""{PreResponse}""" pre_response = PreResponse # Don't use strip else: pre_response = '' if output: prompt += f"""{output}""" return prompt, pre_response, terminate_response, chat_sep, chat_turn_sep class Prompter(object): def __init__(self, prompt_type, prompt_dict, debug=False, stream_output=False, repeat_penalty=False, allowed_repeat_line_length=10, system_prompt=None): self.prompt_type = prompt_type self.prompt_dict = prompt_dict self.debug = debug self.stream_output = stream_output self.repeat_penalty = repeat_penalty self.allowed_repeat_line_length = allowed_repeat_line_length self.prompt = None self.system_prompt = system_prompt context = "" # not for chat context reduced = False # not for chat context making_context = False # not for chat context self.promptA, self.promptB, self.PreInstruct, self.PreInput, self.PreResponse, \ self.terminate_response, self.chat_sep, self.chat_turn_sep, self.humanstr, self.botstr, \ self.generates_leading_space, self.system_prompt, self.can_handle_system_prompt = \ get_prompt(self.prompt_type, self.prompt_dict, context, reduced, making_context, system_prompt=system_prompt) self.pre_response = self.PreResponse def stop_sequences(self): terminate_response = self.terminate_response or [] stop_sequences = list(set(terminate_response + [self.PreResponse])) stop_sequences = [x for x in stop_sequences if x] return stop_sequences def generate_prompt(self, data_point, reduced=False, context_from_history=None): """ data_point['context'] is assumed to be like a system prompt or pre-conversation, not inserted after user prompt :param data_point: :param reduced: :param context_from_history: whether context is from reduced=True version of history in prompt form In which case we need to put promptA at very front to recover correct behavior :return: """ if context_from_history is None and data_point.get('context'): context_from_history = True reduced = True making_context = False # whether really making final prompt or just generating context prompt, _, _, _, _ = generate_prompt(data_point, self.prompt_type, self.prompt_dict, reduced, making_context, histi=-1, system_prompt=self.system_prompt) if self.debug: print("prompt: %s" % prompt, flush=True) # if have context, should have always reduced and only preappend promptA/B here if data_point.get('context') and context_from_history: if data_point.get('input') and self.promptA: prompt = self.promptA + prompt elif self.promptB: prompt = self.promptB + prompt self.prompt = prompt return prompt def get_response(self, outputs, prompt=None, sanitize_bot_response=False, only_new_text=False, plain_prompt_special=False): if isinstance(outputs, str): outputs = [outputs] if self.debug: print("output:\n%s" % '\n\n'.join(outputs), flush=True) if prompt is not None: self.prompt = prompt def clean_response(response): meaningless_words = ['<pad>', '</s>', '<|endoftext|>'] for word in meaningless_words: response = response.replace(word, "") if sanitize_bot_response: # from better_profanity import profanity # response = profanity.censor(response) pass if self.generates_leading_space and isinstance(response, str) and len(response) > 0 and response[0] == ' ': response = response[1:] return response def clean_repeats(response): lines = response.split('\n') new_lines = [] [new_lines.append(line) for line in lines if line not in new_lines or len(line) < self.allowed_repeat_line_length] if self.debug and len(lines) != len(new_lines): print("cleaned repeats: %s %s" % (len(lines), len(new_lines)), flush=True) response = '\n'.join(new_lines) return response multi_output = len(outputs) > 1 for oi, output in enumerate(outputs): if plain_prompt_special and \ self.prompt_type in [PromptType.plain.value, str(PromptType.plain.value), PromptType.plain.name]: output = clean_response(output) allow_terminate = True elif only_new_text: # only use terminate, that will have other variations of cleaning that include \n etc. not just simple human bot that will leave residual \n allow_terminate = True elif prompt is None: allow_terminate = True # then use most basic parsing like pipeline if not self.botstr: pass else: if self.humanstr: output = clean_response(output.split(self.botstr)[-1].split(self.humanstr)[0]) else: # i.e. use after bot but only up to next bot output = clean_response(output.split(self.botstr)[-1].split(self.botstr)[0]) else: # find first instance of prereponse # prompt sometimes has odd characters, that mutate length, # so can't go by length alone if self.pre_response: outputi = output.find(prompt) if outputi >= 0: output = output[outputi + len(prompt):] allow_terminate = True else: # subtraction is risky due to space offsets sometimes, so only do if necessary output = output[len(prompt) - len(self.pre_response):] # [1] to avoid repeated pre_response, just take first (after prompt - pre_response for chat) if self.pre_response in output: output = output.split(self.pre_response)[1] allow_terminate = True else: if output: print("Failure of parsing or not enough output yet: %s" % output, flush=True) allow_terminate = False else: allow_terminate = True output = output[len(prompt):] # clean after subtract prompt out, so correct removal of pre_response output = clean_response(output) if self.repeat_penalty: output = clean_repeats(output) if self.terminate_response and allow_terminate: finds = [] for term in self.terminate_response: finds.append(output.find(term)) finds = [x for x in finds if x >= 0] if len(finds) > 0: termi = finds[0] output = output[:termi] else: output = output if multi_output: # prefix with output counter output = "\n=========== Output %d\n\n" % (1 + oi) + output if oi > 0: # post fix outputs with seperator output += '\n' output = self.fix_text(self.prompt_type, output) outputs[oi] = output # join all outputs, only one extra new line between outputs output = '\n'.join(outputs) if self.debug: print("outputclean:\n%s" % '\n\n'.join(outputs), flush=True) return output def fix_text(prompt_type1, text1): # NOTE: Risk that may sometimes actually end like these, but very unlikely if prompt_type1 == 'human_bot': # hack bug in training human-bot models, no single token is stop token hfix = '<human' if text1.endswith(hfix): text1 = text1[:-len(hfix)] hfix = '<bot' if text1.endswith(hfix): text1 = text1[:-len(hfix)] if prompt_type1 == 'docsgpt': # hack bug in training docsgpt models, no single token is stop token hfix = '### Inst' if text1.endswith(hfix): text1 = text1[:-len(hfix)] if prompt_type1 == 'vicuna11': # hack bug in NousResearch/Nous-Capybara-34B that used different tokenizer and training, so no single token is stop token hfix = '</s' if text1.endswith(hfix): text1 = text1[:-len(hfix)] return text1 def get_vllm_extra_dict(tokenizer, stop_sequences=[], repetition_penalty=None): stop_token_ids = [tokenizer.added_tokens_encoder[x] for x in stop_sequences if hasattr(tokenizer, 'added_tokens_encoder') and x in tokenizer.added_tokens_encoder] if hasattr(tokenizer, 'eos_token_id'): stop_token_ids.extend([tokenizer.eos_token_id]) vllm_extra_dict = dict(extra_body=dict(stop_token_ids=stop_token_ids)) if repetition_penalty is not None: vllm_extra_dict['extra_body'].update(repetition_penalty=repetition_penalty) return vllm_extra_dict def get_stopping(prompt_type, prompt_dict, tokenizer, device, base_model, human='<human>:', bot="<bot>:", model_max_length=None, prompter=None, stop=None, truncation_generation=False): stop_words = [] encounters = [] # FIXME: prompt_dict unused currently user_human_assistant_types = [PromptType.instruct_vicuna.value, str(PromptType.instruct_vicuna.value), PromptType.instruct_vicuna.name] + \ [PromptType.guanaco.value, str(PromptType.guanaco.value), PromptType.guanaco.name] + \ [PromptType.one_shot.value, str(PromptType.one_shot.value), PromptType.one_shot.name] + \ [PromptType.instruct_vicuna2.value, str(PromptType.instruct_vicuna2.value), PromptType.instruct_vicuna2.name] + \ [PromptType.instruct_vicuna3.value, str(PromptType.instruct_vicuna3.value), PromptType.instruct_vicuna3.name] + \ [PromptType.instruct_with_end.value, str(PromptType.instruct_with_end.value), PromptType.instruct_with_end.name] human_bot_types = [PromptType.human_bot.value, str(PromptType.human_bot.value), PromptType.human_bot.name] + \ [PromptType.human_bot_orig.value, str(PromptType.human_bot_orig.value), PromptType.human_bot_orig.name] all_types = user_human_assistant_types + human_bot_types if prompt_type in all_types: if prompt_type in human_bot_types: # encounters = [prompt.count(human) + 1, prompt.count(bot) + 1] # stopping only starts once output is beyond prompt # 1 human is enough to trigger, but need 2 bots, because very first view back will be bot we added stop_words = [human, bot, '\n' + human, '\n' + bot] encounters = [1, 2] elif prompt_type in user_human_assistant_types: # even below is not enough, generic strings and many ways to encode stop_words = [ '### Human:', """ ### Human:""", """ ### Human: """, """### Human: """, """### Human:""", '### Assistant:', """ ### Assistant:""", """ ### Assistant: """, """### Assistant: """, """### Assistant:""" ] if prompt_type in [PromptType.instruct_vicuna2.value, str(PromptType.instruct_vicuna2.value), PromptType.instruct_vicuna2.name]: stop_words = [x.upper() for x in stop_words] if prompt_type in [PromptType.instruct_vicuna3.value, str(PromptType.instruct_vicuna3.value), PromptType.instruct_vicuna3.name]: stop_words = [x.replace('Human', 'User') for x in stop_words] encounters = [1, 2] else: # some instruct prompts have this as end, doesn't hurt to stop on it since not common otherwise stop_words = ['### End'] encounters = [1] elif prompter and prompter.terminate_response: stop_words = prompter.terminate_response encounters = [1] * len(stop_words) handle_newlines = [True] * len(stop_words) # add other stop words too if passed, e.g. for LangChain agents if stop: stop_words += stop encounters += [1] * len(stop) handle_newlines += [False] * len(stop) # get stop tokens stop_words_ids = [ tokenizer(stop_word, return_tensors='pt')['input_ids'].squeeze() for stop_word in stop_words] # handle single token case stop_words_ids = [x if len(x.shape) > 0 else torch.tensor([x]) for x in stop_words_ids] stop_words_ids = [x for x in stop_words_ids if x.shape[0] > 0] # avoid padding in front of tokens if tokenizer._pad_token: # use hidden variable to avoid annoying properly logger bug stop_words_ids = [x[1:] if x[0] == tokenizer.pad_token_id and len(x) > 1 else x for x in stop_words_ids] if tokenizer._unk_token: # use hidden variable to avoid annoying properly logger bug stop_words_ids = [x[1:] if x[0] == tokenizer.unk_token_id and len(x) > 1 else x for x in stop_words_ids] stop_words_ids = [x[:-1] if x[-1] == tokenizer.unk_token_id and len(x) > 1 else x for x in stop_words_ids] if tokenizer._eos_token: # use hidden variable to avoid annoying properly logger bug stop_words_ids = [x[:-1] if x[-1] == tokenizer.eos_token_id and len(x) > 1 else x for x in stop_words_ids] if tokenizer._bos_token: # use hidden variable to avoid annoying properly logger bug stop_words_ids = [x[1:] if x[0] == tokenizer.bos_token_id and len(x) > 1 else x for x in stop_words_ids] stop_words_ids = [x[:-1] if x[-1] == tokenizer.bos_token_id and len(x) > 1 else x for x in stop_words_ids] if base_model and t5_type(base_model): # T5 encoder converts internal double space to space+new line, so fix for stopi, stop_word_id in enumerate(stop_words_ids): start = stop_word_id[0:1] mlist = stop_word_id[1:-1] end = stop_word_id[-1:] mlist = [tokenizer.vocab[' '] if x == tokenizer.vocab['\n'] else x for x in mlist] stop_words_ids[stopi] = torch.tensor(list(start) + list(mlist) + list(end), device=stop_word_id.device) # handle fake \n added stop_words_ids = [x[1:] if y[0] == '\n' and handle_newline else x for x, y, handle_newline in zip(stop_words_ids, stop_words, handle_newlines)] if stop_words_ids: # build stopper stopping_criteria = StoppingCriteriaList( [StoppingCriteriaSub(stops=stop_words_ids, stop_words=stop_words, encounters=encounters, device=device, model_max_length=model_max_length, tokenizer=tokenizer, truncation_generation=truncation_generation)]) else: # nothing to stop on stopping_criteria = StoppingCriteriaList() return stopping_criteria class GradioClient(Client): """ Parent class of gradio client To handle automatically refreshing client if detect gradio server changed """ def __init__( self, src: str, hf_token: str | None = None, max_workers: int = 40, serialize: bool | None = None, output_dir: str | Path | None = DEFAULT_TEMP_DIR, verbose: bool = False, auth: tuple[str, str] | None = None, headers: dict[str, str] | None = None, upload_files: bool = True, download_files: bool = True, h2ogpt_key: str = None, persist: bool = False, check_hash: bool = True, check_model_name: bool = False, ): """ Parameters: Base Class parameters + h2ogpt_key: h2oGPT key to gain access to the server persist: whether to persist the state, so repeated calls are aware of the prior user session This allows the scratch MyData to be reused, etc. This also maintains the chat_conversation history check_hash: whether to check git hash for consistency between server and client to ensure API always up to date check_model_name: whether to check the model name here (adds delays), or just let server fail (faster) """ if serialize is None: # else converts inputs arbitrarily and outputs mutate # False keeps as-is and is normal for h2oGPT serialize = False self.args = tuple([src]) self.kwargs = dict( hf_token=hf_token, max_workers=max_workers, serialize=serialize, output_dir=output_dir, verbose=verbose, h2ogpt_key=h2ogpt_key, persist=persist, check_hash=check_hash, check_model_name=check_model_name, ) if is_gradio_client_version7plus: # 4.18.0: #self.kwargs.update(dict(auth=auth, upload_files=upload_files, download_files=download_files)) # 4.17.0: self.kwargs.update(dict(auth=auth)) self.verbose = verbose self.hf_token = hf_token if serialize is not None: warnings.warn( "The `serialize` parameter is deprecated and will be removed. Please use the equivalent `upload_files` parameter instead." ) upload_files = serialize self.serialize = serialize self.upload_files = upload_files self.download_files = download_files self.space_id = None self.cookies: dict[str, str] = {} if is_gradio_client_version7plus: self.output_dir = ( str(output_dir) if isinstance(output_dir, Path) else output_dir ) else: self.output_dir = output_dir self.max_workers = max_workers self.src = src self.auth = auth self.headers = headers self.config = None self.h2ogpt_key = h2ogpt_key self.persist = persist self.check_hash = check_hash self.check_model_name = check_model_name self.chat_conversation = [] # internal for persist=True self.server_hash = None # internal def __repr__(self): if self.config: return self.view_api(print_info=False, return_format="str") return "Not setup for %s" % self.src def __str__(self): if self.config: return self.view_api(print_info=False, return_format="str") return "Not setup for %s" % self.src def setup(self): src = self.src headers0 = self.headers self.headers = build_hf_headers( token=self.hf_token, library_name="gradio_client", library_version=utils.__version__, ) if headers0: self.headers.update(headers0) if 'authorization' in self.headers and self.headers['authorization'] == 'Bearer ': self.headers['authorization'] = 'Bearer hf_xx' if src.startswith("http://") or src.startswith("https://"): _src = src if src.endswith("/") else src + "/" else: _src = self._space_name_to_src(src) if _src is None: raise ValueError( f"Could not find Space: {src}. If it is a private Space, please provide an hf_token." ) self.space_id = src self.src = _src state = self._get_space_state() if state == SpaceStage.BUILDING: if self.verbose: print("Space is still building. Please wait...") while self._get_space_state() == SpaceStage.BUILDING: time.sleep(2) # so we don't get rate limited by the API pass if state in utils.INVALID_RUNTIME: raise ValueError( f"The current space is in the invalid state: {state}. " "Please contact the owner to fix this." ) if self.verbose: print(f"Loaded as API: {self.src} ✔") if is_gradio_client_version7plus: if self.auth is not None: self._login(self.auth) self.config = self._get_config() self.api_url = urllib.parse.urljoin(self.src, utils.API_URL) if is_gradio_client_version7plus: self.protocol: str = self.config.get("protocol", "ws") self.sse_url = urllib.parse.urljoin( self.src, utils.SSE_URL_V0 if self.protocol == "sse" else utils.SSE_URL ) self.sse_data_url = urllib.parse.urljoin( self.src, utils.SSE_DATA_URL_V0 if self.protocol == "sse" else utils.SSE_DATA_URL, ) self.ws_url = urllib.parse.urljoin( self.src.replace("http", "ws", 1), utils.WS_URL ) self.upload_url = urllib.parse.urljoin(self.src, utils.UPLOAD_URL) self.reset_url = urllib.parse.urljoin(self.src, utils.RESET_URL) if is_gradio_client_version7plus: self.app_version = version.parse(self.config.get("version", "2.0")) self._info = None self.session_hash = str(uuid.uuid4()) self.get_endpoints(self) # Disable telemetry by setting the env variable HF_HUB_DISABLE_TELEMETRY=1 # threading.Thread(target=self._telemetry_thread).start() self.server_hash = self.get_server_hash() return self def get_endpoints(client, verbose=False): t0 = time.time() # Create a pool of threads to handle the requests client.executor = concurrent.futures.ThreadPoolExecutor( max_workers=client.max_workers ) if is_gradio_client_version7plus: from gradio_client.client import EndpointV3Compatibility endpoint_class = ( Endpoint if client.protocol.startswith("sse") else EndpointV3Compatibility ) else: endpoint_class = Endpoint if is_gradio_client_version7plus: client.endpoints = [ endpoint_class(client, fn_index, dependency, client.protocol) for fn_index, dependency in enumerate(client.config["dependencies"]) ] else: client.endpoints = [ endpoint_class(client, fn_index, dependency) for fn_index, dependency in enumerate(client.config["dependencies"]) ] if is_gradio_client_version7plus: client.stream_open = False client.streaming_future = None from gradio_client.utils import Message client.pending_messages_per_event = {} client.pending_event_ids = set() if verbose: print("duration endpoints: %s" % (time.time() - t0), flush=True) def get_server_hash(self): t0 = time.time() if self.config is None: self.setup() """ Get server hash using super without any refresh action triggered Returns: git hash of gradio server """ try: if self.check_hash: return super().submit(api_name="/system_hash").result() else: return "GET_GITHASH" finally: if self.verbose: print("duration server_hash: %s" % (time.time() - t0), flush=True) def refresh_client_if_should(self): if self.config is None: self.setup() # 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: if self.verbose: print("server hash changed: %s %s" % (self.server_hash, server_hash), flush=True) if self.server_hash is not None and self.persist: if self.verbose: print( "Failed to persist due to server hash change, only kept chat_conversation not user session hash", flush=True) # risky to persist if hash changed self.refresh_client() self.server_hash = server_hash 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: """ if self.config is None: self.setup() kwargs = self.kwargs.copy() kwargs.pop('h2ogpt_key', None) kwargs.pop('persist', None) kwargs.pop('check_hash', None) kwargs.pop('check_model_name', None) ntrials = 3 client = None for trial in range(0, ntrials + 1): try: client = Client(*self.args, **kwargs) except ValueError as e: if trial >= ntrials: raise else: if self.verbose: print("Trying refresh %d/%d %s" % (trial, ntrials - 1, str(e))) trial += 1 time.sleep(10) if client is None: raise RuntimeError("Failed to get new client") session_hash0 = self.session_hash if self.persist else None for k, v in client.__dict__.items(): setattr(self, k, v) if session_hash0: # keep same system hash in case server API only changed and not restarted self.session_hash = session_hash0 if self.verbose: print("Hit refresh_client(): %s %s" % (self.session_hash, session_hash0)) # ensure server hash also updated self.server_hash = self.get_server_hash() def clone(self): if self.config is None: self.setup() client = GradioClient("") for k, v in self.__dict__.items(): setattr(client, k, v) client.reset_session() self.get_endpoints(client) # transfer internals in case used client.server_hash = self.server_hash client.chat_conversation = self.chat_conversation return client def submit( self, *args, api_name: str | None = None, fn_index: int | None = None, result_callbacks: Callable | list[Callable] | None = None, exception_handling=True, # new_stream = True, can make False, doesn't matter. ) -> Job: if self.config is None: self.setup() # 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\n\n%s" % (str(e), traceback.format_exc()), flush=True) # force reconfig in case only that self.refresh_client() job = super().submit(*args, api_name=api_name, fn_index=fn_index) if exception_handling: # for debugging if causes issues # see if immediately failed e = check_job(job, timeout=0.01, raise_exception=False) 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 = check_job(job, timeout=0.1, raise_exception=False) 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 def question(self, instruction, *args, **kwargs) -> str: """ Prompt LLM (direct to LLM with instruct prompting required for instruct models) and get response """ kwargs["instruction"] = kwargs.get("instruction", instruction) kwargs["langchain_action"] = LangChainAction.QUERY.value kwargs["langchain_mode"] = 'LLM' ret = '' for response, texts_out in self.query_or_summarize_or_extract(*args, **kwargs): ret = response return ret def question_stream(self, instruction, *args, **kwargs) -> str: """ Prompt LLM (direct to LLM with instruct prompting required for instruct models) and get response """ kwargs["instruction"] = kwargs.get("instruction", instruction) kwargs["langchain_action"] = LangChainAction.QUERY.value kwargs["langchain_mode"] = 'LLM' ret = yield from self.query_or_summarize_or_extract(*args, **kwargs) return ret def query(self, query, *args, **kwargs) -> str: """ Search for documents matching a query, then ask that query to LLM with those documents """ kwargs["instruction"] = kwargs.get("instruction", query) kwargs["langchain_action"] = LangChainAction.QUERY.value ret = '' for response, texts_out in self.query_or_summarize_or_extract(*args, **kwargs): ret = response return ret def query_stream(self, query, *args, **kwargs) -> Generator[tuple[str | list[str], list[str]], None, None]: """ Search for documents matching a query, then ask that query to LLM with those documents """ kwargs["instruction"] = kwargs.get("instruction", query) kwargs["langchain_action"] = LangChainAction.QUERY.value ret = yield from self.query_or_summarize_or_extract(*args, **kwargs) return ret def summarize(self, *args, query=None, focus=None, **kwargs) -> str: """ Search for documents matching a focus, then ask a query to LLM with those documents If focus "" or None, no similarity search is done and all documents (up to top_k_docs) are used """ kwargs["prompt_summary"] = kwargs.get("prompt_summary", query or prompt_summary0) kwargs["instruction"] = kwargs.get('instruction', focus) kwargs["langchain_action"] = LangChainAction.SUMMARIZE_MAP.value ret = '' for response, texts_out in self.query_or_summarize_or_extract(*args, **kwargs): ret = response return ret def summarize_stream(self, *args, query=None, focus=None, **kwargs) -> str: """ Search for documents matching a focus, then ask a query to LLM with those documents If focus "" or None, no similarity search is done and all documents (up to top_k_docs) are used """ kwargs["prompt_summary"] = kwargs.get("prompt_summary", query or prompt_summary0) kwargs["instruction"] = kwargs.get('instruction', focus) kwargs["langchain_action"] = LangChainAction.SUMMARIZE_MAP.value ret = yield from self.query_or_summarize_or_extract(*args, **kwargs) return ret def extract(self, *args, query=None, focus=None, **kwargs) -> list[str]: """ Search for documents matching a focus, then ask a query to LLM with those documents If focus "" or None, no similarity search is done and all documents (up to top_k_docs) are used """ kwargs["prompt_extraction"] = kwargs.get("prompt_extraction", query or prompt_extraction0) kwargs["instruction"] = kwargs.get('instruction', focus) kwargs["langchain_action"] = LangChainAction.EXTRACT.value ret = '' for response, texts_out in self.query_or_summarize_or_extract(*args, **kwargs): ret = response return ret def extract_stream(self, *args, query=None, focus=None, **kwargs) -> list[str]: """ Search for documents matching a focus, then ask a query to LLM with those documents If focus "" or None, no similarity search is done and all documents (up to top_k_docs) are used """ kwargs["prompt_extraction"] = kwargs.get("prompt_extraction", query or prompt_extraction0) kwargs["instruction"] = kwargs.get('instruction', focus) kwargs["langchain_action"] = LangChainAction.EXTRACT.value ret = yield from self.query_or_summarize_or_extract(*args, **kwargs) return ret def query_or_summarize_or_extract(self, h2ogpt_key: str = None, instruction: str = "", text: list[str] | str | None = None, file: list[str] | str | None = None, url: list[str] | str | None = None, embed: bool = True, chunk: bool = True, chunk_size: int = 512, langchain_mode: str = None, langchain_action: str | None = None, langchain_agents: List[str] = [], top_k_docs: int = 10, document_choice: Union[str, List[str]] = "All", document_subset: str = "Relevant", document_source_substrings: Union[str, List[str]] = [], document_source_substrings_op: str = 'and', document_content_substrings: Union[str, List[str]] = [], document_content_substrings_op: str = 'and', system_prompt: str | None = '', pre_prompt_query: str | None = pre_prompt_query0, prompt_query: str | None = prompt_query0, pre_prompt_summary: str | None = pre_prompt_summary0, prompt_summary: str | None = prompt_summary0, pre_prompt_extraction: str | None = pre_prompt_extraction0, prompt_extraction: str | None = prompt_extraction0, hyde_llm_prompt: str | None = hyde_llm_prompt0, model: str | int | None = None, stream_output: bool = False, do_sample: bool = False, temperature: float = 0.0, top_p: float = 0.75, top_k: int = 40, repetition_penalty: float = 1.07, penalty_alpha: float = 0.0, max_time: int = 360, max_new_tokens: int = 1024, add_search_to_context: bool = False, chat_conversation: list[tuple[str, str]] | None = None, text_context_list: list[str] | None = None, docs_ordering_type: str | None = None, min_max_new_tokens: int = 512, max_input_tokens: int = -1, max_total_input_tokens: int = -1, docs_token_handling: str = "split_or_merge", docs_joiner: str = "\n\n", hyde_level: int = 0, hyde_template: str = None, hyde_show_only_final: bool = True, doc_json_mode: bool = False, metadata_in_context: list = [], asserts: bool = False, ) -> Generator[tuple[str | list[str], list[str]], None, None]: """ Query or Summarize or Extract using h2oGPT Args: instruction: Query for LLM chat. Used for similarity search For query, prompt template is: "{pre_prompt_query} \"\"\" {content} \"\"\" {prompt_query}{instruction}" If added to summarization, prompt template is "{pre_prompt_summary} \"\"\" {content} \"\"\" Focusing on {instruction}, {prompt_summary}" text: textual content or list of such contents file: a local file to upload or files to upload url: a url to give or urls to use embed: whether to embed content uploaded langchain_mode: "LLM" to talk to LLM with no docs, "MyData" for personal docs, "UserData" for shared docs, etc. langchain_action: Action to take, "Query" or "Summarize" or "Extract" langchain_agents: Which agents to use, if any top_k_docs: number of document parts. When doing query, number of chunks When doing summarization, not related to vectorDB chunks that are not used E.g. if PDF, then number of pages chunk: whether to chunk sources for document Q/A chunk_size: Size in characters of chunks document_choice: Which documents ("All" means all) -- need to use upload_api API call to get server's name if want to select document_subset: Type of query, see src/gen.py document_source_substrings: See gen.py document_source_substrings_op: See gen.py document_content_substrings: See gen.py document_content_substrings_op: See gen.py system_prompt: pass system prompt to models that support it. If 'auto' or None, then use automatic version If '', then use no system prompt (default) pre_prompt_query: Prompt that comes before document part prompt_query: Prompt that comes after document part pre_prompt_summary: Prompt that comes before document part None makes h2oGPT internally use its defaults E.g. "In order to write a concise single-paragraph or bulleted list summary, pay attention to the following text" prompt_summary: Prompt that comes after document part None makes h2oGPT internally use its defaults E.g. "Using only the text above, write a condensed and concise summary of key results (preferably as bullet points):\n" i.e. for some internal document part fstring, the template looks like: template = "%s \"\"\" %s \"\"\" %s" % (pre_prompt_summary, fstring, prompt_summary) hyde_llm_prompt: hyde prompt for first step when using LLM h2ogpt_key: Access Key to h2oGPT server (if not already set in client at init time) model: base_model name or integer index of model_lock on h2oGPT server None results in use of first (0th index) model in server to get list of models do client.list_models() pre_prompt_extraction: Same as pre_prompt_summary but for when doing extraction prompt_extraction: Same as prompt_summary but for when doing extraction do_sample: see src/gen.py temperature: see src/gen.py top_p: see src/gen.py top_k: see src/gen.py repetition_penalty: see src/gen.py penalty_alpha: see src/gen.py max_new_tokens: see src/gen.py min_max_new_tokens: see src/gen.py max_input_tokens: see src/gen.py max_total_input_tokens: see src/gen.py stream_output: Whether to stream output do_sample: whether to sample max_time: how long to take add_search_to_context: Whether to do web search and add results to context chat_conversation: List of tuples for (human, bot) conversation that will be pre-appended to an (instruction, None) case for a query 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. docs_ordering_type: By default uses 'reverse_ucurve_sort' for optimal retrieval max_input_tokens: Max input tokens to place into model context for each LLM call -1 means auto, fully fill context for query, and fill by original document chunk for summarization >=0 means use that to limit context filling to that many tokens max_total_input_tokens: like max_input_tokens but instead of per LLM call, applies across all LLM calls for single summarization/extraction action max_new_tokens: Maximum new tokens min_max_new_tokens: minimum value for max_new_tokens when auto-adjusting for content of prompt, docs, etc. docs_token_handling: 'chunk' means fill context with top_k_docs (limited by max_input_tokens or model_max_len) chunks for query or top_k_docs original document chunks summarization None or 'split_or_merge' means same as 'chunk' for query, while for summarization merges documents to fill up to max_input_tokens or model_max_len tokens docs_joiner: string to join lists of text when doing split_or_merge. None means '\n\n' hyde_level: 0-3 for HYDE. 0 uses just query to find similarity with docs 1 uses query + pure LLM response to find similarity with docs 2: uses query + LLM response using docs to find similarity with docs 3+: etc. hyde_template: see src/gen.py hyde_show_only_final: see src/gen.py doc_json_mode: see src/gen.py metadata_in_context: see src/gen.py asserts: whether to do asserts to ensure handling is correct Returns: summary/answer: str or extraction List[str] """ if self.config is None: self.setup() if self.persist: client = self else: client = self.clone() h2ogpt_key = h2ogpt_key or self.h2ogpt_key client.h2ogpt_key = h2ogpt_key self.check_model(model) # chunking not used here # MyData specifies scratch space, only persisted for this individual client call langchain_mode = langchain_mode or "MyData" loaders = tuple([None, None, None, None, None, None]) doc_options = tuple([langchain_mode, chunk, chunk_size, embed]) asserts |= bool(os.getenv("HARD_ASSERTS", False)) if ( text and isinstance(text, list) and not file and not url and not text_context_list ): # then can do optimized text-only path text_context_list = text text = None res = [] if text: t0 = time.time() res = client.predict( text, *doc_options, *loaders, h2ogpt_key, api_name="/add_text" ) t1 = time.time() print("upload text: %s" % str(timedelta(seconds=t1 - t0)), flush=True) if asserts: assert res[0] is None assert res[1] == langchain_mode assert "user_paste" in res[2] assert res[3] == "" if file: # upload file(s). Can be list or single file # after below call, "file" replaced with remote location of file _, file = client.predict(file, api_name="/upload_api") res = client.predict( file, *doc_options, *loaders, h2ogpt_key, api_name="/add_file_api" ) if asserts: assert res[0] is None assert res[1] == langchain_mode assert os.path.basename(file) in res[2] assert res[3] == "" if url: res = client.predict( url, *doc_options, *loaders, h2ogpt_key, api_name="/add_url" ) if asserts: assert res[0] is None assert res[1] == langchain_mode assert url in res[2] assert res[3] == "" assert res[4] # should have file name or something similar if res and not res[4] and "Exception" in res[2]: print("Exception: %s" % res[2], flush=True) # ask for summary, need to use same client if using MyData api_name = "/submit_nochat_api" # NOTE: like submit_nochat but stable API for string dict passing pre_prompt_summary = pre_prompt_summary \ if langchain_action == LangChainAction.SUMMARIZE_MAP.value \ else pre_prompt_extraction prompt_summary = prompt_summary \ if langchain_action == LangChainAction.SUMMARIZE_MAP.value \ else prompt_extraction kwargs = dict( h2ogpt_key=h2ogpt_key, instruction=instruction, langchain_mode=langchain_mode, langchain_action=langchain_action, # uses full document, not vectorDB chunks langchain_agents=langchain_agents, top_k_docs=top_k_docs, document_choice=document_choice, document_subset=document_subset, document_source_substrings=document_source_substrings, document_source_substrings_op=document_source_substrings_op, document_content_substrings=document_content_substrings, document_content_substrings_op=document_content_substrings_op, system_prompt=system_prompt, pre_prompt_query=pre_prompt_query, prompt_query=prompt_query, pre_prompt_summary=pre_prompt_summary, prompt_summary=prompt_summary, hyde_llm_prompt=hyde_llm_prompt, visible_models=model, stream_output=stream_output, do_sample=do_sample, temperature=temperature, top_p=top_p, top_k=top_k, repetition_penalty=repetition_penalty, penalty_alpha=penalty_alpha, max_time=max_time, max_new_tokens=max_new_tokens, add_search_to_context=add_search_to_context, chat_conversation=chat_conversation if chat_conversation else self.chat_conversation, text_context_list=text_context_list, docs_ordering_type=docs_ordering_type, min_max_new_tokens=min_max_new_tokens, max_input_tokens=max_input_tokens, max_total_input_tokens=max_total_input_tokens, docs_token_handling=docs_token_handling, docs_joiner=docs_joiner, hyde_level=hyde_level, hyde_template=hyde_template, hyde_show_only_final=hyde_show_only_final, doc_json_mode=doc_json_mode, metadata_in_context=metadata_in_context, ) # in case server changed, update in case clone() self.server_hash = client.server_hash # ensure can fill conversation self.chat_conversation.append((instruction, None)) # get result trials = 3 for trial in range(trials): try: if not stream_output: res = client.predict( str(dict(kwargs)), api_name=api_name, ) # in case server changed, update in case clone() self.server_hash = client.server_hash res = ast.literal_eval(res) response = res["response"] if langchain_action != LangChainAction.EXTRACT.value: response = response.strip() else: response = [r.strip() for r in ast.literal_eval(response)] sources = res["sources"] scores_out = [x["score"] for x in sources] texts_out = [x["content"] for x in sources] if asserts: if text and not file and not url: assert any( text[:cutoff] == texts_out for cutoff in range(len(text)) ) assert len(texts_out) == len(scores_out) yield response, texts_out self.chat_conversation[-1] = (instruction, response) else: job = client.submit(str(dict(kwargs)), api_name=api_name) text0 = "" response = "" texts_out = [] while not job.done(): e = check_job(job, timeout=0, raise_exception=False) if e is not None: break outputs_list = job.outputs().copy() if outputs_list: res = outputs_list[-1] res_dict = ast.literal_eval(res) response = res_dict["response"] # keeps growing text_chunk = response[len(text0):] # only keep new stuff if not text_chunk: time.sleep(0.001) continue text0 = response assert text_chunk, "must yield non-empty string" yield text_chunk, texts_out time.sleep(0.01) # Get final response (if anything left), but also get the actual references (texts_out), above is empty. res_all = job.outputs().copy() success = job.communicator.job.latest_status.success timeout = 0.1 if success else 10 if len(res_all) > 0: check_job(job, timeout=timeout, raise_exception=True) res = res_all[-1] res_dict = ast.literal_eval(res) response = res_dict["response"] sources = res_dict["sources"] texts_out = [x["content"] for x in sources] yield response[len(text0):], texts_out self.chat_conversation[-1] = (instruction, response[len(text0):]) else: check_job(job, timeout=2.0 * timeout, raise_exception=True) yield response[len(text0):], texts_out self.chat_conversation[-1] = (instruction, response[len(text0):]) break except Exception as e: print( "h2oGPT predict failed: %s %s" % (str(e), "".join(traceback.format_tb(e.__traceback__))), flush=True, ) if trial == trials - 1: raise else: print("trying again: %s" % trial, flush=True) time.sleep(1 * trial) finally: # in case server changed, update in case clone() self.server_hash = client.server_hash def check_model(self, model): if model != 0 and self.check_model_name: valid_llms = self.list_models() if ( isinstance(model, int) and model >= len(valid_llms) or isinstance(model, str) and model not in valid_llms ): did_you_mean = "" if isinstance(model, str): alt = difflib.get_close_matches(model, valid_llms, 1) if alt: did_you_mean = f"\nDid you mean {repr(alt[0])}?" raise RuntimeError( f"Invalid llm: {repr(model)}, must be either an integer between " f"0 and {len(valid_llms) - 1} or one of the following values: {valid_llms}.{did_you_mean}" ) def get_models_full(self) -> list[dict[str, Any]]: """ Full model info in list if dict """ if self.config is None: self.setup() return ast.literal_eval(self.predict(api_name="/model_names")) def list_models(self) -> list[str]: """ Model names available from endpoint """ if self.config is None: self.setup() return [x['base_model'] for x in ast.literal_eval(self.predict(api_name="/model_names"))] def simple_stream(self, client_kwargs={}, api_name='/submit_nochat_api', prompt='', prompter=None, sanitize_bot_response=False, max_time=None, is_public=False, raise_exception=True, verbose=False, ): job = self.submit(str(dict(client_kwargs)), api_name=api_name) sources = [] res_dict = dict(response='', sources=sources, save_dict={}, llm_answers={}, response_no_refs='', sources_str='', prompt_raw='') yield res_dict text = '' text0 = '' strex = '' tgen0 = time.time() while not job.done(): e = check_job(job, timeout=0, raise_exception=False) if e is not None: break outputs_list = job.outputs().copy() if outputs_list: res = outputs_list[-1] res_dict = ast.literal_eval(res) text = res_dict['response'] 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: # just need some sleep for threads to switch time.sleep(0.001) continue # save old text0 = response yield dict(response=response, sources=sources, save_dict={}, llm_answers={}, response_no_refs=response, sources_str='', prompt_raw='') if time.time() - tgen0 > max_time: if verbose: print("Took too long for Gradio: %s" % (time.time() - tgen0), flush=True) break time.sleep(0.01) # ensure get last output to avoid race res_all = job.outputs().copy() success = job.communicator.job.latest_status.success timeout = 0.1 if success else 10 if len(res_all) > 0: # don't raise unless nochat API for now e = check_job(job, timeout=timeout, raise_exception=True) if e is not None: strex = ''.join(traceback.format_tb(e.__traceback__)) res = res_all[-1] res_dict = ast.literal_eval(res) text = res_dict['response'] sources = res_dict.get('sources') if sources is None: # then communication terminated, keep what have, but send error if is_public: raise ValueError("Abrupt termination of communication") else: raise ValueError("Abrupt termination of communication: %s" % strex) else: # if got no answer at all, probably something bad, always raise exception # UI will still put exception in Chat History under chat exceptions e = check_job(job, timeout=2.0 * timeout, raise_exception=True) # go with old text if last call didn't work 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" % (res_all, prompt, text, stre, strex), flush=True) prompt_and_text = prompt + text response = prompter.get_response(prompt_and_text, prompt=prompt, sanitize_bot_response=sanitize_bot_response) res_dict = dict(response=response, sources=sources, save_dict={}, error=strex, llm_answers={}, response_no_refs=response, sources_str='', prompt_raw='') yield res_dict return res_dict def stream(self, client_kwargs={}, api_name='/submit_nochat_api', prompt='', prompter=None, sanitize_bot_response=False, max_time=None, is_public=False, raise_exception=True, verbose=False, ): strex = '' e = None res_dict = {} try: res_dict = yield from self._stream(client_kwargs, api_name=api_name, prompt=prompt, prompter=prompter, sanitize_bot_response=sanitize_bot_response, max_time=max_time, verbose=verbose) except Exception as e: strex = ''.join(traceback.format_tb(e.__traceback__)) # check validity of final results and check for timeout # NOTE: server may have more before its timeout, and res_all will have more if waited a bit if raise_exception: raise if 'timeout' in res_dict['save_dict']['extra_dict']: timeout_time = res_dict['save_dict']['extra_dict']['timeout'] raise TimeoutError("Timeout from local after %s %s" % (timeout_time, ': ' + strex if e else '')) # won't have sources if timed out if res_dict.get('sources') is None: # then communication terminated, keep what have, but send error if is_public: raise ValueError("Abrupt termination of communication") else: raise ValueError("Abrupt termination of communication: %s" % strex) return res_dict def _stream(self, client_kwargs, api_name='/submit_nochat_api', prompt='', prompter=None, sanitize_bot_response=False, max_time=None, verbose=False): job = self.submit(str(dict(client_kwargs)), api_name=api_name) text = '' sources = [] save_dict = {} save_dict['extra_dict'] = {} res_dict = dict(response=text, sources=sources, save_dict=save_dict, llm_answers={}, response_no_refs=text, sources_str='', prompt_raw='') yield res_dict text0 = '' tgen0 = time.time() n = 0 for res in job: res_dict, text0 = yield from self.yield_res(res, res_dict, prompt, prompter, sanitize_bot_response, max_time, text0, tgen0, verbose) n += 1 if 'timeout' in res_dict['save_dict']['extra_dict']: break # final res outputs = job.outputs().copy() all_n = len(outputs) for nn in range(n, all_n): res = outputs[nn] res_dict, text0 = yield from self.yield_res(res, res_dict, prompt, prompter, sanitize_bot_response, max_time, text0, tgen0, verbose) return res_dict def yield_res(res, res_dict, prompt, prompter, sanitize_bot_response, max_time, text0, tgen0, verbose): do_yield = True res_dict_server = ast.literal_eval(res) # yield what have text = res_dict_server['response'] if prompter: response = prompter.get_response(prompt + text, prompt=prompt, sanitize_bot_response=sanitize_bot_response) else: response = text text_chunk = response[len(text0):] if not text_chunk: # just need some sleep for threads to switch time.sleep(0.001) do_yield = False # save old text0 = response res_dict.update(res_dict_server) res_dict.update(dict(response=response, response_no_refs=response)) timeout_time_other = res_dict.get('save_dict', {}).get('extra_dict', {}).get('timeout') if timeout_time_other: if verbose: print("Took too long for other Gradio: %s" % (time.time() - tgen0), flush=True) return res_dict, text0 timeout_time = time.time() - tgen0 if max_time is not None and timeout_time > max_time: if 'save_dict' not in res_dict: res_dict['save_dict'] = {} if 'extra_dict' not in res_dict['save_dict']: res_dict['save_dict']['extra_dict'] = {} res_dict['save_dict']['extra_dict']['timeout'] = timeout_time yield res_dict if verbose: print("Took too long for Gradio: %s" % (time.time() - tgen0), flush=True) return res_dict, text0 if do_yield: yield res_dict time.sleep(0.01) return res_dict, text0 def make_image(prompt, filename=None, gpu_id='auto', pipe=None): if pipe is None: pipe = get_pipe_make_image(gpu_id=gpu_id) lock_type = 'image' base_path = os.path.join('locks', 'image_locks') 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 with filelock.FileLock(lock_file): image = pipe(prompt=prompt, num_inference_steps=1, guidance_scale=0.0).images[0] if filename: image.save(filename) return filename return image def make_image(prompt, filename=None, gpu_id='auto', pipe=None, guidance_scale=3.0): if pipe is None: base, refiner = get_pipe_make_image(gpu_id=gpu_id) else: base, refiner = pipe lock_type = 'image' base_path = os.path.join('locks', 'image_locks') 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 with filelock.FileLock(lock_file): # Define how many steps and what % of steps to be run on each experts (80/20) here n_steps = 40 high_noise_frac = 0.8 # run both experts image = base( prompt=prompt, num_inference_steps=n_steps, denoising_end=high_noise_frac, output_type="latent", ).images image = refiner( prompt=prompt, num_inference_steps=n_steps, denoising_start=high_noise_frac, image=image, ).images[0] if filename: image.save(filename) return filename return image def make_image(prompt, filename=None, gpu_id='auto', pipe=None, guidance_scale=3.0): if pipe is None: pipe = get_pipe_make_image(gpu_id=gpu_id) lock_type = 'image' base_path = os.path.join('locks', 'image_locks') 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 with filelock.FileLock(lock_file): image = pipe(prompt=prompt, guidance_scale=guidance_scale).images[0] if filename: image.save(filename) return filename return image 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['hyde_show_intermediate_in_accordion'] = kwargs.get('hyde_show_intermediate_in_accordion', 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 kwargs['exllama_dict'] = {} # shouldn't be required unless from test using _run_qa_db kwargs['gptq_dict'] = {} # shouldn't be required unless from test using _run_qa_db kwargs['sink_dict'] = {} # shouldn't be required unless from test using _run_qa_db kwargs['hf_model_dict'] = {} # shouldn't be required unless from test using _run_qa_db kwargs['image_file'] = kwargs.get('image_file') kwargs['image_control'] = kwargs.get('image_control') kwargs['load_awq'] = kwargs.get('load_awq', '') 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: if kwargs.get('cli', False): clear_torch_cache(allow_skip=True) def get_any_db(db1s, langchain_mode, langchain_mode_paths, langchain_mode_types, dbs=None, load_db_if_exists=None, db_type=None, use_openai_embedding=None, hf_embedding_model=None, migrate_embedding_model=None, auto_migrate_db=None, for_sources_list=False, verbose=False, n_jobs=-1, ): if langchain_mode in [LangChainMode.DISABLED.value, LangChainMode.LLM.value]: return None elif for_sources_list and langchain_mode in [LangChainMode.WIKI_FULL.value]: # NOTE: avoid showing full wiki. Takes about 30 seconds over about 90k entries, but not useful for now return None elif langchain_mode in db1s and len(db1s[langchain_mode]) > 1 and db1s[langchain_mode][0]: return db1s[langchain_mode][0] elif dbs is not None and langchain_mode in dbs and dbs[langchain_mode] is not None: return dbs[langchain_mode] else: db = None if db is None: langchain_type = langchain_mode_types.get(langchain_mode, LangChainTypes.EITHER.value) persist_directory, langchain_type = get_persist_directory(langchain_mode, db1s=db1s, dbs=dbs, langchain_type=langchain_type) langchain_mode_types[langchain_mode] = langchain_type # see if actually have on disk, don't try to switch embedding yet, since can't use return here migrate_embedding_model = False db, _, _ = \ 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 is not None: # if found db, then stuff into state, so don't have to reload again that takes time if langchain_type == LangChainTypes.PERSONAL.value: assert isinstance(db1s, dict), "db1s wrong type: %s" % type(db1s) db1 = db1s[langchain_mode] = [db, None, None] assert len(db1) == length_db1(), "Bad setup: %s" % len(db1) set_dbid(db1) else: assert isinstance(dbs, dict), "dbs wrong type: %s" % type(dbs) dbs[langchain_mode] = db return db def img_to_base64(image_file): # assert image_file.lower().endswith('jpg') or image_file.lower().endswith('jpeg') from PIL import Image EXTENSIONS = {'.png': 'PNG', '.apng': 'PNG', '.blp': 'BLP', '.bmp': 'BMP', '.dib': 'DIB', '.bufr': 'BUFR', '.cur': 'CUR', '.pcx': 'PCX', '.dcx': 'DCX', '.dds': 'DDS', '.ps': 'EPS', '.eps': 'EPS', '.fit': 'FITS', '.fits': 'FITS', '.fli': 'FLI', '.flc': 'FLI', '.fpx': 'FPX', '.ftc': 'FTEX', '.ftu': 'FTEX', '.gbr': 'GBR', '.gif': 'GIF', '.grib': 'GRIB', '.h5': 'HDF5', '.hdf': 'HDF5', '.jp2': 'JPEG2000', '.j2k': 'JPEG2000', '.jpc': 'JPEG2000', '.jpf': 'JPEG2000', '.jpx': 'JPEG2000', '.j2c': 'JPEG2000', '.icns': 'ICNS', '.ico': 'ICO', '.im': 'IM', '.iim': 'IPTC', '.jfif': 'JPEG', '.jpe': 'JPEG', '.jpg': 'JPEG', '.jpeg': 'JPEG', '.tif': 'TIFF', '.tiff': 'TIFF', '.mic': 'MIC', '.mpg': 'MPEG', '.mpeg': 'MPEG', '.mpo': 'MPO', '.msp': 'MSP', '.palm': 'PALM', '.pcd': 'PCD', '.pdf': 'PDF', '.pxr': 'PIXAR', '.pbm': 'PPM', '.pgm': 'PPM', '.ppm': 'PPM', '.pnm': 'PPM', '.psd': 'PSD', '.qoi': 'QOI', '.bw': 'SGI', '.rgb': 'SGI', '.rgba': 'SGI', '.sgi': 'SGI', '.ras': 'SUN', '.tga': 'TGA', '.icb': 'TGA', '.vda': 'TGA', '.vst': 'TGA', '.webp': 'WEBP', '.wmf': 'WMF', '.emf': 'WMF', '.xbm': 'XBM', '.xpm': 'XPM'} from pathlib import Path ext = Path(image_file).suffix if ext in EXTENSIONS: iformat = EXTENSIONS[ext] else: raise ValueError("Invalid file extension %s for file %s" % (ext, image_file)) image = Image.open(image_file) buffered = BytesIO() image.save(buffered, format=iformat) img_str = base64.b64encode(buffered.getvalue()) # FIXME: unsure about below img_str = str(bytes("data:image/%s;base64," % iformat.lower(), encoding='utf-8') + img_str) return img_str def get_llava_response(file=None, llava_model=None, prompt=None, chat_conversation=[], allow_prompt_auto=False, image_model='llava-v1.6-vicuna-13b', temperature=0.2, top_p=0.7, max_new_tokens=512, image_process_mode="Default", include_image=False, client=None, max_time=None, force_stream=True, ): kwargs = locals() if force_stream: text = '' for res in get_llava_stream(**kwargs): text = res return text, prompt prompt = fix_llava_prompt(file, prompt, allow_prompt_auto=allow_prompt_auto) image_model, client, file = \ llava_prep(file, llava_model, image_model=image_model, client=client) res = client.predict(prompt, chat_conversation, file, image_process_mode, include_image, image_model, temperature, top_p, max_new_tokens, api_name='/textbox_api_submit') res = res[-1][-1] return res, prompt def get_llava_stream(file, llava_model, prompt=None, chat_conversation=[], allow_prompt_auto=False, image_model='llava-v1.6-vicuna-13b', temperature=0.2, top_p=0.7, max_new_tokens=512, image_process_mode="Default", include_image=False, client=None, verbose_level=0, max_time=None, force_stream=True, # dummy arg ): image_model = os.path.basename(image_model) # in case passed HF link prompt = fix_llava_prompt(file, prompt, allow_prompt_auto=allow_prompt_auto) image_model, client, file = \ llava_prep(file, llava_model, image_model=image_model, client=client) job = client.submit(prompt, chat_conversation, file, image_process_mode, include_image, image_model, temperature, top_p, max_new_tokens, api_name='/textbox_api_submit') t0 = time.time() job_outputs_num = 0 text = '' while not job.done(): if verbose_level == 2: print("Inside: %s" % llava_model, time.time() - t0, flush=True) if max_time is not None and time.time() - t0 > max_time: return text outputs_list = job.outputs().copy() job_outputs_num_new = len(outputs_list[job_outputs_num:]) for num in range(job_outputs_num_new): res = outputs_list[job_outputs_num + num] if verbose_level == 2: print('Stream %d: %s' % (num, res), flush=True) elif verbose_level == 1: print('Stream %d' % (job_outputs_num + num), flush=True) if res and len(res[0]) > 0: text = res[-1][-1] yield text job_outputs_num += job_outputs_num_new time.sleep(0.01) outputs_list = job.outputs().copy() job_outputs_num_new = len(outputs_list[job_outputs_num:]) for num in range(job_outputs_num_new): if max_time is not None and time.time() - t0 > max_time: return text res = outputs_list[job_outputs_num + num] if verbose_level == 2: print('Final Stream %d: %s' % (num, res), flush=True) elif verbose_level == 1: print('Final Stream %d' % (job_outputs_num + num), flush=True) if res and len(res[0]) > 0: text = res[-1][-1] yield text job_outputs_num += job_outputs_num_new if verbose_level == 1: print("total job_outputs_num=%d" % job_outputs_num, flush=True) return text def evaluate( model_state, my_db_state, selection_docs_state, requests_state, roles_state, # START NOTE: Examples must have same order of parameters instruction, iinput, context, stream_output, prompt_type, prompt_dict, temperature, top_p, top_k, penalty_alpha, 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, document_source_substrings, document_source_substrings_op, document_content_substrings, document_content_substrings_op, pre_prompt_query, prompt_query, pre_prompt_summary, prompt_summary, hyde_llm_prompt, system_prompt, image_audio_loaders, pdf_loaders, url_loaders, jq_schema, extract_frames, llava_prompt, visible_models, h2ogpt_key, add_search_to_context, chat_conversation, text_context_list, docs_ordering_type, min_max_new_tokens, max_input_tokens, max_total_input_tokens, docs_token_handling, docs_joiner, hyde_level, hyde_template, hyde_show_only_final, doc_json_mode, metadata_in_context, chatbot_role, speaker, tts_language, tts_speed, image_file, image_control, # END NOTE: Examples must have same order of parameters captions_model=None, caption_loader=None, doctr_loader=None, pix2struct_loader=None, llava_model=None, image_gen_loader=None, image_gen_loader_high=None, image_change_loader=None, enable_imagegen_high_sd=None, asr_model=None, asr_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, from_ui=True, regenerate_clients=None, regenerate_gradio_clients=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, hyde_show_intermediate_in_accordion=None, top_k_docs_max_show=None, show_link_in_sources=None, langchain_instruct_mode=None, verbose=False, gradio=True, 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, llamacpp_path=None, llamacpp_dict=None, exllama_dict=None, gptq_dict=None, attention_sinks=None, sink_dict=None, truncation_generation=None, hf_model_dict=None, load_exllama=None, answer_with_sources=None, append_sources_to_answer=None, append_sources_to_chat=None, image_audio_loaders_options0=None, pdf_loaders_options0=None, url_loaders_options0=None, jq_schema0=None, extract_frames0=None, keep_sources_in_context=None, gradio_errors_to_chatbot=None, allow_chat_system_prompt=None, # carry defaults to know what forced-off means use_pymupdf=None, use_unstructured_pdf=None, use_pypdf=None, enable_pdf_ocr=None, enable_pdf_doctr=None, try_pdf_as_html=None, load_awq=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_audio_loaders is None: image_audio_loaders = image_audio_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 extract_frames is None: extract_frames = extract_frames0 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) if langchain_action in [LangChainAction.IMAGE_GENERATE.value, LangChainAction.IMAGE_GENERATE_HIGH.value]: t_generate = time.time() if langchain_action in [LangChainAction.IMAGE_GENERATE.value]: assert image_gen_loader, "Generating image, but image_gen_loader is None" from src.vision.sdxl import make_image pipe = image_gen_loader elif langchain_action in [LangChainAction.IMAGE_GENERATE_HIGH.value]: assert image_gen_loader_high, "Generating image, but image_gen_loader_high is None" if enable_imagegen_high_sd: from src.vision.stable_diffusion_xl import make_image else: from src.vision.playv2 import make_image pipe = image_gen_loader_high else: raise ValueError("No such langchain_action=%s" % langchain_action) filename_image = sanitize_filename("image_%s_%s.png" % (instruction, str(uuid.uuid4())), file_length_limit=50) gradio_tmp = get_gradio_tmp() image_file_gen = make_image(instruction, filename=os.path.join(gradio_tmp, filename_image), pipe=pipe, ) response = (image_file_gen,) # FIXME: Could run this through image model if was selected extra_dict = dict(t_generate=time.time() - t_generate, instruction=instruction, prompt_raw=instruction, prompt_type=prompt_type, base_model=LangChainAction.IMAGE_GENERATE.value) save_dict = dict(prompt=instruction, output=response, extra_dict=extra_dict) yield dict(response=response, sources=[], save_dict=save_dict, llm_answers={}, response_no_refs="Generated image for %s" % instruction, sources_str="", prompt_raw=instruction) return 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] no_llm_ok = langchain_action in [LangChainAction.IMAGE_GENERATE.value, LangChainAction.IMAGE_GENERATE_HIGH.value, LangChainAction.IMAGE_CHANGE.value, ] chosen_model_state = model_state0 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 elif not no_llm_ok: 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 and not no_llm_ok: raise AssertionError(no_model_msg) assert base_model.strip(), no_model_msg assert model is not None, "Model is missing" assert tokenizer is not None, "Tokenizer is missing" # choose chat or non-chat mode if not chat: instruction = instruction_nochat iinput = iinput_nochat # avoid instruction in chat_conversation itself, since always used as additional context to prompt in what follows if isinstance(chat_conversation, list) and \ len(chat_conversation) > 0 and \ len(chat_conversation[-1]) == 2 and \ chat_conversation[-1][0] == instruction and \ chat_conversation[-1][1] in [None, '']: chat_conversation = chat_conversation[:-1] if not add_chat_history_to_context: # make it easy to ignore without needing add_chat_history_to_context # some langchain or unit test may need to then handle more general case chat_conversation = [] # in some cases, like lean nochat API, don't want to force sending prompt_type, allow default choice # This doesn't do switch-a-roo, assume already done, so might be wrong model and can't infer model_lower = base_model.lower() llamacpp_dict = str_to_dict(llamacpp_dict) if not prompt_type and prompt_type != 'custom': prompt_type_trial = model_name_to_prompt_type(base_model, llamacpp_dict=llamacpp_dict) if prompt_type_trial: prompt_type = prompt_type_trial if verbose: print("Auto-selecting prompt_type=%s for %s" % (prompt_type, base_model), 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) penalty_alpha = min(2.0, max(0.0, penalty_alpha)) if temperature == 0.0: # override do_sample = False # Note: Could do below, but for now gradio way can control do_sample directly # elif temperature >= 0.01: # do_sample = True temperature = min(max(0.01, temperature), 2.0) max_input_tokens = int(max_input_tokens) if max_input_tokens is not None else -1 max_total_input_tokens = int(max_total_input_tokens) if max_total_input_tokens is not None else -1 # FIXME: https://github.com/h2oai/h2ogpt/issues/106 num_beams = 1 if stream_output else num_beams # See max_beams in gradio_runner if model_lower == 'distilgpt2': # always truncate for certain models that totally fail otherwise truncation_generation = True max_max_new_tokens = get_max_max_new_tokens(chosen_model_state, memory_restriction_level=memory_restriction_level, max_new_tokens=max_new_tokens, attention_sinks=attention_sinks, max_max_new_tokens=max_max_new_tokens, truncation_generation=truncation_generation) if min_max_new_tokens is None: # default for nochat api min_max_new_tokens = 512 if max_input_tokens is None: max_input_tokens = -1 if max_total_input_tokens is None: max_total_input_tokens = -1 if docs_ordering_type is None: docs_ordering_type = docs_ordering_types_default if docs_token_handling is None: docs_token_handling = docs_token_handling_default if docs_joiner is None: docs_joiner = docs_joiner_default 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, from_ui) # limit total tokens processed, e.g. for summarization, if public instance if is_public: # control API too for public case if from_ui: max_input_tokens = max_input_tokens_public else: max_input_tokens = max_input_tokens_public_api if from_ui: max_total_input_tokens = min(max_total_input_tokens, max_total_input_tokens_public) else: max_total_input_tokens = min(max_total_input_tokens, max_total_input_tokens_public_api) 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 = '' # NOTE!!!!!!!!!! Choice of developer. But only possible to force stream if num_beams=1 # stream if can, so can control task iteration and time of iteration # not required, but helpful for max_time control etc. stream_output0 = stream_output stream_output = gradio and num_beams == 1 # get prompter prompter = Prompter(prompt_type, prompt_dict, debug=debug, 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') or \ inference_server.startswith('anthropic') or \ inference_server.startswith('google') or \ inference_server.startswith('mistralai') 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 gen_hyper_dict = dict(do_sample=do_sample, temperature=temperature, repetition_penalty=repetition_penalty, top_p=top_p, top_k=top_k, penalty_alpha=penalty_alpha, 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, ) extra_dict = gen_hyper_dict.copy() extra_dict.update(dict(base_model=base_model, 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, document_source_substrings=document_source_substrings, document_source_substrings_op=document_source_substrings_op, document_content_substrings=document_content_substrings, document_content_substrings_op=document_content_substrings_op, add_search_to_context=add_search_to_context, instruction=instruction, iinput=iinput, context=context, ntokens=None, tokens_persecond=None, llamacpp_dict=llamacpp_dict, )) save_dict = dict(base_model=base_model, save_dir=save_dir, extra_dict=extra_dict) if do_langchain_path: text = '' sources = [] sources_str = '' response = '' response_no_refs = '' prompt_raw = '' # 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 loaders_dict, captions_model, asr_model = gr_to_lg(image_audio_loaders, pdf_loaders, url_loaders, 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, captions_model=captions_model, asr_model=asr_model, ) loaders_dict.update(dict(captions_model=captions_model, caption_loader=caption_loader, doctr_loader=doctr_loader, pix2struct_loader=pix2struct_loader, llava_model=llava_model, asr_model=asr_model, asr_loader=asr_loader, jq_schema=jq_schema, extract_frames=extract_frames, llava_prompt=llava_prompt, )) 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 llm_answers = {} for r in run_qa_db( inference_server=inference_server, regenerate_clients=regenerate_clients, regenerate_gradio_clients=regenerate_gradio_clients, model_name=base_model, model=model, tokenizer=tokenizer, langchain_only_model=langchain_only_model, load_awq=load_awq, 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, append_sources_to_chat=append_sources_to_chat, 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, gradio_errors_to_chatbot=gradio_errors_to_chatbot, memory_restriction_level=memory_restriction_level, system_prompt=system_prompt, allow_chat_system_prompt=allow_chat_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, hyde_show_intermediate_in_accordion=hyde_show_intermediate_in_accordion, top_k_docs_max_show=top_k_docs_max_show, show_link_in_sources=show_link_in_sources, langchain_instruct_mode=langchain_instruct_mode, # evaluate args items query=instruction, iinput=iinput, context=context, stream_output0=stream_output0, 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, document_source_substrings=document_source_substrings, document_source_substrings_op=document_source_substrings_op, document_content_substrings=document_content_substrings, document_content_substrings_op=document_content_substrings_op, 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, hyde_llm_prompt=hyde_llm_prompt, 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, max_input_tokens=max_input_tokens, max_total_input_tokens=max_total_input_tokens, docs_token_handling=docs_token_handling, docs_joiner=docs_joiner, hyde_level=hyde_level, hyde_template=hyde_template, hyde_show_only_final=hyde_show_only_final, doc_json_mode=doc_json_mode, metadata_in_context=metadata_in_context, **gen_hyper_dict, db_type=db_type, n_jobs=n_jobs, verbose=verbose, cli=cli, sanitize_bot_response=sanitize_bot_response, lora_weights=lora_weights, llamacpp_path=llamacpp_path, llamacpp_dict=llamacpp_dict, exllama_dict=exllama_dict, gptq_dict=gptq_dict, attention_sinks=attention_sinks, sink_dict=sink_dict, truncation_generation=truncation_generation, hf_model_dict=hf_model_dict, auto_reduce_chunks=auto_reduce_chunks, max_chunks=max_chunks, headsize=headsize, image_file=image_file, image_control=image_control, ): # doesn't accumulate, new answer every yield, so only save that full answer response = r['response'] sources = r['sources'] num_prompt_tokens = r['num_prompt_tokens'] llm_answers = r['llm_answers'] response_no_refs = r['response_no_refs'] sources_str = r['sources_str'] prompt_raw = str(r['prompt_raw']) if stream_output: yield dict(response=response, sources=[], save_dict={}, llm_answers=llm_answers, response_no_refs=response_no_refs, sources_str='', prompt_raw='') extra_dict.update(dict(num_prompt_tokens=num_prompt_tokens, t_generate=time.time() - t_generate, # tokens_persecond computed in save_generate_output sources_str=sources_str, sources=sources, )) save_dict.update(dict(prompt=prompt, output=response, where_from="run_qa_db", extra_dict=extra_dict)) yield dict(response=response, sources=sources, save_dict=save_dict, llm_answers=llm_answers, response_no_refs=response_no_refs, sources_str=sources_str, prompt_raw=prompt_raw) 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 from gradio_utils.grclient import GradioClient from gradio_client import Client gradio_server = inference_server.startswith('http') and ( isinstance(model, GradioClient) or isinstance(model, Client)) prompt, \ instruction, iinput, context, \ num_prompt_tokens, max_new_tokens, num_prompt_tokens0, num_prompt_tokens_actual, \ history_to_use_final, external_handle_chat_conversation, \ top_k_docs_trial, one_doc_size, truncation_generation, system_prompt = \ get_limited_prompt(instruction, iinput, tokenizer, prompter=prompter, inference_server=inference_server, # prompt_type=prompt_type, # use prompter # prompt_dict=prompt_dict, # use prompter # chat=chat, # use prompter max_new_tokens=max_new_tokens, # system_prompt=system_prompt, # use prompter allow_chat_system_prompt=allow_chat_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, max_input_tokens=max_input_tokens, max_total_input_tokens=max_total_input_tokens, truncation_generation=truncation_generation, gradio_server=gradio_server, attention_sinks=attention_sinks, hyde_level=hyde_level, gradio_errors_to_chatbot=gradio_errors_to_chatbot, ) if inference_server.startswith('vllm') or \ inference_server.startswith('openai') or \ inference_server.startswith('http'): text = '' gen_server_kwargs = {} 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" if isinstance(model, dict): openai_client, openai_async_client, inf_type = model['client'], model['async_client'], model['inf_type'] else: openai_client, openai_async_client, \ inf_type, _, _, _, _ = set_openai(inference_server, model_name=base_model) where_from = inf_type responses = None 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.001, max_tokens=max_new_tokens_openai, top_p=top_p if do_sample else 1, frequency_penalty=0, seed=SEED, n=num_return_sequences, presence_penalty=(repetition_penalty - 1.0) * 2.0 + 0.0, # so good default ) try: if inf_type == 'vllm' or inf_type == 'openai': if inf_type == 'vllm': vllm_extra_dict = get_vllm_extra_dict(tokenizer, stop_sequences=stop_sequences, # repetition_penalty=repetition_penalty, # could pass ) other_dict = dict(timeout=max_time) else: vllm_extra_dict = {} other_dict = dict(timeout=max_time) responses = openai_client.completions.create( model=base_model, prompt=prompt, **gen_server_kwargs, stop=stop_sequences, **vllm_extra_dict, stream=stream_output, **other_dict, ) 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) else: collected_events = [] tgen0 = time.time() for event in responses: collected_events.append(event) # save the event response delta = event.choices[0].text # extract the text text += delta # append the text if delta: response = prompter.get_response(prompt + text, prompt=prompt, sanitize_bot_response=sanitize_bot_response) yield dict(response=response, sources=sources, save_dict={}, llm_answers={}, response_no_refs=response, sources_str='', prompt_raw='') if time.time() - tgen0 > max_time: if verbose: print("Took too long for OpenAI or VLLM: %s" % (time.time() - tgen0), flush=True) break time.sleep(0.01) elif inf_type == 'vllm_chat' or inf_type == 'openai_chat': other_dict = dict(timeout=max_time) 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}) if chat_conversation and add_chat_history_to_context: assert external_handle_chat_conversation, "Should be handling only externally" # history_to_use_final handles token counting issues for message1 in history_to_use_final: if len(message1) == 2 and (message1[0] is None or message1[1] is None): # then not really part of LLM, internal, so avoid continue if len(message1) == 2: if message1[0]: messages0.append( {'role': 'user', 'content': gradio_to_llm(message1[0], bot=False)}) if message1[1]: messages0.append( {'role': 'assistant', 'content': gradio_to_llm(message1[1], bot=True)}) if prompt: messages0.append({'role': 'user', 'content': prompt}) responses = openai_client.chat.completions.create( model=base_model, messages=messages0, stream=stream_output, **gen_server_kwargs, **other_dict, ) 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) else: tgen0 = time.time() for chunk in responses: delta = chunk.choices[0].delta.content if delta: text += delta response = prompter.get_response(prompt + text, prompt=prompt, sanitize_bot_response=sanitize_bot_response) yield dict(response=response, sources=sources, save_dict={}, llm_answers={}, response_no_refs=response, sources_str='', prompt_raw='') if time.time() - tgen0 > max_time: if verbose: print("Took too long for OpenAI or VLLM Chat: %s" % (time.time() - tgen0), flush=True) break else: raise RuntimeError("No such OpenAI mode: %s" % inference_server) finally: if responses is not None: try: responses.close() except Exception as e: print("Failed to close OpenAI response: %s" % str(e), flush=True) if regenerate_clients and openai_client is not None: try: openai_client.close() except Exception as e: print("Failed to close OpenAI client: %s" % str(e), flush=True) elif inference_server.startswith('http') and is_vision_model(base_model): where_from = "gr_client for llava" sources = [] inference_server, headers = get_hf_server(inference_server) if isinstance(model, GradioClient) and not regenerate_gradio_clients: gr_client = model.clone() elif isinstance(model, Client) and not regenerate_gradio_clients: gr_client = model else: inference_server, gr_client, hf_client = get_client_from_inference_server(inference_server, base_model=base_model) assert gr_client is not None assert hf_client is None # NOTE: llava doesn't handle context or system prompt directly img_file = get_image_file(image_file, image_control, document_choice) llava_kwargs = dict(file=img_file, llava_model=inference_server, # prompt=instruction, prompt=prompt, # prepared prompt with chat history etc. chat_conversation=chat_conversation, allow_prompt_auto=False, image_model=base_model, temperature=temperature, top_p=top_p, max_new_tokens=max_new_tokens, client=gr_client if not regenerate_gradio_clients else None, ) if not stream_output: from src.vision.utils_vision import get_llava_response response, _ = get_llava_response(**llava_kwargs) yield dict(response=response, sources=[], save_dict={}, error='', llm_answers={}, response_no_refs=response, sources_str='', prompt_raw='') else: response = '' tgen0 = time.time() from src.vision.utils_vision import get_llava_stream for response in get_llava_stream(**llava_kwargs): yield dict(response=response, sources=[], save_dict={}, error='', llm_answers={}, response_no_refs=response, sources_str='', prompt_raw='') if time.time() - tgen0 > max_time: if verbose: print("Took too long for TGI: %s" % (time.time() - tgen0), flush=True) break elif inference_server.startswith('http'): inference_server, headers = get_hf_server(inference_server) from text_generation import Client as HFClient if isinstance(model, GradioClient) and not regenerate_gradio_clients: gr_client = model.clone() hf_client = None elif isinstance(model, HFClient) and not regenerate_gradio_clients: gr_client = None hf_client = model else: inference_server, gr_client, hf_client = get_client_from_inference_server(inference_server, base_model=base_model) 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 = chat where_from = "gr_client" client_langchain_mode = 'Disabled' client_add_chat_history_to_context = add_chat_history_to_context 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, penalty_alpha=penalty_alpha, 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 # ensure image in correct format img_file = get_image_file(image_file, image_control, document_choice) if img_file is not None and os.path.isfile(img_file): from src.vision.utils_vision import img_to_base64 img_file = img_to_base64(img_file) elif isinstance(img_file, str): # assume already bytes img_file = img_file else: img_file = None 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, chat_conversation=chat_conversation, text_context_list=text_context_list, chatbot_role=chatbot_role, speaker=speaker, tts_language=tts_language, tts_speed=tts_speed, 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], document_source_substrings=[], document_source_substrings_op='and', document_content_substrings=[], document_content_substrings_op='and', pre_prompt_query=pre_prompt_query, prompt_query=prompt_query, pre_prompt_summary=pre_prompt_summary, prompt_summary=prompt_summary, hyde_llm_prompt=hyde_llm_prompt, system_prompt=system_prompt, image_audio_loaders=image_audio_loaders, pdf_loaders=pdf_loaders, url_loaders=url_loaders, jq_schema=jq_schema, extract_frames=extract_frames, llava_prompt=llava_prompt, visible_models=visible_models, h2ogpt_key=h2ogpt_key, add_search_to_context=client_add_search_to_context, docs_ordering_type=docs_ordering_type, min_max_new_tokens=min_max_new_tokens, max_input_tokens=max_input_tokens, max_total_input_tokens=max_total_input_tokens, docs_token_handling=docs_token_handling, docs_joiner=docs_joiner, hyde_level=hyde_level, hyde_template=hyde_template, hyde_show_only_final=hyde_show_only_final, doc_json_mode=doc_json_mode, metadata_in_context=metadata_in_context, image_file=img_file, image_control=None, # already stuffed into image_file ) assert len(set(list(client_kwargs.keys())).symmetric_difference(eval_func_param_names)) == 0 api_name = '/submit_nochat_api' # NOTE: like submit_nochat but stable API for string dict passing response = '' text = '' sources = [] strex = '' 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) else: new_stream = False # hanging for many chatbots gr_stream_kwargs = dict(client_kwargs=client_kwargs, api_name=api_name, prompt=prompt, prompter=prompter, sanitize_bot_response=sanitize_bot_response, max_time=max_time, is_public=is_public, verbose=verbose) if new_stream: res_dict = yield from gr_client.stream(**gr_stream_kwargs) else: res_dict = yield from gr_client.simple_stream(**gr_stream_kwargs) response = res_dict.get('response', '') elif hf_client: # 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'))) # HF inference server needs control over input tokens where_from = "hf_client" response = '' 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) else: tgen0 = time.time() 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={}, llm_answers={}, response_no_refs=response, sources_str='', prompt_raw='') time.sleep(0.01) if time.time() - tgen0 > max_time: if verbose: print("Took too long for TGI: %s" % (time.time() - tgen0), flush=True) break else: raise RuntimeError("Failed to get client: %s" % inference_server) else: raise RuntimeError("No such inference_server %s" % inference_server) # only return yield with save_dict and prompt_raw here to keep streaming light extra_dict.update(gen_server_kwargs) extra_dict.update(dict(inference_server=inference_server, # changes in some cases num_prompt_tokens=num_prompt_tokens, t_generate=time.time() - t_generate, ntokens=None, prompt_type=prompt_type, tokens_persecond=None, )) save_dict.update(dict(prompt=prompt, output=text, where_from=where_from, extra_dict=extra_dict)) # if not streaming, only place yield should be done yield dict(response=response, sources=sources, save_dict=save_dict, llm_answers={}, response_no_refs=response, sources_str='', prompt_raw=prompt) 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 = [] response = model(prompt, max_length=max_new_tokens)[0][key] yield dict(response=response, sources=sources, save_dict=save_dict, llm_answers={}, response_no_refs=response, sources_str='', prompt_raw=prompt) return 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, truncation_generation=truncation_generation) 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 = int(tokenizer.model_max_length) max_input_tokens_default = max(0, int(max_max_tokens - min_new_tokens)) if max_input_tokens >= 0: max_input_tokens = min(max_input_tokens_default, max_input_tokens) else: max_input_tokens = max_input_tokens_default # 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 if attention_sinks: assert use_cache, "attention sinks requires use_cache=True" bad_word_ids = [tokenizer.eos_token_id] 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, max_new_tokens=max_new_tokens, # unsure if required here ) if do_sample: gen_config_kwargs.update(dict(temperature=float(temperature), top_p=float(top_p), top_k=top_k)) if penalty_alpha > 0: gen_config_kwargs.update(dict(penalty_alpha=penalty_alpha)) 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 use_cache and attention_sinks: from transformers import SinkCache sink_dict['window_length'] = sink_dict.get('window_length', max_input_tokens) sink_dict['num_sink_tokens'] = sink_dict.get('num_sink_tokens', 4) cache = SinkCache(**sink_dict) gen_kwargs.update(dict(past_key_values=cache)) 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 = '' 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(), llm_answers={}, response_no_refs='', sources_str='', prompt_raw=prompt) outputs = "" sources = [] tgen0 = time.time() 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=save_dict, llm_answers={}, response_no_refs=response, sources_str='', prompt_raw=prompt) if stream_output: yield ret if time.time() - tgen0 > max_time: if verbose: print("Took too long for Torch: %s" % (time.time() - tgen0), flush=True) break if stream_output: # will yield at end if required # yield if anything left over as can happen (FIXME: Understand better) 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) if outputs and len(outputs) >= 1: decoded_output = prompt + outputs[0] # full return with save_dict and prompt_raw # if not streaming, only place yield should be extra_dict.update(gen_config_kwargs) extra_dict.update(dict(num_prompt_tokens=num_prompt_tokens, t_generate=time.time() - t_generate, sources_str='', ntokens=ntokens, tokens_persecond=ntokens / (time.time() - t_generate), )) save_dict.update(dict(prompt=prompt, output=decoded_output, where_from="evaluate_%s" % str(stream_output), extra_dict=extra_dict)) yield dict(response=response, sources=sources, save_dict=save_dict, llm_answers={}, response_no_refs=response, sources_str='', prompt_raw=prompt) if torch.cuda.is_available() and device not in ['cpu', 'mps']: torch.cuda.empty_cache() if hasattr(model, 'memory') and hasattr(model.memory, 'reset'): model.memory.reset() if verbose: print('Post-Generate: %s decoded_output: %s' % ( str(datetime.now()), len(decoded_output) if decoded_output else -1), flush=True)
null
167,118
import ast import copy import functools import inspect import queue import sys import os import time import traceback import typing import uuid import warnings from datetime import datetime import httpx 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 from src.image_utils import get_image_file 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' 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, docs_joiner_default, \ docs_ordering_types_default, docs_token_handling_default, max_input_tokens_public, max_total_input_tokens_public, \ max_top_k_docs_public, max_top_k_docs_default, max_total_input_tokens_public_api, max_top_k_docs_public_api, \ max_input_tokens_public_api, model_token_mapping_outputs, anthropic_mapping, anthropic_mapping_outputs, \ user_prompt_for_fake_system_prompt, base_langchain_actions, google_mapping, google_mapping_outputs, generic_prefix, \ generic_postfix, mistralai_mapping, mistralai_mapping_outputs, langchain_modes_intrinsic 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, \ url_alive, have_wavio, have_soundfile, have_deepspeed, have_doctr, have_librosa, have_TTS, have_flash_attention_2, \ have_diffusers, sanitize_filename, get_gradio_tmp, get_is_gradio_h2oai 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, \ openai_gpts, get_vllm_extra_dict, anthropic_gpts, google_gpts, mistralai_gpts, is_vision_model from stopping import get_stopping def clear_torch_cache(allow_skip=False): if allow_skip and os.getenv('CLEAR_CLEAR_TORCH', '2') == '1' or os.getenv('CLEAR_CLEAR_TORCH', '2') == '0': return try: import torch if torch.cuda.is_available(): torch.cuda.empty_cache() torch.cuda.ipc_collect() gc.collect() except RuntimeError as e: print("clear_torch_cache error: %s" % ''.join(traceback.format_tb(e.__traceback__)), flush=True) def score_qa(smodel, stokenizer, question, answer, memory_restriction_level=0): if memory_restriction_level > 0: max_length_tokenize = 768 - 256 if memory_restriction_level <= 2 else 512 - 256 elif hasattr(stokenizer, 'model_max_length'): max_length_tokenize = stokenizer.model_max_length else: # limit to 1024, not worth OOMing on reward score max_length_tokenize = 2048 - 1024 cutoff_len = max_length_tokenize * 4 # restrict deberta related to max for LLM 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: score = 0.0 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: score = 0.0 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
null
167,119
import ast import copy import functools import inspect import queue import sys import os import time import traceback import typing import uuid import warnings from datetime import datetime import httpx 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 from src.image_utils import get_image_file 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, docs_joiner_default, \ docs_ordering_types_default, docs_token_handling_default, max_input_tokens_public, max_total_input_tokens_public, \ max_top_k_docs_public, max_top_k_docs_default, max_total_input_tokens_public_api, max_top_k_docs_public_api, \ max_input_tokens_public_api, model_token_mapping_outputs, anthropic_mapping, anthropic_mapping_outputs, \ user_prompt_for_fake_system_prompt, base_langchain_actions, google_mapping, google_mapping_outputs, generic_prefix, \ generic_postfix, mistralai_mapping, mistralai_mapping_outputs, langchain_modes_intrinsic 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, \ url_alive, have_wavio, have_soundfile, have_deepspeed, have_doctr, have_librosa, have_TTS, have_flash_attention_2, \ have_diffusers, sanitize_filename, get_gradio_tmp, get_is_gradio_h2oai 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, \ openai_gpts, get_vllm_extra_dict, anthropic_gpts, google_gpts, mistralai_gpts, is_vision_model from stopping import get_stopping inputs_kwargs_list = [x for x in inputs_list_names if x not in eval_func_param_names + state_names] no_default_param_names = [ 'instruction', 'iinput', 'context', 'instruction_nochat', 'iinput_nochat', 'h2ogpt_key', ] 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', 'document_source_substrings', 'document_source_substrings_op', 'document_content_substrings', 'document_content_substrings_op', 'pre_prompt_query', 'prompt_query', 'pre_prompt_summary', 'prompt_summary', 'hyde_llm_prompt', 'system_prompt', ] + \ reader_names + \ ['visible_models', 'h2ogpt_key', 'add_search_to_context', 'chat_conversation', 'text_context_list', 'docs_ordering_type', 'min_max_new_tokens', 'max_input_tokens', 'max_total_input_tokens', 'docs_token_handling', 'docs_joiner', 'hyde_level', 'hyde_template', 'hyde_show_only_final', 'doc_json_mode', 'metadata_in_context', 'chatbot_role', 'speaker', 'tts_language', 'tts_speed', 'image_file', 'image_control', ] def check_locals(**kwargs): # ensure everything in evaluate is here can_skip_because_locally_generated = no_default_param_names + [ # get_model: 'reward_type' ] missing1 = [] for k in eval_func_param_names: if k in can_skip_because_locally_generated: continue if k not in kwargs: missing1.append(k) assert not missing1, "Missing %s" % missing1 missing2 = [] for k in inputs_kwargs_list: if k in can_skip_because_locally_generated: continue if k not in kwargs: missing2.append(k) assert not missing2, "Missing %s" % missing2
null
167,120
import ast import copy import functools import inspect import queue import sys import os import time import traceback import typing import uuid import warnings from datetime import datetime import httpx 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 from src.image_utils import get_image_file 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, docs_joiner_default, \ docs_ordering_types_default, docs_token_handling_default, max_input_tokens_public, max_total_input_tokens_public, \ max_top_k_docs_public, max_top_k_docs_default, max_total_input_tokens_public_api, max_top_k_docs_public_api, \ max_input_tokens_public_api, model_token_mapping_outputs, anthropic_mapping, anthropic_mapping_outputs, \ user_prompt_for_fake_system_prompt, base_langchain_actions, google_mapping, google_mapping_outputs, generic_prefix, \ generic_postfix, mistralai_mapping, mistralai_mapping_outputs, langchain_modes_intrinsic 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, \ url_alive, have_wavio, have_soundfile, have_deepspeed, have_doctr, have_librosa, have_TTS, have_flash_attention_2, \ have_diffusers, sanitize_filename, get_gradio_tmp, get_is_gradio_h2oai 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, \ openai_gpts, get_vllm_extra_dict, anthropic_gpts, google_gpts, mistralai_gpts, is_vision_model from stopping import get_stopping def get_model_max_length_from_tokenizer(tokenizer): if hasattr(tokenizer, 'model_max_length'): return int(tokenizer.model_max_length) else: return 2048
null
167,121
import ast import copy import functools import inspect import queue import sys import os import time import traceback import typing import uuid import warnings from datetime import datetime import httpx 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 from src.image_utils import get_image_file 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, docs_joiner_default, \ docs_ordering_types_default, docs_token_handling_default, max_input_tokens_public, max_total_input_tokens_public, \ max_top_k_docs_public, max_top_k_docs_default, max_total_input_tokens_public_api, max_top_k_docs_public_api, \ max_input_tokens_public_api, model_token_mapping_outputs, anthropic_mapping, anthropic_mapping_outputs, \ user_prompt_for_fake_system_prompt, base_langchain_actions, google_mapping, google_mapping_outputs, generic_prefix, \ generic_postfix, mistralai_mapping, mistralai_mapping_outputs, langchain_modes_intrinsic 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, \ url_alive, have_wavio, have_soundfile, have_deepspeed, have_doctr, have_librosa, have_TTS, have_flash_attention_2, \ have_diffusers, sanitize_filename, get_gradio_tmp, get_is_gradio_h2oai 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, \ openai_gpts, get_vllm_extra_dict, anthropic_gpts, google_gpts, mistralai_gpts, is_vision_model from stopping import get_stopping def get_token_count(x, tokenizer, token_count_fun=None): # NOTE: Somewhat duplicates H2OTextGenerationPipeline.get_token_count() # handle ambiguity in if get dict or list if tokenizer is not None: if hasattr(tokenizer, 'encode'): tokens = tokenizer.encode(x) else: tokens = tokenizer(x) if isinstance(tokens, dict) and 'input_ids' in tokens: tokens = tokens['input_ids'] if isinstance(tokens, list): n_tokens = len(tokens) elif len(tokens.shape) == 2: n_tokens = tokens.shape[1] elif len(tokens.shape) == 1: n_tokens = tokens.shape[0] else: raise RuntimeError("Cannot handle tokens: %s" % tokens) elif token_count_fun is not None: assert callable(token_count_fun) n_tokens = token_count_fun(x) else: tokenizer = FakeTokenizer() n_tokens = tokenizer.num_tokens_from_string(x) return n_tokens def get_relaxed_max_new_tokens(prompt, tokenizer=None, max_new_tokens=None, max_new_tokens0=None): # check if can relax max_new_tokens for this specific prompt if max_new_tokens0 is not None and \ hasattr(tokenizer, 'model_max_len') and \ isinstance(tokenizer.model_max_len, (float, int)): max_new_tokens = int(tokenizer.model_max_length) - get_token_count(prompt, tokenizer) if max_new_tokens is not None: return min(max_new_tokens0, max_new_tokens) else: return max_new_tokens0 return max_new_tokens
null
167,122
import ast import copy import functools import inspect import queue import sys import os import time import traceback import typing import uuid import warnings from datetime import datetime import httpx 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 from src.image_utils import get_image_file 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' 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, docs_joiner_default, \ docs_ordering_types_default, docs_token_handling_default, max_input_tokens_public, max_total_input_tokens_public, \ max_top_k_docs_public, max_top_k_docs_default, max_total_input_tokens_public_api, max_top_k_docs_public_api, \ max_input_tokens_public_api, model_token_mapping_outputs, anthropic_mapping, anthropic_mapping_outputs, \ user_prompt_for_fake_system_prompt, base_langchain_actions, google_mapping, google_mapping_outputs, generic_prefix, \ generic_postfix, mistralai_mapping, mistralai_mapping_outputs, langchain_modes_intrinsic 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, \ url_alive, have_wavio, have_soundfile, have_deepspeed, have_doctr, have_librosa, have_TTS, have_flash_attention_2, \ have_diffusers, sanitize_filename, get_gradio_tmp, get_is_gradio_h2oai 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, \ openai_gpts, get_vllm_extra_dict, anthropic_gpts, google_gpts, mistralai_gpts, is_vision_model from stopping import get_stopping def get_on_disk_models(llamacpp_path, use_auth_token, trust_remote_code): print("Begin auto-detect HF cache text generation models", flush=True) from huggingface_hub import scan_cache_dir hf_cache_info = scan_cache_dir() hf_models = [x.repo_id for x in hf_cache_info.repos if x.repo_type == 'model' and x.size_on_disk > 100000 and x.nb_files > 0] # filter all models down to plausible text models # FIXME: Maybe better/faster way to doing this from transformers import AutoConfig text_hf_models = [] for x in hf_models: try: config = AutoConfig.from_pretrained(x, token=use_auth_token, trust_remote_code=trust_remote_code) if hasattr(config, 'is_encoder_decoder') and config.is_encoder_decoder and x != 'lmsys/fastchat-t5-3b-v1.0': print("No loading model %s because is_encoder_decoder=True" % x) continue if hasattr(config, 'vocab_size'): text_hf_models.append(x) except Exception as e: print("No loading model %s because %s" % (x, str(e))) print("End auto-detect HF cache text generation models", flush=True) print("Begin auto-detect llama.cpp models", flush=True) llamacpp_path = os.getenv('LLAMACPP_PATH', llamacpp_path) or './' llamacpp_files = [os.path.join(llamacpp_path, f) for f in os.listdir(llamacpp_path) if os.path.isfile(os.path.join(llamacpp_path, f))] print("End auto-detect llama.cpp models", flush=True) return text_hf_models + llamacpp_files
null
167,124
from __future__ import annotations from typing import Iterable from gradio.themes.soft import Soft from gradio.themes import Color, Size from gradio.themes.utils import colors, sizes, fonts h2o_logo = '<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%"' \ ' viewBox="0 0 600.28 600.28"><defs><style>.cls-1{fill:#fec925;}.cls-2{fill:#161616;}.cls-3{fill:' \ '#54585a;}</style></defs><g id="Fill-1"><rect class="cls-1" width="600.28" height="600.28" ' \ 'rx="23.24"/></g><path class="cls-2" d="M174.33,246.06v92.78H152.86v-38H110.71v38H89.24V246.06h21.' \ '47v36.58h42.15V246.06Z"/><path class="cls-2" d="M259.81,321.34v17.5H189.7V324.92l35.78-33.8c8.22-7.' \ '82,9.68-12.59,9.68-17.09,0-7.29-5-11.53-14.85-11.53-7.95,0-14.71,3-19.21,9.27L185.46,261.7c7.15-10' \ '.47,20.14-17.23,36.84-17.23,20.68,0,34.46,10.6,34.46,27.44,0,9-2.52,17.22-15.51,29.29l-21.33,20.14Z"' \ '/><path class="cls-2" d="M268.69,292.45c0-27.57,21.47-48,50.76-48s50.76,20.28,50.76,48-21.6,48-50.' \ '76,48S268.69,320,268.69,292.45Zm79.78,0c0-17.63-12.46-29.69-29-29.69s-29,12.06-29,29.69,12.46,29.69' \ ',29,29.69S348.47,310.08,348.47,292.45Z"/><path class="cls-3" d="M377.23,326.91c0-7.69,5.7-12.73,12.' \ '85-12.73s12.86,5,12.86,12.73a12.86,12.86,0,1,1-25.71,0Z"/><path class="cls-3" d="M481.4,298.15v40.' \ '69H462.05V330c-3.84,6.49-11.27,9.94-21.74,9.94-16.7,0-26.64-9.28-26.64-21.61,0-12.59,8.88-21.34,30.' \ '62-21.34h16.43c0-8.87-5.3-14-16.43-14-7.55,0-15.37,2.51-20.54,6.62l-7.43-14.44c7.82-5.57,19.35-8.' \ '62,30.75-8.62C468.81,266.47,481.4,276.54,481.4,298.15Zm-20.68,18.16V309H446.54c-9.67,0-12.72,3.57-' \ '12.72,8.35,0,5.16,4.37,8.61,11.66,8.61C452.37,326,458.34,322.8,460.72,316.31Z"/><path class="cls-3"' \ ' d="M497.56,246.06c0-6.49,5.17-11.53,12.86-11.53s12.86,4.77,12.86,11.13c0,6.89-5.17,11.93-12.86,' \ '11.93S497.56,252.55,497.56,246.06Zm2.52,21.47h20.68v71.31H500.08Z"/></svg>' def get_h2o_title(title, description, visible_h2ogpt_qrcode): # NOTE: Check full width desktop, smallest width browser desktop, iPhone browsers to ensure no overlap etc. ret = f"""<div style="float:left; justify-content:left; height: 80px; width: 195px; margin-top:0px"> {description} </div> <div style="display:flex; justify-content:center; margin-bottom:30px; margin-right:330px;"> <div style="height: 60px; width: 60px; margin-right:20px;">{h2o_logo}</div> <h1 style="line-height:60px">{title}</h1> </div> """ if visible_h2ogpt_qrcode: ret += """ <div style="float:right; height: 80px; width: 80px; margin-top:-100px"> <img src="https://raw.githubusercontent.com/h2oai/h2ogpt/main/docs/h2o-qr.png"> </div> """ return ret
null
167,125
from __future__ import annotations from typing import Iterable from gradio.themes.soft import Soft from gradio.themes import Color, Size from gradio.themes.utils import colors, sizes, fonts def get_simple_title(title, description): return f"""{description}<h1 align="center"> {title}</h1>"""
null
167,126
from __future__ import annotations from typing import Iterable from gradio.themes.soft import Soft from gradio.themes import Color, Size from gradio.themes.utils import colors, sizes, fonts def get_dark_js() -> str: return """ if (document.querySelectorAll('.dark').length) { document.querySelectorAll('.dark').forEach(el => el.classList.remove('dark')); } else { document.querySelector('body').classList.add('dark'); } """
null
167,127
from __future__ import annotations from typing import Iterable from gradio.themes.soft import Soft from gradio.themes import Color, Size from gradio.themes.utils import colors, sizes, fonts def get_heap_js(heapAppId: str) -> str: return ( """globalThis.window.heap=window.heap||[],heap.load=function(e,t){window.heap.appid=e,window.heap.config=t=t||{};var r=document.createElement("script");r.type="text/javascript",r.async=!0,r.src="https://cdn.heapanalytics.com/js/heap-"+e+".js";var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(r,a);for(var n=function(e){return function(){heap.push([e].concat(Array.prototype.slice.call(arguments,0)))}},p=["addEventProperties","addUserProperties","clearEventProperties","identify","resetIdentity","removeEventProperty","setEventProperties","track","unsetEventProperty"],o=0;o<p.length;o++)heap[p[o]]=n(p[o])};""" f"""heap.load("{heapAppId}");""")
null
167,128
from __future__ import annotations from typing import Iterable from gradio.themes.soft import Soft from gradio.themes import Color, Size from gradio.themes.utils import colors, sizes, fonts The provided code snippet includes necessary dependencies for implementing the `wrap_js_to_lambda` function. Write a Python function `def wrap_js_to_lambda(num_params: int, *args: str) -> str` to solve the following problem: Generates a JS code representing JS lambda that wraps all given '*args' code strings. The lambda function has number of parameters based on 'num_params' and returns them without modification in an array. Lambda with zero parameters returns an empty array. Here is the function: def wrap_js_to_lambda(num_params: int, *args: str) -> str: """ Generates a JS code representing JS lambda that wraps all given '*args' code strings. The lambda function has number of parameters based on 'num_params' and returns them without modification in an array. Lambda with zero parameters returns an empty array. """ params = ", ".join([f"p{i}" for i in range(num_params)]) newline = "\n" return f""" ({params}) => {{ {newline.join([a for a in args if a is not None])} return [{params}]; }} """
Generates a JS code representing JS lambda that wraps all given '*args' code strings. The lambda function has number of parameters based on 'num_params' and returns them without modification in an array. Lambda with zero parameters returns an empty array.
167,129
import ast import time from enums import PromptType, gpt_token_mapping, \ anthropic_mapping, google_mapping, mistralai_mapping def is_vision_model(base_model): return base_model.startswith('llava-') or \ base_model.startswith('liuhaotian/llava-') or \ base_model.startswith('Qwen-VL') or \ base_model.startswith('Qwen/Qwen-VL')
null
167,130
import ast import time from enums import PromptType, gpt_token_mapping, \ anthropic_mapping, google_mapping, mistralai_mapping prompt_types = [] def get_prompt(prompt_type, prompt_dict, context, reduced, making_context, return_dict=False, system_prompt=None, histi=-1): prompt_dict_error = '' generates_leading_space = False can_handle_system_prompt = False if prompt_type == PromptType.custom.name and not isinstance(prompt_dict, dict): try: prompt_dict = ast.literal_eval(prompt_dict) except BaseException as e: prompt_dict_error = str(e) if prompt_dict_error: promptA = None promptB = None PreInstruct = None PreInput = '' PreResponse = '' terminate_response = None chat_sep = '' chat_turn_sep = '' humanstr = '' botstr = '' generates_leading_space = False elif prompt_type in [PromptType.custom.value, str(PromptType.custom.value), PromptType.custom.name]: promptA = prompt_dict.get('promptA', '') promptB = prompt_dict.get('promptB', '') PreInstruct = prompt_dict.get('PreInstruct', '') PreInput = prompt_dict.get('PreInput', '') PreResponse = prompt_dict.get('PreResponse', '') terminate_response = prompt_dict.get('terminate_response', None) chat_sep = prompt_dict.get('chat_sep', '\n') chat_turn_sep = prompt_dict.get('chat_turn_sep', '\n') humanstr = prompt_dict.get('humanstr', '') botstr = prompt_dict.get('botstr', '') elif prompt_type in [PromptType.plain.value, str(PromptType.plain.value), PromptType.plain.name] or \ prompt_type in [PromptType.llava.value, str(PromptType.llava.value), PromptType.llava.name]: promptA = promptB = PreInstruct = PreInput = PreResponse = None terminate_response = [] chat_turn_sep = chat_sep = '\n' # plain should have None for human/bot, so nothing truncated out, not '' that would truncate after first token humanstr = None botstr = None elif prompt_type == 'simple_instruct': promptA = promptB = PreInstruct = PreInput = PreResponse = None terminate_response = [] chat_turn_sep = chat_sep = '\n' humanstr = None botstr = None elif prompt_type in [PromptType.instruct.value, str(PromptType.instruct.value), PromptType.instruct.name] + [PromptType.instruct_with_end.value, str(PromptType.instruct_with_end.value), PromptType.instruct_with_end.name]: promptA = 'Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.\n' if not reduced else '' promptB = 'Below is an instruction that describes a task. Write a response that appropriately completes the request.\n' if not reduced else '' PreInstruct = """ ### Instruction: """ PreInput = """ ### Input: """ PreResponse = """ ### Response: """ if prompt_type in [PromptType.instruct_with_end.value, str(PromptType.instruct_with_end.value), PromptType.instruct_with_end.name]: terminate_response = ['### End'] else: terminate_response = None chat_turn_sep = chat_sep = '\n' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.quality.value, str(PromptType.quality.value), PromptType.quality.name]: promptA = 'Write a detailed high-quality, accurate, fair, Response with about 100 words by following the Instruction as applied on the Input.\n' if not reduced else '' promptB = 'Write a detailed high-quality, accurate, fair, Response with about 100 words by following the Instruction.\n' if not reduced else '' PreInstruct = """ ### Instruction: """ PreInput = """ ### Input: """ PreResponse = """ ### Response: """ terminate_response = None chat_turn_sep = chat_sep = '\n' humanstr = PreInstruct # first thing human says botstr = PreResponse # first thing bot says elif prompt_type in [PromptType.human_bot.value, str(PromptType.human_bot.value), PromptType.human_bot.name] + [PromptType.human_bot_orig.value, str(PromptType.human_bot_orig.value), PromptType.human_bot_orig.name]: human = '<human>:' bot = "<bot>:" if reduced or context or prompt_type in [PromptType.human_bot.value, str(PromptType.human_bot.value), PromptType.human_bot.name]: preprompt = '' else: cur_date = time.strftime('%Y-%m-%d') cur_time = time.strftime('%H:%M:%S %p %Z') PRE_PROMPT = """\ Current Date: {} Current Time: {} """ preprompt = PRE_PROMPT.format(cur_date, cur_time) start = '' promptB = promptA = '%s%s' % (preprompt, start) PreInstruct = human + ' ' PreInput = None if making_context: # when making context, want it to appear as-if LLM generated, which starts with space after : PreResponse = bot + ' ' else: # normally LLM adds space after this, because was how trained. # if add space here, non-unique tokenization will often make LLM produce wrong output PreResponse = bot terminate_response = ['\n' + human, '\n' + bot, human, bot, PreResponse] chat_turn_sep = chat_sep = '\n' humanstr = human # tag before human talks botstr = bot # tag before bot talks generates_leading_space = True elif prompt_type in [PromptType.dai_faq.value, str(PromptType.dai_faq.value), PromptType.dai_faq.name]: promptA = '' promptB = 'Answer the following Driverless AI question.\n' PreInstruct = """ ### Driverless AI frequently asked question: """ PreInput = None PreResponse = """ ### Driverless AI documentation answer: """ terminate_response = ['\n\n'] chat_turn_sep = chat_sep = terminate_response humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.summarize.value, str(PromptType.summarize.value), PromptType.summarize.name]: promptA = promptB = PreInput = '' PreInstruct = '## Main Text\n\n' PreResponse = '\n\n## Summary\n\n' terminate_response = None chat_turn_sep = chat_sep = '\n' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.instruct_vicuna.value, str(PromptType.instruct_vicuna.value), PromptType.instruct_vicuna.name]: can_handle_system_prompt = True if system_prompt in [None, 'None', 'auto']: system_prompt = "A chat between a curious human and an artificial intelligence assistant. " \ "The assistant gives helpful, detailed, and polite answers to the human's questions." promptA = promptB = system_prompt if not reduced else '' PreInstruct = """ ### Human: """ PreInput = None PreResponse = """ ### Assistant: """ # but only allow terminate after prompt is found correctly, else can't terminate terminate_response = ['### Human:', '### Human: ', ' ### Human:', '### Assistant:'] chat_turn_sep = chat_sep = '\n' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.prompt_answer.value, str(PromptType.prompt_answer.value), PromptType.prompt_answer.name]: preprompt = '' prompt_tokens = "<|prompt|>" answer_tokens = "<|answer|>" start = '' promptB = promptA = '%s%s' % (preprompt, start) PreInstruct = prompt_tokens PreInput = None PreResponse = answer_tokens eos = '<|endoftext|>' # neox eos humanstr = prompt_tokens botstr = answer_tokens terminate_response = [humanstr, PreResponse, eos] chat_sep = eos chat_turn_sep = eos elif prompt_type in [PromptType.prompt_answer_openllama.value, str(PromptType.prompt_answer_openllama.value), PromptType.prompt_answer_openllama.name]: preprompt = '' prompt_tokens = "<|prompt|>" answer_tokens = "<|answer|>" start = '' promptB = promptA = '%s%s' % (preprompt, start) PreInstruct = prompt_tokens PreInput = None PreResponse = answer_tokens eos = '</s>' # llama eos humanstr = prompt_tokens botstr = answer_tokens terminate_response = [humanstr, PreResponse, eos] chat_sep = eos chat_turn_sep = eos elif prompt_type in [PromptType.danube.value, str(PromptType.danube.value), PromptType.danube.name]: can_handle_system_prompt = True # so not part of pre-conversation prompt_tokens = "<|prompt|>" answer_tokens = "<|answer|>" if system_prompt in [None, 'None', 'auto']: system_prompt = "I am H2O-Danube, a conversational chat assistant developed by H2O.ai." promptA = promptB = system_prompt if not reduced else '' PreInstruct = prompt_tokens PreInput = None PreResponse = answer_tokens eos = '</s>' # llama eos humanstr = prompt_tokens botstr = answer_tokens terminate_response = [humanstr, PreResponse, eos] chat_sep = eos chat_turn_sep = eos elif prompt_type in [PromptType.open_assistant.value, str(PromptType.open_assistant.value), PromptType.open_assistant.name]: # From added_tokens.json preprompt = '' prompt_tokens = "<|prompter|>" answer_tokens = "<|assistant|>" start = '' promptB = promptA = '%s%s' % (preprompt, start) PreInstruct = prompt_tokens PreInput = None PreResponse = answer_tokens pend = "<|prefix_end|>" eos = "</s>" humanstr = prompt_tokens botstr = answer_tokens terminate_response = [humanstr, PreResponse, pend, eos] chat_turn_sep = chat_sep = eos elif prompt_type in [PromptType.wizard_lm.value, str(PromptType.wizard_lm.value), PromptType.wizard_lm.name]: # https://github.com/ehartford/WizardLM/blob/main/src/train_freeform.py preprompt = '' start = '' promptB = promptA = '%s%s' % (preprompt, start) PreInstruct = "" PreInput = None PreResponse = "\n\n### Response\n" eos = "</s>" terminate_response = [PreResponse, eos] chat_turn_sep = chat_sep = eos humanstr = promptA botstr = PreResponse elif prompt_type in [PromptType.wizard_mega.value, str(PromptType.wizard_mega.value), PromptType.wizard_mega.name]: preprompt = '' start = '' promptB = promptA = '%s%s' % (preprompt, start) PreInstruct = """ ### Instruction: """ PreInput = None PreResponse = """ ### Assistant: """ terminate_response = [PreResponse] chat_turn_sep = chat_sep = '\n' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.instruct_vicuna2.value, str(PromptType.instruct_vicuna2.value), PromptType.instruct_vicuna2.name]: promptA = promptB = "" if not reduced else '' PreInstruct = """ HUMAN: """ PreInput = None PreResponse = """ ASSISTANT: """ terminate_response = [ 'HUMAN:'] # but only allow terminate after prompt is found correctly, else can't terminate chat_turn_sep = chat_sep = '\n' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.instruct_vicuna3.value, str(PromptType.instruct_vicuna3.value), PromptType.instruct_vicuna3.name]: promptA = promptB = "" if not reduced else '' PreInstruct = """ ### User: """ PreInput = None PreResponse = """ ### Assistant: """ terminate_response = [ '### User:'] # but only allow terminate after prompt is found correctly, else can't terminate chat_turn_sep = chat_sep = '\n' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.wizard2.value, str(PromptType.wizard2.value), PromptType.wizard2.name]: can_handle_system_prompt = True # https://huggingface.co/TheBloke/WizardLM-7B-uncensored-GGML if system_prompt in [None, 'None', 'auto']: system_prompt = "Below is an instruction that describes a task. Write a response that appropriately completes the request." preprompt = """%s""" % system_prompt if not reduced else '' start = '' promptB = promptA = '%s%s' % (preprompt, start) PreInstruct = """ ### Instruction: """ PreInput = None PreResponse = """ ### Response: """ terminate_response = [PreResponse] chat_turn_sep = chat_sep = '\n' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.wizard3.value, str(PromptType.wizard3.value), PromptType.wizard3.name]: # https://huggingface.co/TheBloke/wizardLM-13B-1.0-GGML can_handle_system_prompt = True if system_prompt in [None, 'None', 'auto']: system_prompt = "A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions." preprompt = """%s""" % system_prompt if not reduced else '' start = '' promptB = promptA = '%s%s' % (preprompt, start) PreInstruct = """USER: """ PreInput = None PreResponse = """ASSISTANT: """ terminate_response = [PreResponse] chat_turn_sep = chat_sep = '\n' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.wizard_vicuna.value, str(PromptType.wizard_vicuna.value), PromptType.wizard_vicuna.name]: preprompt = '' start = '' promptB = promptA = '%s%s' % (preprompt, start) PreInstruct = """USER: """ PreInput = None PreResponse = """ASSISTANT: """ terminate_response = [PreResponse] chat_turn_sep = chat_sep = '\n' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.instruct_simple.value, str(PromptType.instruct_simple.value), PromptType.instruct_simple.name]: promptB = promptA = '' if not reduced else '' PreInstruct = """ ### Instruction: """ PreInput = """ ### Input: """ PreResponse = """ ### Response: """ terminate_response = None chat_turn_sep = chat_sep = '\n' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.openai.value, str(PromptType.openai.value), PromptType.openai.name]: can_handle_system_prompt = True if system_prompt in [None, 'None', 'auto']: system_prompt = "The following is a conversation with an AI assistant. The assistant is helpful, creative, clever, and very friendly." preprompt = """%s""" % system_prompt if not reduced else '' start = '' promptB = promptA = '%s%s' % (preprompt, start) PreInstruct = "\nHuman: " PreInput = None PreResponse = "\nAI:" terminate_response = [PreResponse] + [" Human:", " AI:"] chat_turn_sep = chat_sep = '\n' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.gptj.value, str(PromptType.gptj.value), PromptType.gptj.name]: preprompt = "### Instruction:\n The prompt below is a question to answer, a task to complete, or a conversation to respond to; decide which and write an appropriate response." if not reduced else '' start = '' promptB = promptA = '%s%s' % (preprompt, start) PreInstruct = "\n### Prompt: " PreInput = None PreResponse = "\n### Response: " terminate_response = [PreResponse] + ["Prompt:", "Response:"] chat_turn_sep = chat_sep = '\n' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.openai_chat.value, str(PromptType.openai_chat.value), PromptType.openai_chat.name] or \ prompt_type in [PromptType.anthropic.value, str(PromptType.anthropic.value), PromptType.anthropic.name] or \ prompt_type in [PromptType.google.value, str(PromptType.google.value), PromptType.google.name] or \ prompt_type in [PromptType.mistralai.value, str(PromptType.mistralai.value), PromptType.mistralai.name]: can_handle_system_prompt = True # handled via special messages/arguments not part of prompt # mistral safe_mode=True is same as this system prompt: # Always assist with care, respect, and truth. Respond with utmost utility yet securely. Avoid harmful, unethical, prejudiced, or negative content. Ensure replies promote fairness and positivity. # prompting and termination all handled by endpoint preprompt = """""" start = '' promptB = promptA = '%s%s' % (preprompt, start) PreInstruct = "" PreInput = None PreResponse = "" terminate_response = [] chat_turn_sep = chat_sep = '\n' humanstr = None botstr = None if prompt_type in [PromptType.google.value, str(PromptType.google.value), PromptType.google.name] and system_prompt == 'auto': # google throws safety/harassment errors if don't tell the model it's helpful, even for asking "what is 1+1?" # so give basic prompt if auto, the current default, so part of pre-conversation always system_prompt = 'I am a helpful assistant. I will accurately answer all your questions.' elif prompt_type in [PromptType.vicuna11.value, str(PromptType.vicuna11.value), PromptType.vicuna11.name] or \ prompt_type in [PromptType.vicuna11nosys.value, str(PromptType.vicuna11nosys.value), PromptType.vicuna11nosys.name]: can_handle_system_prompt = prompt_type in [PromptType.vicuna11.value, str(PromptType.vicuna11.value), PromptType.vicuna11.name] if system_prompt in [None, 'None', 'auto']: system_prompt = "A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions." if not can_handle_system_prompt: # totally remove system prompt stuff, maybe not always done for every model like this preprompt = "" else: preprompt = """%s """ % system_prompt if not reduced else '' start = '' promptB = promptA = '%s%s' % (preprompt, start) eos = '</s>' PreInstruct = """USER: """ PreInput = None PreResponse = """ASSISTANT:""" terminate_response = [PreResponse, eos] chat_sep = ' ' chat_turn_sep = eos humanstr = PreInstruct botstr = PreResponse if making_context: # when making context, want it to appear as-if LLM generated, which starts with space after : PreResponse = PreResponse + ' ' else: # normally LLM adds space after this, because was how trained. # if add space here, non-unique tokenization will often make LLM produce wrong output PreResponse = PreResponse elif prompt_type in [PromptType.mptinstruct.value, str(PromptType.mptinstruct.value), PromptType.mptinstruct.name]: can_handle_system_prompt = True # https://huggingface.co/mosaicml/mpt-30b-instruct#formatting if system_prompt in [None, 'None', 'auto']: system_prompt = "Below is an instruction that describes a task. Write a response that appropriately completes the request." promptA = promptB = '%s\n' % system_prompt if not reduced else '' PreInstruct = """ ### Instruction """ PreInput = """ ### Input """ PreResponse = """ ### Response """ terminate_response = None chat_turn_sep = chat_sep = '\n' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.mptchat.value, str(PromptType.mptchat.value), PromptType.mptchat.name]: can_handle_system_prompt = True # https://huggingface.co/TheBloke/mpt-30B-chat-GGML#prompt-template if system_prompt in [None, 'None', 'auto']: system_prompt = "A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers." promptA = promptB = """<|im_start|>system\n%s\n<|im_end|>""" % system_prompt if not reduced else '' PreInstruct = """<|im_start|>user """ PreInput = None PreResponse = """<|im_end|><|im_start|>assistant """ terminate_response = ['<|im_end|>'] chat_sep = '' chat_turn_sep = '<|im_end|>' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.orca2.value, str(PromptType.orca2.value), PromptType.orca2.name]: can_handle_system_prompt = True # https://huggingface.co/microsoft/Orca-2-13b#getting-started-with-orca-2 if system_prompt in [None, 'None', 'auto']: system_prompt = "You are Orca, an AI language model created by Microsoft. You are a cautious assistant. You carefully follow instructions. You are helpful and harmless and you follow ethical guidelines and promote positive behavior." promptA = promptB = """<|im_start|>system\n%s\n<|im_end|>""" % system_prompt if not reduced else '' PreInstruct = """<|im_start|>user """ PreInput = None PreResponse = """<|im_end|><|im_start|>assistant """ terminate_response = ['<|im_end|>'] chat_sep = '' chat_turn_sep = '<|im_end|>' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.falcon.value, str(PromptType.falcon.value), PromptType.falcon.name]: promptA = promptB = "" if not reduced else '' PreInstruct = """User: """ PreInput = None PreResponse = """Assistant:""" terminate_response = ['\nUser', "<|endoftext|>"] chat_sep = '\n\n' chat_turn_sep = '\n\n' humanstr = PreInstruct botstr = PreResponse if making_context: # when making context, want it to appear as-if LLM generated, which starts with space after : PreResponse = 'Assistant: ' else: # normally LLM adds space after this, because was how trained. # if add space here, non-unique tokenization will often make LLM produce wrong output PreResponse = PreResponse # generates_leading_space = True elif prompt_type in [PromptType.guanaco.value, str(PromptType.guanaco.value), PromptType.guanaco.name]: # https://huggingface.co/TheBloke/guanaco-65B-GPTQ promptA = promptB = "" if not reduced else '' PreInstruct = """### Human: """ PreInput = None PreResponse = """### Assistant:""" terminate_response = [ '### Human:'] # but only allow terminate after prompt is found correctly, else can't terminate chat_turn_sep = chat_sep = '\n' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.llama2.value, str(PromptType.llama2.value), PromptType.llama2.name]: can_handle_system_prompt = True if system_prompt in [None, 'None', 'auto']: # automatic system_prompt = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""" # too much safety, hurts accuracy if system_prompt: sys_msg = """<<SYS>>\n%s\n<</SYS>>\n\n""" % system_prompt else: sys_msg = '' if not reduced: promptA = promptB = '' else: promptA = promptB = '' PreInput = None PreInstruct = "<s>[INST] " if making_context and histi == 0 or not making_context and not reduced: PreInstruct += sys_msg PreResponse = "[/INST]" terminate_response = ["[INST]", "</s>"] chat_sep = ' ' chat_turn_sep = ' </s>' humanstr = '[INST]' botstr = '[/INST]' if making_context: PreResponse += " " elif prompt_type in [PromptType.beluga.value, str(PromptType.beluga.value), PromptType.beluga.name]: can_handle_system_prompt = True if system_prompt in [None, 'None', 'auto']: # automatic system_prompt = "You are Stable Beluga, an AI that follows instructions extremely well. Help as much as you can. Remember, be safe, and don't do anything illegal." if system_prompt: sys_msg = """### System:\n%s\n\n""" % system_prompt else: sys_msg = '' if sys_msg and not reduced: # too much safety, hurts accuracy promptA = promptB = sys_msg else: promptA = promptB = '' PreInput = None PreInstruct = "### User:\n" PreResponse = "\n### Assistant:\n" terminate_response = ['### Assistant:', "</s>"] chat_sep = '\n' chat_turn_sep = '\n\n' humanstr = '### User:' botstr = '### Assistant:' elif prompt_type in [PromptType.wizard3nospace.value, str(PromptType.wizard3nospace.value), PromptType.wizard3nospace.name]: # https://huggingface.co/WizardLM/WizardLM-13B-V1.2/discussions/3 preprompt = """A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.""" if not reduced else '' start = '' promptB = promptA = '%s%s' % (preprompt, start) PreInstruct = """USER: """ PreInput = None PreResponse = """ASSISTANT:""" terminate_response = [PreResponse] chat_turn_sep = chat_sep = '\n' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.one_shot.value, str(PromptType.one_shot.value), PromptType.one_shot.name]: promptA = promptB = """A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions. ### Human: Got any creative ideas for a 10 year old’s birthday? ### Assistant: Of course! Here are some creative ideas for a 10-year-old's birthday party: 1. Treasure Hunt: Organize a treasure hunt in your backyard or nearby park. Create clues and riddles for the kids to solve, leading them to hidden treasures and surprises. 2. Science Party: Plan a science-themed party where kids can engage in fun and interactive experiments. You can set up different stations with activities like making slime, erupting volcanoes, or creating simple chemical reactions. 3. Outdoor Movie Night: Set up a backyard movie night with a projector and a large screen or white sheet. Create a cozy seating area with blankets and pillows, and serve popcorn and snacks while the kids enjoy a favorite movie under the stars. 4. DIY Crafts Party: Arrange a craft party where kids can unleash their creativity. Provide a variety of craft supplies like beads, paints, and fabrics, and let them create their own unique masterpieces to take home as party favors. 5. Sports Olympics: Host a mini Olympics event with various sports and games. Set up different stations for activities like sack races, relay races, basketball shooting, and obstacle courses. Give out medals or certificates to the participants. 6. Cooking Party: Have a cooking-themed party where the kids can prepare their own mini pizzas, cupcakes, or cookies. Provide toppings, frosting, and decorating supplies, and let them get hands-on in the kitchen. 7. Superhero Training Camp: Create a superhero-themed party where the kids can engage in fun training activities. Set up an obstacle course, have them design their own superhero capes or masks, and organize superhero-themed games and challenges. 8. Outdoor Adventure: Plan an outdoor adventure party at a local park or nature reserve. Arrange activities like hiking, nature scavenger hunts, or a picnic with games. Encourage exploration and appreciation for the outdoors. Remember to tailor the activities to the birthday child's interests and preferences. Have a great celebration!""" if not reduced else '' PreInstruct = """ ### Human: """ PreInput = None PreResponse = """ ### Assistant:""" # but only allow terminate after prompt is found correctly, else can't terminate terminate_response = ['### Human:', '### Human: ', ' ### Human:', '### Assistant:'] chat_turn_sep = chat_sep = '\n' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.falcon_chat.value, str(PromptType.falcon_chat.value), PromptType.falcon_chat.name]: can_handle_system_prompt = True if system_prompt in [None, 'None', 'auto']: # automatic system_prompt = "You are an intelligent and helpful assistant." if system_prompt: sys_msg = "System: %s\n" % system_prompt else: sys_msg = '' if sys_msg and not reduced: # too much safety, hurts accuracy promptA = promptB = sys_msg else: promptA = promptB = '' PreInstruct = """User: """ PreInput = None PreResponse = """Falcon:""" terminate_response = ['\nUser:', "<|endoftext|>", " User:", "###"] chat_sep = '\n' chat_turn_sep = '\n' humanstr = PreInstruct botstr = PreResponse if making_context: # when making context, want it to appear as-if LLM generated, which starts with space after : PreResponse = botstr + ' ' elif prompt_type in [PromptType.mistral.value, str(PromptType.mistral.value), PromptType.mistral.name]: promptA = promptB = '' PreInput = None PreInstruct = "[INST] " if making_context and histi == 0 or not making_context and not reduced: PreInstruct = '<s>' + PreInstruct PreResponse = "[/INST]" terminate_response = ["[INST]", "</s>"] chat_sep = ' ' chat_turn_sep = '</s> ' humanstr = '[INST]' botstr = '[/INST]' if making_context: PreResponse += "" elif prompt_type in [PromptType.mixtral.value, str(PromptType.mixtral.value), PromptType.mixtral.name] or \ prompt_type in [PromptType.mixtralnosys.value, str(PromptType.mixtralnosys.value), PromptType.mixtralnosys.name]: if prompt_type in [PromptType.mixtral.value, str(PromptType.mixtral.value), PromptType.mixtral.name]: can_handle_system_prompt = True if system_prompt in [None, 'None', 'auto']: # automatic system_prompt = "You are an AI that follows instructions extremely well and as helpful as possible." if system_prompt: # sys_msg = """<|system|>\n%s""" % system_prompt sys_msg = """<<SYS>>\n%s\n<</SYS>>\n\n""" % system_prompt else: sys_msg = '' else: sys_msg = '' if sys_msg and not reduced: # too much safety, hurts accuracy promptA = promptB = sys_msg else: promptA = promptB = '' PreInput = None PreInstruct = "[INST] " if making_context and histi == 0 or not making_context and not reduced: PreInstruct = '<s> ' + PreInstruct PreResponse = "[/INST]" terminate_response = ["[INST]", "</s>"] chat_sep = ' ' chat_turn_sep = '</s> ' humanstr = '[INST]' botstr = '[/INST]' if making_context: PreResponse += "" elif prompt_type in [PromptType.zephyr0.value, str(PromptType.zephyr0.value), PromptType.zephyr0.name]: can_handle_system_prompt = True # https://huggingface.co/HuggingFaceH4/zephyr-7b-alpha#intended-uses--limitations # prompt_template = "<|system|>\n</s>\n<|user|>\n{query}</s>\n<|assistant|>\n" if system_prompt in [None, 'None', 'auto']: # automatic system_prompt = "You are an AI that follows instructions extremely well and as helpful as possible." if system_prompt: sys_msg = """<|system|>\n%s""" % system_prompt else: sys_msg = '' if sys_msg and not reduced: # too much safety, hurts accuracy promptA = promptB = sys_msg else: promptA = promptB = '' PreInput = None PreInstruct = "</s>\n<|user|>\n" PreResponse = "</s>\n<|assistant|>\n" terminate_response = ['<|assistant|>', "</s>"] chat_sep = '\n' chat_turn_sep = '</s>\n' humanstr = '<|user|>' botstr = '<|assistant|>' elif prompt_type in [PromptType.zephyr.value, str(PromptType.zephyr.value), PromptType.zephyr.name]: can_handle_system_prompt = True # fixed version of zephyr0, and passes tests, but doesn't take system prompt as well # https://huggingface.co/HuggingFaceH4/zephyr-7b-alpha#intended-uses--limitations # prompt_template = "<|system|>\n</s>\n<|user|>\n{query}</s>\n<|assistant|>\n" if system_prompt in [None, 'None', 'auto']: # automatic system_prompt = "You are an AI that follows instructions extremely well and as helpful as possible." if system_prompt: sys_msg = """<|system|>\n%s</s>\n""" % system_prompt else: sys_msg = '' if sys_msg and not reduced: # too much safety, hurts accuracy promptA = promptB = sys_msg else: promptA = promptB = '' PreInput = None PreInstruct = "<|user|>\n" PreResponse = "</s>\n<|assistant|>\n" terminate_response = ['<|assistant|>', "</s>"] chat_sep = '' chat_turn_sep = '</s>\n' humanstr = '<|user|>' botstr = '<|assistant|>' elif prompt_type in [PromptType.xwin.value, str(PromptType.xwin.value), PromptType.xwin.name]: can_handle_system_prompt = True # https://huggingface.co/Xwin-LM/Xwin-LM-13B-V0.1#huggingface-example if system_prompt in [None, 'None', 'auto']: system_prompt = "A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions." # space below intended preprompt = """%s """ % system_prompt if not reduced else '' start = '' promptB = promptA = '%s%s' % (preprompt, start) PreInstruct = """USER: """ PreInput = None PreResponse = """ASSISTANT:""" terminate_response = [PreResponse, 'ASSISTANT:', '</s>'] chat_turn_sep = '\n' # docs say multi-turn uses </s> but doesn't work, so use huggingface/vllm example chat_sep = '\n' # docs say multi-turn uses ' ' but doesn't work, so use huggingface/vllm example humanstr = PreInstruct botstr = PreResponse if making_context: PreResponse = botstr + ' ' elif prompt_type in [PromptType.xwincoder.value, str(PromptType.xwincoder.value), PromptType.xwincoder.name]: can_handle_system_prompt = True # https://github.com/Xwin-LM/Xwin-LM/blob/main/Xwin-Coder/online_chat.py#L38-L48 if system_prompt in [None, 'None', 'auto']: system_prompt = "You are an AI coding assistant that helps people with programming. Write a response that appropriately completes the user's request.\n" # space below intended preprompt = """<system>: %s\n""" % system_prompt if not reduced else '' start = '' promptB = promptA = '%s%s' % (preprompt, start) PreInstruct = """<user>: """ PreInput = None PreResponse = """<AI>:""" terminate_response = [PreResponse, '<AI>:', '</s>'] chat_turn_sep = '\n' # docs say multi-turn uses </s> but doesn't work, so use huggingface/vllm example chat_sep = '\n' # docs say multi-turn uses ' ' but doesn't work, so use huggingface/vllm example humanstr = PreInstruct botstr = PreResponse if making_context: PreResponse = botstr + ' ' elif prompt_type in [PromptType.xwinmath.value, str(PromptType.xwinmath.value), PromptType.xwinmath.name]: can_handle_system_prompt = True # https://huggingface.co/Xwin-LM/Xwin-Math-70B-V1.0#generate if system_prompt in [None, 'None', 'auto']: system_prompt = "A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions." # space below intended preprompt = """%s """ % system_prompt if not reduced else '' start = '' promptB = promptA = '%s%s' % (preprompt, start) PreInstruct = """USER: """ PreInput = None PreResponse = """Give your solution in detail. In the end, write your final answer in the format of 'The answer is: <ANSWER>.'. ASSISTANT:""" terminate_response = [PreResponse, 'ASSISTANT:', '</s>'] chat_turn_sep = '\n' # docs say multi-turn uses </s> but doesn't work, so use huggingface/vllm example chat_sep = '\n' # docs say multi-turn uses ' ' but doesn't work, so use huggingface/vllm example humanstr = PreInstruct botstr = PreResponse if making_context: PreResponse = botstr + ' ' elif prompt_type in [PromptType.mistralgerman.value, str(PromptType.mistralgerman.value), PromptType.mistralgerman.name]: can_handle_system_prompt = True # https://huggingface.co/TheBloke/em_german_leo_mistral-GPTQ#prompt-template-emgerman if system_prompt in [None, 'None', 'auto']: system_prompt = "Du bist ein hilfreicher" # space below intended preprompt = """%s """ % system_prompt if not reduced else '' start = '' promptB = promptA = '%s%s' % (preprompt, start) PreInstruct = """USER: """ PreInput = None PreResponse = """ASSISTANT:""" terminate_response = [PreResponse, 'ASSISTANT:', '</s>'] chat_turn_sep = '\n' chat_sep = '\n' humanstr = PreInstruct botstr = PreResponse if making_context: PreResponse = botstr + ' ' elif prompt_type in [PromptType.mistrallite.value, str(PromptType.mistrallite.value), PromptType.mistrallite.name]: # From added_tokens.json preprompt = '' prompt_tokens = "<|prompter|>" answer_tokens = "<|assistant|>" start = '' promptB = promptA = '%s%s' % (preprompt, start) PreInstruct = prompt_tokens PreInput = None PreResponse = answer_tokens pend = "<|prefix_end|>" eos = "</s>" humanstr = prompt_tokens botstr = answer_tokens terminate_response = [humanstr, PreResponse, pend, eos] chat_turn_sep = chat_sep = eos elif prompt_type in [PromptType.aquila.value, str(PromptType.aquila.value), PromptType.aquila.name]: can_handle_system_prompt = True # https://huggingface.co/BAAI/AquilaChat2-34B-16K/blob/main/predict.py#L197-L210 if system_prompt in [None, 'None', 'auto']: system_prompt = "A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions." promptA = promptB = "%s###" % system_prompt if not reduced else '' PreInstruct = """Human: """ PreInput = None PreResponse = """Assistant:""" terminate_response = ['###Human:', "###", "</s>", "[UNK]"] chat_turn_sep = '</s>' # turn-by-turn works with '' too chat_sep = '###' humanstr = PreInstruct botstr = PreResponse if making_context: PreResponse = botstr + ' ' elif prompt_type in [PromptType.aquila_simple.value, str(PromptType.aquila_simple.value), PromptType.aquila_simple.name]: can_handle_system_prompt = True # like aquila but less strictly correct (but less complex) for multi-turn if system_prompt in [None, 'None', 'auto']: system_prompt = "A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions." promptA = promptB = "%s" % system_prompt if not reduced else '' PreInstruct = """###Human: """ PreInput = None PreResponse = """###Assistant:""" terminate_response = ['###Human:', "###", "</s>", "[UNK]"] chat_turn_sep = '' chat_sep = '' humanstr = PreInstruct botstr = PreResponse if making_context: PreResponse = botstr + '' elif prompt_type in [PromptType.aquila_legacy.value, str(PromptType.aquila_legacy.value), PromptType.aquila_legacy.name]: can_handle_system_prompt = True if system_prompt in [None, 'None', 'auto']: system_prompt = "A chat between a curious human and an artificial intelligence assistant. " \ "The assistant gives helpful, detailed, and polite answers to the human's questions.\n\n" promptA = promptB = "%s" % system_prompt if not reduced else '' PreInstruct = """### Human: """ PreInput = None PreResponse = """### Assistant:""" terminate_response = ['### Human:', "</s>", "[UNK]"] chat_turn_sep = '</s>' chat_sep = '\n' humanstr = PreInstruct botstr = PreResponse if True: PreResponse = botstr + ' ' elif prompt_type in [PromptType.aquila_v1.value, str(PromptType.aquila_v1.value), PromptType.aquila_v1.name]: promptA = promptB = "" if not reduced else '' PreInstruct = """<|startofpiece|>""" PreInput = None PreResponse = """<|endofpiece|>""" terminate_response = ["</s>", "<|endoftext|>"] chat_turn_sep = '</s>' chat_sep = '' humanstr = PreInstruct botstr = PreResponse if making_context: PreResponse = botstr + '' elif prompt_type in [PromptType.deepseek_coder.value, str(PromptType.deepseek_coder.value), PromptType.deepseek_coder.name]: can_handle_system_prompt = True # https://huggingface.co/deepseek-ai/deepseek-coder-33b-instruct if system_prompt in [None, 'None', 'auto']: system_prompt = "<|begin▁of▁sentence|>You are an AI programming assistant, utilizing the Deepseek Coder model, developed by Deepseek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer\n" promptA = promptB = "%s" % system_prompt if not reduced else '' PreInput = None PreInstruct = "### Instruction:\n" PreResponse = "### Response:\n" eos = '<|end▁of▁sentence|>' terminate_response = [PreResponse, eos, '<|EOT|>'] chat_sep = '\n' chat_turn_sep = '\n<|EOT|>\n' humanstr = PreInstruct botstr = PreResponse if making_context: PreResponse += "" elif prompt_type in [PromptType.open_chat.value, str(PromptType.open_chat.value), PromptType.open_chat.name] or \ prompt_type in [PromptType.open_chat_correct.value, str(PromptType.open_chat_correct.value), PromptType.open_chat_correct.name] or \ prompt_type in [PromptType.open_chat_code.value, str(PromptType.open_chat_code.value), PromptType.open_chat_code.name] or \ prompt_type in [PromptType.open_chat_math.value, str(PromptType.open_chat_math.value), PromptType.open_chat_math.name]: # https://huggingface.co/TheBloke/openchat_3.5-GPTQ#prompt-template-openchat # https://github.com/imoneoi/openchat/tree/master#-inference-with-transformers # GPT4 Correct User: Hello<|end_of_turn|>GPT4 Correct Assistant: Hi<|end_of_turn|>GPT4 Correct User: How are you today?<|end_of_turn|>GPT4 Correct Assistant: # GPT4 User: {prompt}<|end_of_turn|>GPT4 Assistant: # GPT4 User: {prompt}<|end_of_turn|>GPT4 Assistant: # Code User: Implement quicksort using C++<|end_of_turn|>Code Assistant: promptA = promptB = "" # no apparent system prompt PreInput = None if prompt_type in [PromptType.open_chat.value, str(PromptType.open_chat.value), PromptType.open_chat.name]: PreInstruct = "GPT4 User: " PreResponse = "GPT4 Assistant:" elif prompt_type in [PromptType.open_chat_correct.value, str(PromptType.open_chat_correct.value), PromptType.open_chat_correct.name]: PreInstruct = "GPT4 Correct User: " PreResponse = "GPT4 Correct Assistant:" elif prompt_type in [PromptType.open_chat_math.value, str(PromptType.open_chat_math.value), PromptType.open_chat_math.name]: PreInstruct = "Math Correct User: " PreResponse = "Math Correct Assistant:" else: PreInstruct = "Code User: " PreResponse = "Code Assistant:" eos = '<|end_of_turn|>' terminate_response = [PreResponse, eos] chat_sep = eos chat_turn_sep = eos humanstr = PreInstruct botstr = PreResponse if making_context: PreResponse += " " elif prompt_type in [PromptType.jais.value, str(PromptType.jais.value), PromptType.jais.name]: can_handle_system_prompt = True # https://huggingface.co/core42/jais-30b-chat-v1 if system_prompt in [None, 'None', 'auto']: system_prompt = """Your name is Jais, and you are named after Jebel Jais, the highest mountain in UAE. You are built by Core42. You are the world's most advanced Arabic large language model with 30b parameters. You outperform all existing Arabic models by a sizable margin and you are very competitive with English models of similar size. You can answer in Arabic and English only. You are a helpful, respectful and honest assistant. When answering, abide by the following guidelines meticulously: Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, explicit, offensive, toxic, dangerous, or illegal content. Do not give medical, legal, financial, or professional advice. Never assist in or promote illegal activities. Always encourage legal and responsible actions. Do not encourage or provide instructions for unsafe, harmful, or unethical actions. Do not create or share misinformation or fake news. Please ensure that your responses are socially unbiased and positive in nature. If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information. Prioritize the well-being and the moral integrity of users. Avoid using toxic, derogatory, or offensive language. Maintain a respectful tone. Do not generate, promote, or engage in discussions about adult content. Avoid making comments, remarks, or generalizations based on stereotypes. Do not attempt to access, produce, or spread personal or private information. Always respect user confidentiality. Stay positive and do not say bad things about anything. Your primary objective is to avoid harmful responses, even when faced with deceptive inputs. Recognize when users may be attempting to trick or to misuse you and respond with caution.\n\nComplete the conversation below between""" promptA = promptB = "### Instruction: %s [|Human|] and [|AI|]:" % system_prompt if not reduced else "" PreInstruct = """\n### Input: [|Human|] """ PreInput = None PreResponse = """\n### Response: [|AI|]""" if making_context: PreResponse += " " terminate_response = [PreResponse, PreInstruct] chat_turn_sep = chat_sep = '' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.yi.value, str(PromptType.yi.value), PromptType.yi.name]: can_handle_system_prompt = True # https://huggingface.co/01-ai/Yi-34B-Chat#31-use-the-chat-model if system_prompt in [None, 'None', 'auto']: system_prompt = "A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers." promptA = promptB = """<|im_start|>system\n%s<|im_end|>""" % system_prompt if not reduced else '' PreInstruct = """\n<|im_start|>user\n""" PreInput = None PreResponse = """<|im_end|>\n<|im_start|>assistant\n""" terminate_response = ['<|im_end|>', '<|endotftext|>'] chat_sep = '' chat_turn_sep = '<|im_end|>' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.docsgpt.value, str(PromptType.docsgpt.value), PromptType.docsgpt.name]: # https://huggingface.co/Arc53/docsgpt-7b-mistral can_handle_system_prompt = True if system_prompt in [None, 'None', 'auto']: system_prompt = "Below is an instruction that describes a task. Write a response that appropriately completes the request." promptA = promptB = '' PreInstruct = """### Instruction\n""" PreInput = None PreResponse = """### Answer\n""" terminate_response = ['### Answer', '### Instruction'] chat_turn_sep = chat_sep = '\n' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.orion.value, str(PromptType.orion.value), PromptType.orion.name]: can_handle_system_prompt = False # OrionStarAI/Orion-14B-Chat-RAG # https://huggingface.co/OrionStarAI/Orion-14B-Chat-RAG/blob/main/generation_utils.py#L6-L8 # # chat format: # # single-turn: <s>Human: Hello!\n\nAssistant: </s> # # multi-turn: <s>Human: Hello!\n\nAssistant: </s>Hi!</s>Human: How are you?\n\nAssistant: </s>I'm fine</s> promptA = promptB = '' PreInstruct = """<s>Human: """ if not reduced or histi == 0 else """</s>Human: """ PreInput = None eos = "</s>" PreResponse = """\n\nAssistant: %s""" % eos terminate_response = ['Human:', eos, "[UNK]", "Assistant:"] chat_turn_sep = '' chat_sep = '' humanstr = PreInstruct botstr = PreResponse if making_context: PreResponse = botstr + '' elif prompt_type in [PromptType.sciphi.value, str(PromptType.sciphi.value), PromptType.sciphi.name]: can_handle_system_prompt = True if system_prompt in [None, 'None', 'auto']: # automatic system_prompt = "A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers." if system_prompt: sys_msg = """### System:\n%s\n\n""" % system_prompt else: sys_msg = '' if sys_msg and not reduced: # too much safety, hurts accuracy promptA = promptB = sys_msg else: promptA = promptB = '' PreInput = None PreInstruct = "### Instruction:\n" PreResponse = "\n### Response:\n" terminate_response = ['### Response:', "</s>", "### Instruction:"] chat_sep = '\n' chat_turn_sep = '\n\n' humanstr = '### Instruction:' botstr = '### Response:' elif prompt_type in [PromptType.beacon.value, str(PromptType.beacon.value), PromptType.beacon.name]: can_handle_system_prompt = False promptA = promptB = '' PreInput = None PreInstruct = "\nQuestion: " PreResponse = "\nAnswer:" terminate_response = ["Question:", "</s>", "Answer:"] chat_sep = '\n' chat_turn_sep = '\n\n' humanstr = 'Question:' botstr = 'Answer:' if making_context: PreResponse += " " elif prompt_type in [PromptType.beacon2.value, str(PromptType.beacon2.value), PromptType.beacon2.name]: can_handle_system_prompt = False promptA = promptB = '' PreInput = None PreInstruct = "" PreResponse = "" terminate_response = ["</s>"] chat_sep = '\n' chat_turn_sep = '\n\n' humanstr = 'Question:' botstr = 'Answer:' if making_context: PreResponse += " " elif prompt_type in [PromptType.gemma.value, str(PromptType.gemma.value), PromptType.gemma.name]: can_handle_system_prompt = True # so not part of pre-conversation if making_context and histi == 0 or not making_context and not reduced: prompt_tokens = "<bos><start_of_turn>user\n" else: prompt_tokens = "<start_of_turn>user\n" answer_tokens = "<end_of_turn>\n<start_of_turn>model\n" if system_prompt in [None, 'None', 'auto']: system_prompt = "I am Gemma, a conversational chat assistant developed by Google" promptA = promptB = system_prompt if not reduced else '' PreInstruct = prompt_tokens PreInput = None PreResponse = answer_tokens humanstr = prompt_tokens botstr = answer_tokens chat_turn_sep = '<end_of_turn>\n' terminate_response = [humanstr, PreResponse, '<bos>', '<end_of_turn>'] chat_sep = '' elif prompt_type in [PromptType.qwen.value, str(PromptType.qwen.value), PromptType.qwen.name]: can_handle_system_prompt = True # https://huggingface.co/TheBloke/mpt-30B-chat-GGML#prompt-template if system_prompt in [None, 'None', 'auto']: system_prompt = "A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers." promptA = promptB = """<|im_start|>system\n%s<|im_end|>\n""" % system_prompt if not reduced else '' PreInstruct = """<|im_start|>user\n""" PreInput = None PreResponse = """<|im_end|>\n<|im_start|>assistant\n""" terminate_response = ['<|im_end|>'] chat_sep = '' chat_turn_sep = '<|im_end|>\n' humanstr = PreInstruct botstr = PreResponse elif prompt_type in [PromptType.sealion.value, str(PromptType.sealion.value), PromptType.sealion.name]: can_handle_system_prompt = False promptA = promptB = '' PreInput = None PreInstruct = "### USER:\n" PreResponse = "\n\n### RESPONSE:\n" terminate_response = ['### RESPONSE:', "</s>", "<|endoftext|>"] chat_sep = '\n' chat_turn_sep = '\n\n' humanstr = '### USER:' botstr = '### RESPONSE:' else: raise RuntimeError("No such prompt_type=%s" % prompt_type) if isinstance(terminate_response, (tuple, list)): assert '' not in terminate_response, "Bad terminate_response" if system_prompt == 'auto': # if still auto, then safest then to just avoid system prompt system_prompt = '' ret_dict = dict(promptA=promptA, promptB=promptB, PreInstruct=PreInstruct, PreInput=PreInput, PreResponse=PreResponse, terminate_response=terminate_response, chat_sep=chat_sep, chat_turn_sep=chat_turn_sep, humanstr=humanstr, botstr=botstr, generates_leading_space=generates_leading_space, system_prompt=system_prompt, can_handle_system_prompt=can_handle_system_prompt, ) if return_dict: return ret_dict, prompt_dict_error else: return tuple(list(ret_dict.values())) def inject_chatsep(prompt_type, prompt, chat_sep=None): if chat_sep: # only add new line if structured prompt, while 'plain' is just generation of next tokens from input prompt += chat_sep return prompt def generate_prompt(data_point, prompt_type, prompt_dict, reduced, making_context, system_prompt=None, histi=-1): context = data_point.get('context') if context is None: context = '' instruction = data_point.get('instruction') input = data_point.get('input') output = data_point.get('output') prompt_type = data_point.get('prompt_type', prompt_type) prompt_dict = data_point.get('prompt_dict', prompt_dict) assert prompt_type in prompt_types, "Bad prompt type: %s" % prompt_type promptA, promptB, PreInstruct, PreInput, PreResponse, \ terminate_response, chat_sep, chat_turn_sep, humanstr, botstr, \ generates_leading_space, system_prompt, can_handle_system_prompt = \ get_prompt(prompt_type, prompt_dict, context, reduced, making_context, system_prompt=system_prompt, histi=histi) # could avoid if reduce=True, but too complex for parent functions to handle prompt = context if input and promptA: prompt += f"""{promptA}""" elif promptB: prompt += f"""{promptB}""" if instruction and PreInstruct is not None and input and PreInput is not None: prompt += f"""{PreInstruct}{instruction}{PreInput}{input}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) elif instruction and input and PreInstruct is None and PreInput is not None: prompt += f"""{PreInput}{instruction} {input}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) elif input and instruction and PreInput is None and PreInstruct is not None: prompt += f"""{PreInstruct}{instruction} {input}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) elif instruction and PreInstruct is not None: prompt += f"""{PreInstruct}{instruction}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) elif input and PreInput is not None: prompt += f"""{PreInput}{input}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) elif input and instruction and PreInput is not None: prompt += f"""{PreInput}{instruction}{input}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) elif input and instruction and PreInstruct is not None: prompt += f"""{PreInstruct}{instruction}{input}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) elif input and instruction: # i.e. for simple_instruct prompt += f"""{instruction}: {input}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) elif input: prompt += f"""{input}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) elif instruction: prompt += f"""{instruction}""" prompt = inject_chatsep(prompt_type, prompt, chat_sep=chat_sep) if PreResponse is not None: prompt += f"""{PreResponse}""" pre_response = PreResponse # Don't use strip else: pre_response = '' if output: prompt += f"""{output}""" return prompt, pre_response, terminate_response, chat_sep, chat_turn_sep
null
167,133
import ast import time from enums import PromptType, gpt_token_mapping, \ anthropic_mapping, google_mapping, mistralai_mapping def get_vllm_extra_dict(tokenizer, stop_sequences=[], repetition_penalty=None): stop_token_ids = [tokenizer.added_tokens_encoder[x] for x in stop_sequences if hasattr(tokenizer, 'added_tokens_encoder') and x in tokenizer.added_tokens_encoder] if hasattr(tokenizer, 'eos_token_id'): stop_token_ids.extend([tokenizer.eos_token_id]) vllm_extra_dict = dict(extra_body=dict(stop_token_ids=stop_token_ids)) if repetition_penalty is not None: vllm_extra_dict['extra_body'].update(repetition_penalty=repetition_penalty) return vllm_extra_dict
null
167,134
import ast import time from enums import PromptType, gpt_token_mapping, \ anthropic_mapping, google_mapping, mistralai_mapping def step_forward_prompts(which): if which == 1: return """Let’s think step by step.""" elif which == 2: return """Take a deep breath and work on this problem step-by-step.""" elif which == 3: return """Break this down.""" elif which == 4: return """A little bit of arithmetic and a logical approach will help us quickly arrive at the solution to this problem.""" elif which == 5: return """Let’s combine our numerical command and clear thinking to quickly and accurately decipher the answer.""" elif which == 6: return """Let’s work together to solve math word problems! First, we will read and discuss the problem together to make sure we understand it. Then, we will work together to find the solution. I will give you hints and help you work through the problem if you get stuck.""" def step_back_prompts(which): gen1 = """List a much more general abstract versions of this question, then describe the situation using your imagination ensuring not to over-constrain the problem, then explore in a list all the possible different constraints or lack of constraints (be sure to consider from a human viewpoint) relevant for the circumstance, then explore in a list the many extreme possibilities for issues. Finally, let's work this out in a step-by-step way to be sure we have the right answer. Make a final best guess using common sense.""" gen2 = """List a much more general abstract versions of this question, then describe the situation using your imagination ensuring not to over-constrain the problem, then explore in a list all the possible different constraints or lack of constraints (be sure to consider from a human viewpoint) relevant for the circumstance, then explore in a list the many extreme possibilities for issues. Let's work this out in a well-structured step-by-step thoughtful way to be sure we have the right answer. Make a final best guess using common sense.""" gen3 = """Respond as follows: 1) Restate the question in elaborate form. 2) Give an abstract version of the question. 3) Provide a detailed highly-accurate and well-structured response to the user's question. 4) Give a detailed highly-accurate and well-structured justification for the response. 5) Evaluate your response with a score of 0 through 10. 10 means the justification perfectly explains the response to the question and the response is perfectly accurate, 5 means the response and justification might contain some errors, 0 means the response is not accurate or is not well-justified. """ if which == 0: return f"""You are a very helpful expert at the topic of the question. {gen2}""" elif which == 1: return f"""You are a mathematician or physicist. {gen1}""" elif which == 2: return f"""You are a mathematician or physicist. {gen2}""" elif which == 3: return f"""You are a very helpful expert at the topic of the question. {gen3}""" else: raise ValueError("No such case for back prompts which=%d" % which) system_generic = """A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.""" system_docqa = """You are an expert document question-answer language model named GPT-4 Turbo created by OpenAI. You will get a tip of $200 when you answer correctly the questions and only use the document context given. I may lose my job if your answers are inaccurate or do a poor job of using the documents in the context.""" system_python_tutor = """You are a Python Tutor AI, dedicated to helping users learn Python and build end-to-end projects using Python and its related libraries. Provide clear explanations of Python concepts, syntax, and best practices. Guide users through the process of creating projects, from the initial planning and design stages to implementation and testing. Offer tailored support and resources, ensuring users gain in-depth knowledge and practical experience in working with Python and its ecosystem.""" system_ml_tutor = """You are a Machine Learning Tutor AI, dedicated to guiding senior software engineers in their journey to become proficient machine learning engineers. Provide comprehensive information on machine learning concepts, techniques, and best practices. Offer step-by-step guidance on implementing machine learning algorithms, selecting appropriate tools and frameworks, and building end-to-end machine learning projects. Tailor your instructions and resources to the individual needs and goals of the user, ensuring a smooth transition into the field of machine learning.""" system_coding = """You are an AI programming assistant. Follow the user's requirements carefully and to the letter. First, think step-by-step and describe your plan for what to build in pseudocode, written out in great detail. Then, output the code in a single code block. Minimize any other prose.""" system_know_math = """Follow these steps in solving any problem: 1) Know: This will help students find the important information. 2) Need to Know: This will force students to reread the question and write down what they are trying to solve for. 3) Organize: I think this would be a great place for teachers to emphasize drawing a model or picture. 4) Work: Students show their calculations here. 5) Solution: This is where students will ask themselves if the answer is reasonable and whether it answered the question. """ system_algebra = """The fundamentals of algebra teach students how to apply algebraic concepts to elementary mathematical operations such as addition, subtraction, multiplication, and division using both constants and variables. For example, x + 10 = 0. Equations, a fundamental concept in algebra, are presented here as an example of this. The algebraic equation can be conceptualised as a scale, with the “weights” being represented by numbers or constants, and the scale is balanced. In algebra, letters of the alphabet are substituted for numbers in order to solve mathematical problems. Algebra is a subfield of mathematics. These alphabetic characters are also referred to as variables. The values, such as numbers, that are known to be present in the expression being evaluated are referred to as constants. The concept of algebra at the potential level will be taught to students even though they are in higher-level classes. However, when we talk about its fundamentals, it encompasses the general algebraic expressions, formulas, and identities that are used to solve a wide variety of mathematical issues. Algebra Basics In order for us to understand the fundamentals of algebra, it is necessary for us to be familiar with the terminology that is associated with it. An expression known as an algebraic equation contains a variable, an operator, an exponent, a coefficient, and a constant, as well as the symbol for equal to connect all of these components together. Let us take an equation, ax2 + bx + c = d. When doing algebra, you begin by writing the term that has the highest exponent, and then you write the subsequent terms with reducing powers. There are four terms in the equation ax2 + bx + c = d, which can be seen above. An algebraic equation may contain different terms that are the same or different from one another. When solving an equation, like terms are terms that have the same variables and exponents. On the other hand, terms in an equation that are dissimilar to one another constitute distinct variables and exponents. Algebra Rules There are five fundamental rules that makeup algebra. They are as follows: 1) Commutative Rule of Addition The commutative rule of addition is a fundamental concept in algebra. According to this rule, the order in which two terms are added together does not affect the final result. (a+ b) =(b+ a) is the equation that describes the same thing. For example, (x3 + 2x) = (2x + x3) 2) Commutative Rule of Multiplication According to the commutative rule of multiplication, when multiplying two terms, it does not make a difference which orders the multiplication is performed in (a.b) = (b.a) is the equation that describes the same thing mathematically. For example, (x4 – 2x) × 3x = 3x × (x4 – 2x). LHS = (x4 – 2x) × 3x = (3x5 – 6x2) RHS = 3x × (x4 – 2x) = (3x5 – 6x2) Since the left-hand side (LHS) equals the right-hand side (RHS), this demonstrates that the two sets of values are comparable. 3) Associative Rule of Addition According to the associative rule of addition in algebra, when three or more terms are added together, it does not matter what order the additions are performed in. The corresponding equation is written as follows: a + (b + c) = (a + b) + c. For example, x5 + (3x2 + 2) = (x5 + 3x2) + 2 4) Multiplication according to the Associative Rule In a similar vein, the associative rule of multiplication states that it does not make a difference in which order the terms are multiplied when there are three or more terms being multiplied together. The corresponding equation is written as follows: a plus (b plus c) equals (a plus b) plus c. For example, x3 × (2x4 × x) = (x3 × 2x4) × x. 5) Distributive Rule of Multiplication. According to the distributive rule of multiplication, the answer that we get when we multiply a number by the addition of two other numbers should be the same as the sum of the products those numbers have when they are multiplied by the number on their own. This demonstrates the prevalence of multiplication in comparison to addition. The corresponding equation reads as follows: a x (b + c) = (a.b) +(a .c). For example, x2× (2x + 1) = (x2 × 2x) + (x2× 1). """ system_problem_solve = """8-Step Problem Solving Process: Step 1: Define the Problem. What is the problem? Step 2: Clarify the Problem. Step 3: Define the Goals. Step 4: Identify Root Cause of the Problem. Step 5: Develop Action Plan. Step 6: Execute Action Plan. Step 7: Evaluate the Results. Step 8: Continuously Improve. """ system_problem_solve_full = """Steps for solving any problem: Step 1: Define the Problem What is the problem? How did you discover the problem? When did the problem start and how long has this problem been going on? Is there enough data available to contain the problem and prevent it from getting passed to the next process step? If yes, contain the problem. Step 2: Clarify the Problem What data is available or needed to help clarify, or fully understand the problem? Is it a top priority to resolve the problem at this point in time? Are additional resources required to clarify the problem? If yes, elevate the problem to your leader to help locate the right resources and form a team. Consider a Lean Event (Do-it, Burst, RPI, Project). ∙Ensure the problem is contained and does not get passed to the next process step. Step 3: Define the Goals What is your end goal or desired future state? What will you accomplish if you fix this problem? What is the desired timeline for solving this problem? Step 4: Identify Root Cause of the Problem Identify possible causes of the problem. Prioritize possible root causes of the problem. What information or data is there to validate the root cause? Step 5: Develop Action Plan Generate a list of actions required to address the root cause and prevent problem from getting to others. Assign an owner and timeline to each action. Status actions to ensure completion. Step 6: Execute Action Plan Implement action plan to address the root cause. Verify actions are completed. Step 7: Evaluate the Results Monitor and Collect Data. Did you meet your goals defined in step 3? If not, repeat the 8-Step Process. Were there any unforeseen consequences? If problem is resolved, remove activities that were added previously to contain the problem. Step 8: Continuously Improve Look for additional opportunities to implement solution. Ensure problem will not come back and communicate lessons learned. If needed, repeat the 8-Step Problem Solving Process to drive further improvements. """ def get_system_prompts(): return [('None', ''), ('Auto', 'auto'), ('Generic', system_generic), ('DocQA', system_docqa), ('Coding', system_coding), ('PythonTutor', system_python_tutor), ('MLTutor', system_ml_tutor), ('CoT', step_forward_prompts(2)), ('Math', step_forward_prompts(6)), ('MathSteps', system_know_math), ('Algebra', system_algebra), ('ProblemSolve', system_problem_solve), ('ProblemSolveFull', system_problem_solve_full), ('StepBackSimple', step_back_prompts(0)), ('StepBackFull', step_back_prompts(3)), ]
null
167,135
import ast import time from enums import PromptType, gpt_token_mapping, \ anthropic_mapping, google_mapping, mistralai_mapping def get_llava_prompts(): return [('None', ''), ('Auto', 'auto'), ('Generic', "Describe the image and what does the image say?"), ('OCR', "Read all text from the image, keeping any structure"), ('Ignore', "Ignore -- for https://github.com/gradio-app/gradio/issues/6957"), ]
null
167,142
import os import filelock from diffusers import DiffusionPipeline import torch from src.utils import makedirs from src.vision.sdxl import get_device def get_pipe_make_image(gpu_id, refine=True): device = get_device(gpu_id) base = DiffusionPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16, use_safetensors=True, add_watermarker=False, variant="fp16" ).to(device) if not refine: refiner = None else: refiner = DiffusionPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-refiner-1.0", text_encoder_2=base.text_encoder_2, vae=base.vae, torch_dtype=torch.float16, use_safetensors=True, variant="fp16", ).to(device) return base, refiner def makedirs(path, exist_ok=True, tmp_ok=False, use_base=False): """ Avoid some inefficiency in os.makedirs() :param path: :param exist_ok: :param tmp_ok: use /tmp if can't write locally :param use_base: :return: """ if path is None: return path # if base path set, make relative to that, unless user_path absolute path if use_base: if os.path.normpath(path) == os.path.normpath(os.path.abspath(path)): pass else: if os.getenv('H2OGPT_BASE_PATH') is not None: base_dir = os.path.normpath(os.getenv('H2OGPT_BASE_PATH')) path = os.path.normpath(path) if not path.startswith(base_dir): path = os.path.join(os.getenv('H2OGPT_BASE_PATH', ''), path) path = os.path.normpath(path) if os.path.isdir(path) and os.path.exists(path): assert exist_ok, "Path already exists" return path try: os.makedirs(path, exist_ok=exist_ok) return path except FileExistsError: # e.g. soft link return path except PermissionError: if tmp_ok: path0 = path path = os.path.join('/tmp/', path) print("Permission denied to %s, using %s instead" % (path0, path), flush=True) os.makedirs(path, exist_ok=exist_ok) return path else: raise def make_image(prompt, filename=None, gpu_id='auto', pipe=None, guidance_scale=3.0): if pipe is None: base, refiner = get_pipe_make_image(gpu_id=gpu_id) else: base, refiner = pipe lock_type = 'image' base_path = os.path.join('locks', 'image_locks') 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 with filelock.FileLock(lock_file): # Define how many steps and what % of steps to be run on each experts (80/20) here n_steps = 40 high_noise_frac = 0.8 # run both experts image = base( prompt=prompt, num_inference_steps=n_steps, denoising_end=high_noise_frac, output_type="latent", ).images image = refiner( prompt=prompt, num_inference_steps=n_steps, denoising_start=high_noise_frac, image=image, ).images[0] if filename: image.save(filename) return filename return image
null
167,143
import os import filelock import torch from diffusers import AutoPipelineForImage2Image, AutoPipelineForText2Image from diffusers.utils import load_image from src.utils import cuda_vis_check, makedirs def get_pipe_make_image(gpu_id='auto'): # https://huggingface.co/stabilityai/sdxl-turbo device = get_device(gpu_id) pipe = AutoPipelineForText2Image.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16").to(device) return pipe def makedirs(path, exist_ok=True, tmp_ok=False, use_base=False): """ Avoid some inefficiency in os.makedirs() :param path: :param exist_ok: :param tmp_ok: use /tmp if can't write locally :param use_base: :return: """ if path is None: return path # if base path set, make relative to that, unless user_path absolute path if use_base: if os.path.normpath(path) == os.path.normpath(os.path.abspath(path)): pass else: if os.getenv('H2OGPT_BASE_PATH') is not None: base_dir = os.path.normpath(os.getenv('H2OGPT_BASE_PATH')) path = os.path.normpath(path) if not path.startswith(base_dir): path = os.path.join(os.getenv('H2OGPT_BASE_PATH', ''), path) path = os.path.normpath(path) if os.path.isdir(path) and os.path.exists(path): assert exist_ok, "Path already exists" return path try: os.makedirs(path, exist_ok=exist_ok) return path except FileExistsError: # e.g. soft link return path except PermissionError: if tmp_ok: path0 = path path = os.path.join('/tmp/', path) print("Permission denied to %s, using %s instead" % (path0, path), flush=True) os.makedirs(path, exist_ok=exist_ok) return path else: raise def make_image(prompt, filename=None, gpu_id='auto', pipe=None): if pipe is None: pipe = get_pipe_make_image(gpu_id=gpu_id) lock_type = 'image' base_path = os.path.join('locks', 'image_locks') 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 with filelock.FileLock(lock_file): image = pipe(prompt=prompt, num_inference_steps=1, guidance_scale=0.0).images[0] if filename: image.save(filename) return filename return image
null
167,145
import os import uuid from src.utils import makedirs, sanitize_filename, get_gradio_tmp def sanitize_filename(name, file_length_limit=250): """ Sanitize file *base* names. :param name: name to sanitize :param file_length_limit: bit smaller than 256 for safety :return: """ bad_chars = ['[', ']', ',', '/', '\\', '\\w', '\\s', '-', '+', '\"', '\'', '>', '<', ' ', '=', ')', '(', ':', '^'] for char in bad_chars: name = name.replace(char, "_") length = len(name) sha_length = 32 real_length_limit = file_length_limit - (sha_length + 2) assert real_length_limit > 0, "Bad file limit length: %s %s" % (file_length_limit, real_length_limit) if length > file_length_limit: sha = get_sha(name) half_real_length_limit = max(1, int(real_length_limit / 2)) name = name[0:half_real_length_limit] + "_" + sha + "_" + name[length - half_real_length_limit:length] return name def makedirs(path, exist_ok=True, tmp_ok=False, use_base=False): """ Avoid some inefficiency in os.makedirs() :param path: :param exist_ok: :param tmp_ok: use /tmp if can't write locally :param use_base: :return: """ if path is None: return path # if base path set, make relative to that, unless user_path absolute path if use_base: if os.path.normpath(path) == os.path.normpath(os.path.abspath(path)): pass else: if os.getenv('H2OGPT_BASE_PATH') is not None: base_dir = os.path.normpath(os.getenv('H2OGPT_BASE_PATH')) path = os.path.normpath(path) if not path.startswith(base_dir): path = os.path.join(os.getenv('H2OGPT_BASE_PATH', ''), path) path = os.path.normpath(path) if os.path.isdir(path) and os.path.exists(path): assert exist_ok, "Path already exists" return path try: os.makedirs(path, exist_ok=exist_ok) return path except FileExistsError: # e.g. soft link return path except PermissionError: if tmp_ok: path0 = path path = os.path.join('/tmp/', path) print("Permission denied to %s, using %s instead" % (path0, path), flush=True) os.makedirs(path, exist_ok=exist_ok) return path else: raise def get_gradio_tmp(): gradio_tmp = '/tmp/gradio' makedirs(gradio_tmp, exist_ok=True) # won't hurt if soft link if exists gradio_tmp = os.path.realpath(gradio_tmp) return gradio_tmp def extract_unique_frames(urls=None, file=None, download_dir=None, export_dir=None, extract_frames=10): download_dir = download_dir or os.getenv('VID_DOWNLOADS', "viddownloads") download_dir = os.path.join(download_dir, str(uuid.uuid4())) # os.environ['FIFTYONE_DISABLE_SERVICES'] = 'True' if urls: import fiftyone.utils.youtube as fouy fouy.download_youtube_videos(urls, download_dir=download_dir) # Create a FiftyOne Dataset import fiftyone as fo if file: dataset = fo.Dataset.from_videos([file]) else: dataset = fo.Dataset.from_videos_dir(download_dir) # Convert videos to images, sample 1 frame per second frame_view = dataset.to_frames(sample_frames=True, fps=1) import fiftyone.brain as fob # Index images by similarity results = fob.compute_similarity(frame_view, brain_key="frame_sim") # Find maximally unique frames num_unique = extract_frames # Scale this to whatever you want results.find_unique(num_unique) unique_view = frame_view.select(results.unique_ids) # Visualize in the App # session = fo.launch_app(frame_view) # session = fo.launch_app(unique_view) san_file = sanitize_filename(os.path.basename(file)) if file else None gradio_tmp = get_gradio_tmp() if san_file: export_dir = export_dir or os.path.join(gradio_tmp, "extraction_%s" % san_file) if os.path.isdir(export_dir): export_dir += "_%s" % str(uuid.uuid4()) else: export_dir = export_dir or os.path.join(gradio_tmp, "extraction_%s" % str(uuid.uuid4())) makedirs(export_dir, exist_ok=True) unique_view.export(export_dir, dataset_type=fo.types.VideoDirectory) return export_dir
null
167,146
import base64 import os import time import uuid from io import BytesIO import numpy as np def img_to_base64(image_file): # assert image_file.lower().endswith('jpg') or image_file.lower().endswith('jpeg') from PIL import Image EXTENSIONS = {'.png': 'PNG', '.apng': 'PNG', '.blp': 'BLP', '.bmp': 'BMP', '.dib': 'DIB', '.bufr': 'BUFR', '.cur': 'CUR', '.pcx': 'PCX', '.dcx': 'DCX', '.dds': 'DDS', '.ps': 'EPS', '.eps': 'EPS', '.fit': 'FITS', '.fits': 'FITS', '.fli': 'FLI', '.flc': 'FLI', '.fpx': 'FPX', '.ftc': 'FTEX', '.ftu': 'FTEX', '.gbr': 'GBR', '.gif': 'GIF', '.grib': 'GRIB', '.h5': 'HDF5', '.hdf': 'HDF5', '.jp2': 'JPEG2000', '.j2k': 'JPEG2000', '.jpc': 'JPEG2000', '.jpf': 'JPEG2000', '.jpx': 'JPEG2000', '.j2c': 'JPEG2000', '.icns': 'ICNS', '.ico': 'ICO', '.im': 'IM', '.iim': 'IPTC', '.jfif': 'JPEG', '.jpe': 'JPEG', '.jpg': 'JPEG', '.jpeg': 'JPEG', '.tif': 'TIFF', '.tiff': 'TIFF', '.mic': 'MIC', '.mpg': 'MPEG', '.mpeg': 'MPEG', '.mpo': 'MPO', '.msp': 'MSP', '.palm': 'PALM', '.pcd': 'PCD', '.pdf': 'PDF', '.pxr': 'PIXAR', '.pbm': 'PPM', '.pgm': 'PPM', '.ppm': 'PPM', '.pnm': 'PPM', '.psd': 'PSD', '.qoi': 'QOI', '.bw': 'SGI', '.rgb': 'SGI', '.rgba': 'SGI', '.sgi': 'SGI', '.ras': 'SUN', '.tga': 'TGA', '.icb': 'TGA', '.vda': 'TGA', '.vst': 'TGA', '.webp': 'WEBP', '.wmf': 'WMF', '.emf': 'WMF', '.xbm': 'XBM', '.xpm': 'XPM'} from pathlib import Path ext = Path(image_file).suffix if ext in EXTENSIONS: iformat = EXTENSIONS[ext] else: raise ValueError("Invalid file extension %s for file %s" % (ext, image_file)) image = Image.open(image_file) buffered = BytesIO() image.save(buffered, format=iformat) img_str = base64.b64encode(buffered.getvalue()) # FIXME: unsure about below img_str = str(bytes("data:image/%s;base64," % iformat.lower(), encoding='utf-8') + img_str) return img_str
null
167,147
import base64 import os import time import uuid from io import BytesIO import numpy as np def base64_to_img(img_str, output_path): # Split the string on "," to separate the metadata from the base64 data meta, base64_data = img_str.split(",", 1) # Extract the format from the metadata img_format = meta.split(';')[0].split('/')[-1] # Decode the base64 string to bytes img_bytes = base64.b64decode(base64_data) # Create output file path with the correct format extension output_file = f"{output_path}.{img_format}" # Write the bytes to a file with open(output_file, "wb") as f: f.write(img_bytes) print(f"Image saved to {output_file} with format {img_format}") return output_file
null
167,148
import base64 import os import time import uuid from io import BytesIO import numpy as np def fix_llava_prompt(file, prompt, allow_prompt_auto=True): if prompt in ['auto', None] and allow_prompt_auto: prompt = "Describe the image and what does the image say?" # prompt = "According to the image, describe the image in full details with a well-structured response." if file in ['', None]: # let model handle if no prompt and no file prompt = '' # allow prompt = '', will describe image by default if prompt is None: if os.environ.get('HARD_ASSERTS'): raise ValueError('prompt is None') else: prompt = '' return prompt def llava_prep(file, llava_model, image_model='llava-v1.6-vicuna-13b', client=None): prefix = '' if llava_model.startswith('http://'): prefix = 'http://' if llava_model.startswith('https://'): prefix = 'https://' llava_model = llava_model[len(prefix):] llava_model_split = llava_model.split(':') assert len(llava_model_split) >= 2 # FIXME: Allow choose model in UI if len(llava_model_split) >= 2: pass # assume default model is ok # llava_ip = llava_model_split[0] # llava_port = llava_model_split[1] if len(llava_model_split) >= 3: image_model = llava_model_split[2] llava_model = ':'.join(llava_model_split[:2]) # add back prefix llava_model = prefix + llava_model if client is None: from gradio_utils.grclient import GradioClient client = GradioClient(llava_model, check_hash=False, serialize=True) client.setup() assert image_model, "No image model specified" if isinstance(file, np.ndarray): from PIL import Image im = Image.fromarray(file) file = "%s.jpeg" % str(uuid.uuid4()) im.save(file) return image_model, client, file def get_llava_stream(file, llava_model, prompt=None, chat_conversation=[], allow_prompt_auto=False, image_model='llava-v1.6-vicuna-13b', temperature=0.2, top_p=0.7, max_new_tokens=512, image_process_mode="Default", include_image=False, client=None, verbose_level=0, max_time=None, force_stream=True, # dummy arg ): image_model = os.path.basename(image_model) # in case passed HF link prompt = fix_llava_prompt(file, prompt, allow_prompt_auto=allow_prompt_auto) image_model, client, file = \ llava_prep(file, llava_model, image_model=image_model, client=client) job = client.submit(prompt, chat_conversation, file, image_process_mode, include_image, image_model, temperature, top_p, max_new_tokens, api_name='/textbox_api_submit') t0 = time.time() job_outputs_num = 0 text = '' while not job.done(): if verbose_level == 2: print("Inside: %s" % llava_model, time.time() - t0, flush=True) if max_time is not None and time.time() - t0 > max_time: return text outputs_list = job.outputs().copy() job_outputs_num_new = len(outputs_list[job_outputs_num:]) for num in range(job_outputs_num_new): res = outputs_list[job_outputs_num + num] if verbose_level == 2: print('Stream %d: %s' % (num, res), flush=True) elif verbose_level == 1: print('Stream %d' % (job_outputs_num + num), flush=True) if res and len(res[0]) > 0: text = res[-1][-1] yield text job_outputs_num += job_outputs_num_new time.sleep(0.01) outputs_list = job.outputs().copy() job_outputs_num_new = len(outputs_list[job_outputs_num:]) for num in range(job_outputs_num_new): if max_time is not None and time.time() - t0 > max_time: return text res = outputs_list[job_outputs_num + num] if verbose_level == 2: print('Final Stream %d: %s' % (num, res), flush=True) elif verbose_level == 1: print('Final Stream %d' % (job_outputs_num + num), flush=True) if res and len(res[0]) > 0: text = res[-1][-1] yield text job_outputs_num += job_outputs_num_new if verbose_level == 1: print("total job_outputs_num=%d" % job_outputs_num, flush=True) return text def get_llava_response(file=None, llava_model=None, prompt=None, chat_conversation=[], allow_prompt_auto=False, image_model='llava-v1.6-vicuna-13b', temperature=0.2, top_p=0.7, max_new_tokens=512, image_process_mode="Default", include_image=False, client=None, max_time=None, force_stream=True, ): kwargs = locals() if force_stream: text = '' for res in get_llava_stream(**kwargs): text = res return text, prompt prompt = fix_llava_prompt(file, prompt, allow_prompt_auto=allow_prompt_auto) image_model, client, file = \ llava_prep(file, llava_model, image_model=image_model, client=client) res = client.predict(prompt, chat_conversation, file, image_process_mode, include_image, image_model, temperature, top_p, max_new_tokens, api_name='/textbox_api_submit') res = res[-1][-1] return res, prompt
null
167,149
import os import filelock from diffusers import DiffusionPipeline import torch from src.utils import makedirs from src.vision.sdxl import get_device def get_pipe_make_image(gpu_id): device = get_device(gpu_id) pipe = DiffusionPipeline.from_pretrained( "playgroundai/playground-v2-1024px-aesthetic", torch_dtype=torch.float16, use_safetensors=True, add_watermarker=False, variant="fp16" ).to(device) return pipe def makedirs(path, exist_ok=True, tmp_ok=False, use_base=False): """ Avoid some inefficiency in os.makedirs() :param path: :param exist_ok: :param tmp_ok: use /tmp if can't write locally :param use_base: :return: """ if path is None: return path # if base path set, make relative to that, unless user_path absolute path if use_base: if os.path.normpath(path) == os.path.normpath(os.path.abspath(path)): pass else: if os.getenv('H2OGPT_BASE_PATH') is not None: base_dir = os.path.normpath(os.getenv('H2OGPT_BASE_PATH')) path = os.path.normpath(path) if not path.startswith(base_dir): path = os.path.join(os.getenv('H2OGPT_BASE_PATH', ''), path) path = os.path.normpath(path) if os.path.isdir(path) and os.path.exists(path): assert exist_ok, "Path already exists" return path try: os.makedirs(path, exist_ok=exist_ok) return path except FileExistsError: # e.g. soft link return path except PermissionError: if tmp_ok: path0 = path path = os.path.join('/tmp/', path) print("Permission denied to %s, using %s instead" % (path0, path), flush=True) os.makedirs(path, exist_ok=exist_ok) return path else: raise def make_image(prompt, filename=None, gpu_id='auto', pipe=None, guidance_scale=3.0): if pipe is None: pipe = get_pipe_make_image(gpu_id=gpu_id) lock_type = 'image' base_path = os.path.join('locks', 'image_locks') 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 with filelock.FileLock(lock_file): image = pipe(prompt=prompt, guidance_scale=guidance_scale).images[0] if filename: image.save(filename) return filename return image
null
167,150
import io import numpy as np import pydub from src.utils import have_pyrubberband def get_wave_header(frame_input=b"", channels=1, sample_width=2, sample_rate=24000): # This will create a wave header then append the frame input # It should be first on a streaming wav file # Other frames better should not have it (else you will hear some artifacts each chunk start) import wave wav_buf = io.BytesIO() with wave.open(wav_buf, "wb") as vfout: vfout.setnchannels(channels) vfout.setsampwidth(sample_width) vfout.setframerate(sample_rate) vfout.writeframes(frame_input) wav_buf.seek(0) return wav_buf.read() def prepare_speech(sr=24000): # Must set autoplay to True first return get_wave_header(sample_rate=sr)
null
167,151
import io import numpy as np import pydub from src.utils import have_pyrubberband def get_no_audio(return_as_byte=True, return_nonbyte_as_file=False, sr=None): if return_as_byte: return b"" else: if return_nonbyte_as_file: return None else: assert sr is not None return sr, np.array([]).astype(np.int16) def combine_audios(audios, audio=None, channels=1, sample_width=2, sr=24000, expect_bytes=True): no_audio = get_no_audio(sr=sr) have_audio = any(x not in [no_audio, None, ''] for x in audios) or audio not in [no_audio, None, ''] if not have_audio: return no_audio if audio or audios: is_bytes = expect_bytes # force default as bytes no matter input if know should have been bytes if audios: is_bytes |= isinstance(audios[0], (bytes, bytearray)) if audio: is_bytes |= isinstance(audio, (bytes, bytearray)) assert audio is None or isinstance(audio, (bytes, bytearray)) from pydub import AudioSegment combined_wav = AudioSegment.empty() for x in audios: if x is not None: s = io.BytesIO(x) if is_bytes else x combined_wav += AudioSegment.from_raw(s, sample_width=sample_width, frame_rate=sr, channels=channels) if audio is not None: s = io.BytesIO(audio) if is_bytes else audio combined_wav += AudioSegment.from_raw(s, sample_width=sample_width, frame_rate=sr, channels=channels) if is_bytes: combined_wav = combined_wav.export(format='raw').read() return combined_wav # audio just empty stream, but not None, else would nuke audio return audio
null
167,152
import io import numpy as np import pydub from src.utils import have_pyrubberband def pydub_to_np(audio: pydub.AudioSegment) -> (np.ndarray, int): """ Converts pydub audio segment into np.int16 of shape [duration_in_seconds*sample_rate, channels], """ return np.array(audio.get_array_of_samples(), dtype=np.int16).reshape((-1, audio.channels)) def chunk_speed_change(chunk, sr, tts_speed=1.0): if tts_speed == 1.0: return chunk if have_pyrubberband: import pyrubberband as pyrb chunk = pyrb.time_stretch(chunk, sr, tts_speed) chunk = (chunk * 32767).astype(np.int16) return chunk if tts_speed < 1.0: # chunk = chunk.astype(np.float32) # chunk = 0.5 * chunk / np.max(chunk) # chunk = librosa.effects.time_stretch(chunk, rate=tts_speed) return chunk # speed-up from pydub import AudioSegment from pydub.effects import speedup s = io.BytesIO(chunk) channels = 1 sample_width = 2 audio = AudioSegment.from_raw(s, sample_width=sample_width, frame_rate=sr, channels=channels) # chunk = speedup(audio, tts_speed, 150).export(format='raw').read() chunk = pydub_to_np(speedup(audio, tts_speed, 150)) # audio = audio._spawn(audio.raw_data, overrides={ # "frame_rate": int(audio.frame_rate * tts_speed) # }) # chunk = np.array(audio.get_array_of_samples()) return chunk
null
167,154
from __future__ import annotations import base64 from pkg_resources import resource_filename import os import time from io import BytesIO import numpy as np import scipy import wavio import soundfile as sf import torch import librosa from src.tts_sentence_parsing import init_sentence_state, get_sentence from src.tts_utils import prepare_speech, get_no_audio, chunk_speed_change, combine_audios def get_speakers(): return ["SLT (female)", "BDL (male)", "CLB (female)", "KSP (male)", "RMS (male)", "Surprise Me!", "None", ] def get_speakers_gr(value=None): import gradio as gr choices = get_speakers() if value is None: value = choices[0] return gr.Dropdown(label="Speech Style", choices=choices, value=value)
null
167,158
from __future__ import annotations import base64 from pkg_resources import resource_filename import os import time from io import BytesIO import numpy as np import scipy import wavio import soundfile as sf import torch import librosa from src.tts_sentence_parsing import init_sentence_state, get_sentence from src.tts_utils import prepare_speech, get_no_audio, chunk_speed_change, combine_audios def get_speech_model(): def generate_speech(response, speaker, model=None, processor=None, vocoder=None, speaker_embedding=None, sentence_state=None, sr=16000, tts_speed=1.0, return_as_byte=True, return_gradio=False, is_final=False, verbose=False): def text_to_speech(text, sr=16000): processor, model, vocoder, speaker_embedding = get_speech_model() inputs = processor(text=text, return_tensors="pt") speech = model.generate_speech(inputs["input_ids"], speaker_embedding, vocoder=vocoder) sf.write("speech.wav", speech.numpy(), samplerate=sr)
null
167,160
from __future__ import annotations import functools import io import os import tempfile import filelock import numpy as np import uuid import subprocess import time from src.enums import coqui_lock_name from src.tts_sentence_parsing import init_sentence_state, get_sentence, clean_sentence, detect_language from src.tts_utils import prepare_speech, get_no_audio, chunk_speed_change, combine_audios from src.utils import cuda_vis_check, get_lock_file import torch def list_models(): from TTS.utils.manage import ModelManager return ModelManager().list_tts_models()
null
167,161
from __future__ import annotations import functools import io import os import tempfile import filelock import numpy as np import uuid import subprocess import time from src.enums import coqui_lock_name from src.tts_sentence_parsing import init_sentence_state, get_sentence, clean_sentence, detect_language from src.tts_utils import prepare_speech, get_no_audio, chunk_speed_change, combine_audios from src.utils import cuda_vis_check, get_lock_file import torch def allowed_roles(): return list(get_role_to_wave_map().keys()) def get_roles(choices=None, value=None): if choices is None: choices = allowed_roles() if value is None: value = choices[0] import gradio as gr chatbot_role = gr.Dropdown( label="Speech Style", choices=choices, value=value, ) return chatbot_role
null
167,164
from __future__ import annotations import functools import io import os import tempfile import filelock import numpy as np import uuid import subprocess import time from src.enums import coqui_lock_name from src.tts_sentence_parsing import init_sentence_state, get_sentence, clean_sentence, detect_language from src.tts_utils import prepare_speech, get_no_audio, chunk_speed_change, combine_audios from src.utils import cuda_vis_check, get_lock_file import torch def get_languages_gr(visible=True, value=None): import gradio as gr choices = [ "autodetect", "en", "es", "fr", "de", "it", "pt", "pl", "tr", "ru", "nl", "cs", "ar", "zh-cn", "ja", "ko", "hu" ] if value is None: value = choices[0] language_gr = gr.Dropdown( label="Language", info="Select an output language for the synthesised speech", choices=choices, value=value, visible=visible, ) return language_gr
null
167,165
import functools import json from src.enums import t5_type from src.utils import have_optimum 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() class H2OExLlamaTokenizer(ExLlamaTokenizer): def __call__(self, text, *args, **kwargs): return dict(input_ids=self.encode(text)) class H2OExLlamaGenerator(ExLlamaGenerator): def is_exlama(self): return True def get_loaders(model_name, reward_type, llama_type=None, load_gptq='', use_autogptq=False, load_awq='', load_exllama=False, config=None, rope_scaling=None, max_seq_len=None, model_name_exllama_if_no_config='', exllama_dict=None, gptq_dict=None, hf_model_dict={}, ): # NOTE: Some models need specific new prompt_type # E.g. t5_xxl_true_nli_mixture has input format: "premise: PREMISE_TEXT hypothesis: HYPOTHESIS_TEXT".) if load_exllama: if exllama_dict is None: exllama_dict = {} from src.llm_exllama import H2OExLlamaTokenizer, H2OExLlamaGenerator from exllama.model import ExLlama, ExLlamaCache, ExLlamaConfig import os, glob if config: # then use HF path from transformers import TRANSFORMERS_CACHE model_directory = os.path.join(TRANSFORMERS_CACHE, 'models--' + config.name_or_path.replace('/', '--'), 'snapshots', config._commit_hash) else: # then use path in env file # Directory containing model, tokenizer, generator model_directory = model_name_exllama_if_no_config # download model revision = config._commit_hash from huggingface_hub import snapshot_download snapshot_download(repo_id=model_name, revision=revision) # Locate files we need within that directory tokenizer_path = os.path.join(model_directory, "tokenizer.model") assert os.path.isfile(tokenizer_path), "Missing %s" % tokenizer_path model_config_path = os.path.join(model_directory, "config.json") assert os.path.isfile(model_config_path), "Missing %s" % model_config_path st_pattern = os.path.join(model_directory, "*.safetensors") model_path = glob.glob(st_pattern)[0] assert os.path.isfile(model_path), "Missing %s" % model_path # Create config, model, tokenizer and generator exconfig = ExLlamaConfig(model_config_path) # create config from config.json rope_scaling = rope_scaling or {} exconfig.alpha_value = rope_scaling.get('alpha_value', 1) # rope exconfig.compress_pos_emb = rope_scaling.get('compress_pos_emb', 1) # related rope # update max_seq_len assert hasattr(config, 'max_position_embeddings') or hasattr(config, 'max_sequence_length'), "Improve code if no such argument" if hasattr(config, 'max_position_embeddings'): exconfig.max_seq_len = int(config.max_position_embeddings * exconfig.alpha_value) else: exconfig.max_seq_len = int(config.max_sequence_length * exconfig.alpha_value) if 'Llama-2'.lower() in model_name.lower(): # override bad defaults exconfig.max_seq_len = int(4096 * exconfig.alpha_value) if max_seq_len is not None: exconfig.max_seq_len = max_seq_len exconfig.model_path = model_path # supply path to model weights file for k, v in exllama_dict.items(): setattr(exconfig, k, v) if 'set_auto_map' in exllama_dict: exconfig.auto_map = [float(alloc) for alloc in exllama_dict['set_auto_map'].split(",")] model = ExLlama(exconfig) # create ExLlama instance and load the weights tokenizer = H2OExLlamaTokenizer(tokenizer_path) # create tokenizer from tokenizer model file tokenizer.model_max_length = exconfig.max_seq_len cache = ExLlamaCache(model) # create cache for inference generator = H2OExLlamaGenerator(model, tokenizer, cache) # create generator return generator, tokenizer, False if load_gptq and use_autogptq: if gptq_dict is None: gptq_dict = {} from transformers import AutoTokenizer from auto_gptq import AutoGPTQForCausalLM if 'use_triton' not in gptq_dict: gptq_dict['use_triton'] = False if 'llama-2-70B-chat-GPTQ' in model_name.lower() and 'inject_fused_attention' not in gptq_dict: gptq_dict.update(dict(inject_fused_attention=False)) model_loader = functools.partial(AutoGPTQForCausalLM.from_quantized, quantize_config=None, **gptq_dict, ) return model_loader, AutoTokenizer, False if load_gptq and not use_autogptq: assert have_optimum, "To use HF transformers GPTQ, please: pip install optimum" if load_awq: from transformers import AutoTokenizer from awq import AutoAWQForCausalLM model_loader = functools.partial(AutoAWQForCausalLM.from_quantized, fuse_layers=True, ) return model_loader, AutoTokenizer, False if llama_type is None: llama_type = "llama" in model_name.lower() if llama_type and not load_gptq: from transformers import LlamaForCausalLM, LlamaTokenizer return functools.partial(LlamaForCausalLM.from_pretrained, **hf_model_dict), LlamaTokenizer, False elif 'distilgpt2' in model_name.lower(): from transformers import AutoModelForCausalLM, AutoTokenizer return functools.partial(AutoModelForCausalLM.from_pretrained, **hf_model_dict), AutoTokenizer, False elif 'gpt2' in model_name.lower(): from transformers import GPT2LMHeadModel, GPT2Tokenizer return functools.partial(GPT2LMHeadModel.from_pretrained, **hf_model_dict), GPT2Tokenizer, False elif 'mbart-' in model_name.lower(): from transformers import MBartForConditionalGeneration, MBart50TokenizerFast return functools.partial(MBartForConditionalGeneration.from_pretrained, **hf_model_dict), MBart50TokenizerFast, True elif t5_type(model_name): from transformers import AutoTokenizer, T5ForConditionalGeneration return functools.partial(T5ForConditionalGeneration.from_pretrained, **hf_model_dict), AutoTokenizer, True elif 'bigbird' in model_name: from transformers import BigBirdPegasusForConditionalGeneration, AutoTokenizer return functools.partial(BigBirdPegasusForConditionalGeneration.from_pretrained, **hf_model_dict), AutoTokenizer, True elif 'bart-large-cnn-samsum' in model_name or 'flan-t5-base-samsum' in model_name: from transformers import pipeline return pipeline, "summarization", False elif reward_type or 'OpenAssistant/reward-model'.lower() in model_name.lower(): from transformers import AutoModelForSequenceClassification, AutoTokenizer return functools.partial(AutoModelForSequenceClassification.from_pretrained, **hf_model_dict), AutoTokenizer, False else: from transformers import AutoTokenizer, AutoModelForCausalLM model_loader = functools.partial(AutoModelForCausalLM.from_pretrained, **hf_model_dict) tokenizer_loader = AutoTokenizer return model_loader, tokenizer_loader, False
null
167,166
import functools import json from src.enums import t5_type from src.utils import have_optimum def get_tokenizer(tokenizer_loader, tokenizer_base_model, local_files_only, resume_download, use_auth_token): tokenizer = tokenizer_loader.from_pretrained(tokenizer_base_model, local_files_only=local_files_only, resume_download=resume_download, token=use_auth_token, padding_side='left') tokenizer.pad_token_id = 0 # different from the eos token # when generating, we will use the logits of right-most token to predict the next token # so the padding should be on the left, # e.g. see: https://huggingface.co/transformers/v4.11.3/model_doc/t5.html#inference tokenizer.padding_side = "left" # Allow batched inference return tokenizer
null
167,167
import torch from transformers import StoppingCriteria, StoppingCriteriaList from enums import PromptType, t5_type class StoppingCriteriaSub(StoppingCriteria): def __init__(self, stops=[], stop_words=[], encounters=[], device="cuda", model_max_length=None, tokenizer=None, truncation_generation=False): super().__init__() assert len(stops) % len(encounters) == 0, "Number of stops and encounters must match" self.encounters = encounters self.stops = [stop.to(device) for stop in stops] self.stop_words = stop_words self.num_stops = [0] * len(stops) self.model_max_length = model_max_length self.tokenizer = tokenizer self.truncation_generation = truncation_generation self.token_start = None # not setup for handling existing prompt, only look at new tokens, some models like xwin have funny token handling, # and despite new tokens present the block looks back into different sized output and matches the stop token self.look_at_new_tokens_only = max(self.encounters) == 1 def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: # if self.tokenizer: # print('stop: %s' % self.tokenizer.decode(input_ids[0]), flush=True) if self.token_start is None: self.token_start = input_ids[0].shape[0] if self.look_at_new_tokens_only: new_tokens = input_ids[0][self.token_start:] else: new_tokens = input_ids[0][0:] for stopi, (stop, stop_word) in enumerate(zip(self.stops, self.stop_words)): current_block = new_tokens[-len(stop):] stop_text = self.tokenizer.decode(current_block) len_new_tokens = current_block.shape[0] # if len(stop) <= len_new_tokens and torch.all((stop == input_ids[0][-len(stop):])).item(): if len(stop) <= len_new_tokens and stop_word in stop_text: self.num_stops[stopi] += 1 if self.num_stops[stopi] >= self.encounters[stopi % len(self.encounters)]: # print("Stopped", flush=True) return True if self.truncation_generation and ( self.model_max_length is not None and input_ids[0].shape[0] >= self.model_max_length): # critical limit return True # print("Tokens: %s" % input_ids[0].cpu().numpy(), flush=True) # print("Stop Tokens: %s" % [x.cpu().numpy() for x in self.stops], flush=True) return False 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 mistral = 34 zephyr = 35 xwin = 36 mistrallite = 37 aquila = 38 aquila_simple = 39 aquila_legacy = 40 aquila_v1 = 41 mistralgerman = 42 deepseek_coder = 43 open_chat = 44 open_chat_correct = 45 open_chat_code = 46 anthropic = 47 orca2 = 48 jais = 49 yi = 50 xwincoder = 51 xwinmath = 52 vicuna11nosys = 53 zephyr0 = 54 google = 55 docsgpt = 56 open_chat_math = 57 mistralai = 58 mixtral = 59 mixtralnosys = 60 orion = 61 sciphi = 62 beacon = 63 beacon2 = 64 llava = 65 danube = 66 gemma = 67 qwen = 68 sealion = 69 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_stopping(prompt_type, prompt_dict, tokenizer, device, base_model, human='<human>:', bot="<bot>:", model_max_length=None, prompter=None, stop=None, truncation_generation=False): stop_words = [] encounters = [] # FIXME: prompt_dict unused currently user_human_assistant_types = [PromptType.instruct_vicuna.value, str(PromptType.instruct_vicuna.value), PromptType.instruct_vicuna.name] + \ [PromptType.guanaco.value, str(PromptType.guanaco.value), PromptType.guanaco.name] + \ [PromptType.one_shot.value, str(PromptType.one_shot.value), PromptType.one_shot.name] + \ [PromptType.instruct_vicuna2.value, str(PromptType.instruct_vicuna2.value), PromptType.instruct_vicuna2.name] + \ [PromptType.instruct_vicuna3.value, str(PromptType.instruct_vicuna3.value), PromptType.instruct_vicuna3.name] + \ [PromptType.instruct_with_end.value, str(PromptType.instruct_with_end.value), PromptType.instruct_with_end.name] human_bot_types = [PromptType.human_bot.value, str(PromptType.human_bot.value), PromptType.human_bot.name] + \ [PromptType.human_bot_orig.value, str(PromptType.human_bot_orig.value), PromptType.human_bot_orig.name] all_types = user_human_assistant_types + human_bot_types if prompt_type in all_types: if prompt_type in human_bot_types: # encounters = [prompt.count(human) + 1, prompt.count(bot) + 1] # stopping only starts once output is beyond prompt # 1 human is enough to trigger, but need 2 bots, because very first view back will be bot we added stop_words = [human, bot, '\n' + human, '\n' + bot] encounters = [1, 2] elif prompt_type in user_human_assistant_types: # even below is not enough, generic strings and many ways to encode stop_words = [ '### Human:', """ ### Human:""", """ ### Human: """, """### Human: """, """### Human:""", '### Assistant:', """ ### Assistant:""", """ ### Assistant: """, """### Assistant: """, """### Assistant:""" ] if prompt_type in [PromptType.instruct_vicuna2.value, str(PromptType.instruct_vicuna2.value), PromptType.instruct_vicuna2.name]: stop_words = [x.upper() for x in stop_words] if prompt_type in [PromptType.instruct_vicuna3.value, str(PromptType.instruct_vicuna3.value), PromptType.instruct_vicuna3.name]: stop_words = [x.replace('Human', 'User') for x in stop_words] encounters = [1, 2] else: # some instruct prompts have this as end, doesn't hurt to stop on it since not common otherwise stop_words = ['### End'] encounters = [1] elif prompter and prompter.terminate_response: stop_words = prompter.terminate_response encounters = [1] * len(stop_words) handle_newlines = [True] * len(stop_words) # add other stop words too if passed, e.g. for LangChain agents if stop: stop_words += stop encounters += [1] * len(stop) handle_newlines += [False] * len(stop) # get stop tokens stop_words_ids = [ tokenizer(stop_word, return_tensors='pt')['input_ids'].squeeze() for stop_word in stop_words] # handle single token case stop_words_ids = [x if len(x.shape) > 0 else torch.tensor([x]) for x in stop_words_ids] stop_words_ids = [x for x in stop_words_ids if x.shape[0] > 0] # avoid padding in front of tokens if tokenizer._pad_token: # use hidden variable to avoid annoying properly logger bug stop_words_ids = [x[1:] if x[0] == tokenizer.pad_token_id and len(x) > 1 else x for x in stop_words_ids] if tokenizer._unk_token: # use hidden variable to avoid annoying properly logger bug stop_words_ids = [x[1:] if x[0] == tokenizer.unk_token_id and len(x) > 1 else x for x in stop_words_ids] stop_words_ids = [x[:-1] if x[-1] == tokenizer.unk_token_id and len(x) > 1 else x for x in stop_words_ids] if tokenizer._eos_token: # use hidden variable to avoid annoying properly logger bug stop_words_ids = [x[:-1] if x[-1] == tokenizer.eos_token_id and len(x) > 1 else x for x in stop_words_ids] if tokenizer._bos_token: # use hidden variable to avoid annoying properly logger bug stop_words_ids = [x[1:] if x[0] == tokenizer.bos_token_id and len(x) > 1 else x for x in stop_words_ids] stop_words_ids = [x[:-1] if x[-1] == tokenizer.bos_token_id and len(x) > 1 else x for x in stop_words_ids] if base_model and t5_type(base_model): # T5 encoder converts internal double space to space+new line, so fix for stopi, stop_word_id in enumerate(stop_words_ids): start = stop_word_id[0:1] mlist = stop_word_id[1:-1] end = stop_word_id[-1:] mlist = [tokenizer.vocab[' '] if x == tokenizer.vocab['\n'] else x for x in mlist] stop_words_ids[stopi] = torch.tensor(list(start) + list(mlist) + list(end), device=stop_word_id.device) # handle fake \n added stop_words_ids = [x[1:] if y[0] == '\n' and handle_newline else x for x, y, handle_newline in zip(stop_words_ids, stop_words, handle_newlines)] if stop_words_ids: # build stopper stopping_criteria = StoppingCriteriaList( [StoppingCriteriaSub(stops=stop_words_ids, stop_words=stop_words, encounters=encounters, device=device, model_max_length=model_max_length, tokenizer=tokenizer, truncation_generation=truncation_generation)]) else: # nothing to stop on stopping_criteria = StoppingCriteriaList() return stopping_criteria
null
167,168
import functools import os import math import csv import datetime import filelock import gradio as gr from src.enums import no_server_str from src.utils import is_gradio_version4 def get_chatbot_name(base_model, model_path_llama, inference_server='', prompt_type='', model_label_prefix='', debug=False): #have_inference_server = inference_server not in [no_server_str, None, ''] #if not have_inference_server and prompt_type in [None, '', 'plain']: # label_postfix = ' [Please select prompt_type in Models tab or on CLI for chat models]' #else: # pass label_postfix = '' if not debug: inference_server = '' else: inference_server = ' : ' + inference_server if base_model == 'llama': model_path_llama = os.path.basename(model_path_llama) if model_path_llama.endswith('?download=true'): model_path_llama = model_path_llama.replace('?download=true', '') label = f'{model_label_prefix} [Model: {model_path_llama}{inference_server}]' else: if base_model == 'mixtral-8x7b-32768': base_model = 'groq:mixtral-8x7b-32768' label = f'{model_label_prefix} [Model: {base_model}{inference_server}]' label += label_postfix return label def get_avatars(base_model, model_path_llama, inference_server=''): if base_model == 'llama': base_model = model_path_llama if inference_server is None: inference_server = '' model_base = os.getenv('H2OGPT_MODEL_BASE', 'models/') human_avatar = "human.jpg" if 'h2ogpt-gm'.lower() in base_model.lower(): bot_avatar = "h2oai.png" elif 'llava-' in base_model.lower(): bot_avatar = "llava.png" elif 'mistralai'.lower() in base_model.lower() or \ 'mistral'.lower() in base_model.lower() or \ 'mixtral'.lower() in base_model.lower(): bot_avatar = "mistralai.png" elif '01-ai/Yi-'.lower() in base_model.lower(): bot_avatar = "yi.svg" elif 'wizard' in base_model.lower(): bot_avatar = "wizard.jpg" elif 'openchat' in base_model.lower(): bot_avatar = "openchat.png" elif 'vicuna' in base_model.lower(): bot_avatar = "vicuna.jpeg" elif 'longalpaca' in base_model.lower(): bot_avatar = "longalpaca.png" elif 'llama2-70b-chat' in base_model.lower(): bot_avatar = "meta.png" elif 'llama2-13b-chat' in base_model.lower(): bot_avatar = "meta.png" elif 'llama2-7b-chat' in base_model.lower(): bot_avatar = "meta.png" elif 'llama2' in base_model.lower(): bot_avatar = "lama2.jpeg" elif 'llama-2' in base_model.lower(): bot_avatar = "lama2.jpeg" elif 'llama' in base_model.lower(): bot_avatar = "lama.jpeg" elif 'openai' in base_model.lower() or 'openai' in inference_server.lower(): bot_avatar = "openai.png" elif 'hugging' in base_model.lower(): bot_avatar = "hf-logo.png" elif 'claude' in base_model.lower(): bot_avatar = "anthropic.jpeg" elif 'gemini' in base_model.lower(): bot_avatar = "google.png" else: bot_avatar = "h2oai.png" bot_avatar = os.path.join(model_base, bot_avatar) human_avatar = os.path.join(model_base, human_avatar) human_avatar = human_avatar if os.path.isfile(human_avatar) else None bot_avatar = bot_avatar if os.path.isfile(bot_avatar) else None return human_avatar, bot_avatar def ratingfn1(): return 1 def ratingfn2(): return 2 def ratingfn3(): return 3 def ratingfn4(): return 4 def ratingfn5(): return 5 def submit_review(review_text, text_output, text_output2, *text_outputs1, reviews_file=None, num_model_lock=None, do_info=True): if reviews_file is None: if do_info: gr.Info('No review file') return '' chatbots = [text_output, text_output2] + list(text_outputs1) last_chatbots = [x[-1] for x in chatbots if x] now = datetime.datetime.now() with filelock.FileLock(reviews_file + '.lock'): with open(reviews_file, 'a', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow([review_text, *last_chatbots, now]) if do_info: gr.Info('Review submitted!') return '' def make_chatbots(output_label0, output_label0_model2, **kwargs): visible_models = kwargs['visible_models'] all_models = kwargs['all_possible_visible_models'] visible_ratings = kwargs['visible_ratings'] reviews_file = kwargs['reviews_file'] or 'reviews.csv' text_outputs = [] chat_kwargs = [] min_width = 250 if kwargs['gradio_size'] in ['small', 'large', 'medium'] else 160 for model_state_locki, model_state_lock in enumerate(kwargs['model_states']): output_label = get_chatbot_name(model_state_lock["base_model"], model_state_lock['llamacpp_dict']["model_path_llama"], model_state_lock["inference_server"], model_state_lock["prompt_type"], model_label_prefix=kwargs['model_label_prefix'], debug=bool(os.environ.get('DEBUG_MODEL_LOCK', 0))) if kwargs['avatars']: avatar_images = get_avatars(model_state_lock["base_model"], model_state_lock['llamacpp_dict']["model_path_llama"], model_state_lock["inference_server"]) else: avatar_images = None chat_kwargs.append(dict(render_markdown=kwargs.get('render_markdown', True), label=output_label, show_label=kwargs.get('visible_chatbot_label', True), elem_classes='chatsmall', height=kwargs['height'] or 400, min_width=min_width, avatar_images=avatar_images, likeable=True, latex_delimiters=[], 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 and kwargs['model_lock_layout_based_upon_initial_visible']: 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 > 0: len_chatbots = len(kwargs['model_states']) nrows = math.ceil(len_chatbots / kwargs['model_lock_columns']) for nrowi in range(nrows): with gr.Row(): for mii, (chat_kwargs1, model_state_lock) in enumerate(zip(chat_kwargs, kwargs['model_states'])): if mii < nrowi * len_chatbots / nrows or mii >= (1 + nrowi) * len_chatbots / nrows: continue text_outputs.append(gr.Chatbot(**chat_kwargs1)) if len(kwargs['model_states']) > 0: assert len(text_outputs) == len(kwargs['model_states']) if kwargs['avatars']: avatar_images = get_avatars(kwargs["base_model"], kwargs['llamacpp_dict']["model_path_llama"], kwargs["inference_server"]) else: avatar_images = None no_model_lock_chat_kwargs = dict(render_markdown=kwargs.get('render_markdown', True), show_label=kwargs.get('visible_chatbot_label', True), elem_classes='chatsmall', height=kwargs['height'] or 400, min_width=min_width, show_copy_button=kwargs['show_copy_button'], avatar_images=avatar_images, latex_delimiters=[], ) with gr.Row(): text_output = gr.Chatbot(label=output_label0, visible=not kwargs['model_lock'], **no_model_lock_chat_kwargs, likeable=True, ) text_output2 = gr.Chatbot(label=output_label0_model2, visible=False and not kwargs['model_lock'], **no_model_lock_chat_kwargs, likeable=True, ) chatbots = [text_output, text_output2] + text_outputs with gr.Row(visible=visible_ratings): review_textbox = gr.Textbox(visible=True, label="Review", placeholder="Type your review...", scale=4) rating_text_output = gr.Textbox(elem_id="text_output", visible=False) with gr.Column(): with gr.Row(): rating1 = gr.Button(value='⭑', variant='outline-primary', scale=1, elem_id="rating1", size="sm") rating2 = gr.Button(value='⭑', variant='outline-primary', scale=1, elem_id="rating2", size="sm") rating3 = gr.Button(value='⭑', variant='outline-primary', scale=1, elem_id="rating3", size="sm") rating4 = gr.Button(value='⭑', variant='outline-primary', scale=1, elem_id="rating4", size="sm") rating5 = gr.Button(value='⭑', variant='outline-primary', scale=1, elem_id="rating5", size="sm") review_js1 = """ function highlightButtons() { var element = document.getElementById("rating1"); // element.style.backgroundColor = "#ffa41c"; element.style.color = "#ffa41c"; var element = document.getElementById("rating2"); // element.style.backgroundColor = "rgba(173, 181, 189, 0.5)"; element.style.color = "rgba(173, 181, 189, 0.5)"; var element = document.getElementById("rating3"); // element.style.backgroundColor = "rgba(173, 181, 189, 0.5)"; element.style.color = "rgba(173, 181, 189, 0.5)"; var element = document.getElementById("rating4"); // element.style.backgroundColor = "rgba(173, 181, 189, 0.5)"; element.style.color = "rgba(173, 181, 189, 0.5)"; var element = document.getElementById("rating5"); // element.style.backgroundColor = "rgba(173, 181, 189, 0.5)"; element.style.color = "rgba(173, 181, 189, 0.5)"; } """ review_js2 = """ function highlightButtons() { var element = document.getElementById("rating1"); // element.style.backgroundColor = "#ffa41c"; element.style.color = "#ffa41c"; var element = document.getElementById("rating2"); // element.style.backgroundColor = "#ffa41c"; element.style.color = "#ffa41c"; var element = document.getElementById("rating3"); // element.style.backgroundColor = "rgba(173, 181, 189, 0.5)"; element.style.color = "rgba(173, 181, 189, 0.5)"; var element = document.getElementById("rating4"); // element.style.backgroundColor = "rgba(173, 181, 189, 0.5)"; element.style.color = "rgba(173, 181, 189, 0.5)"; var element = document.getElementById("rating5"); // element.style.backgroundColor = "rgba(173, 181, 189, 0.5)"; element.style.color = "rgba(173, 181, 189, 0.5)"; } """ review_js3 = """ function highlightButtons() { var element = document.getElementById("rating1"); // element.style.backgroundColor = "#ffa41c"; element.style.color = "#ffa41c"; var element = document.getElementById("rating2"); // element.style.backgroundColor = "#ffa41c"; element.style.color = "#ffa41c"; var element = document.getElementById("rating3"); // element.style.backgroundColor = "#ffa41c"; element.style.color = "#ffa41c"; var element = document.getElementById("rating4"); // element.style.backgroundColor = "rgba(173, 181, 189, 0.5)"; element.style.color = "rgba(173, 181, 189, 0.5)"; var element = document.getElementById("rating5"); // element.style.backgroundColor = "rgba(173, 181, 189, 0.5)"; element.style.color = "rgba(173, 181, 189, 0.5)"; } """ review_js4 = """ function highlightButtons() { var element = document.getElementById("rating1"); // element.style.backgroundColor = "#ffa41c"; element.style.color = "#ffa41c"; var element = document.getElementById("rating2"); // element.style.backgroundColor = "#ffa41c"; element.style.color = "#ffa41c"; var element = document.getElementById("rating3"); // element.style.backgroundColor = "#ffa41c"; element.style.color = "#ffa41c"; var element = document.getElementById("rating4"); // element.style.backgroundColor = "#ffa41c"; element.style.color = "#ffa41c"; var element = document.getElementById("rating5"); // element.style.backgroundColor = "rgba(173, 181, 189, 0.5)"; element.style.color = "rgba(173, 181, 189, 0.5)"; } """ review_js5 = """ function highlightButtons() { var element = document.getElementById("rating1"); // element.style.backgroundColor = "#ffa41c"; element.style.color = "#ffa41c"; var element = document.getElementById("rating2"); // element.style.backgroundColor = "#ffa41c"; element.style.color = "#ffa41c"; var element = document.getElementById("rating3"); // element.style.backgroundColor = "#ffa41c"; element.style.color = "#ffa41c"; var element = document.getElementById("rating4"); // element.style.backgroundColor = "#ffa41c"; element.style.color = "#ffa41c"; var element = document.getElementById("rating5"); // element.style.backgroundColor = "#ffa41c"; element.style.color = "#ffa41c"; } """ if is_gradio_version4: rating1.click(ratingfn1, outputs=rating_text_output, js=review_js1) rating2.click(ratingfn2, outputs=rating_text_output, js=review_js2) rating3.click(ratingfn3, outputs=rating_text_output, js=review_js3) rating4.click(ratingfn4, outputs=rating_text_output, js=review_js4) rating5.click(ratingfn5, outputs=rating_text_output, js=review_js5) else: rating1.click(ratingfn1, outputs=rating_text_output, _js=review_js1) rating2.click(ratingfn2, outputs=rating_text_output, _js=review_js2) rating3.click(ratingfn3, outputs=rating_text_output, _js=review_js3) rating4.click(ratingfn4, outputs=rating_text_output, _js=review_js4) rating5.click(ratingfn5, outputs=rating_text_output, _js=review_js5) submit_review_btn = gr.Button("Submit Review", scale=1) submit_review_func = functools.partial(submit_review, reviews_file=reviews_file if reviews_file else None, num_model_lock=len(chatbots)) submit_review_btn.click(submit_review_func, inputs=[review_textbox, rating_text_output, text_output, text_output2] + text_outputs, outputs=review_textbox) # set likeable method def on_like(like_data: gr.LikeData): submit_review(str(like_data.liked) + "," + str(like_data.target.label), *tuple([['', like_data.value], []]), reviews_file=reviews_file, num_model_lock=len(chatbots), do_info=False) for chatbot in chatbots: chatbot.like(on_like) return text_output, text_output2, text_outputs
null
167,169
def make_css_base() -> str: return """ #col_container {margin-left: auto; margin-right: auto; text-align: left;} body.dark{#warning {background-color: #555555};} #sidebar { order: 1; order: 2; } } #col-tabs { order: 2; 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; } #microphone-button { position: absolute; top: 14px; right: 125px; display: flex; justify-content: center; border: 1px solid var(--primary-500) !important; width: 20px; } } #microphone-button > img { margin-right: 0; } #add-button { position: absolute; top: 14px; right: 75px; display: flex; justify-content: center; border: 1px solid var(--primary-500) !important; width: 40px; } } #add-button > img { margin-right: 0; } #attach-button { position: absolute; top: 14px; right: 20px; display: flex; justify-content: center; border: 1px solid var(--primary-500) !important; width: 40px; } } #attach-button > img { margin-right: 40; } #prompt-form > label > textarea { padding-right: 0px; min-height: 94px; padding-right: 0px; } } #multi-selection > label > div.wrap > div.wrap-inner > div.secondary-wrap > div.remove-all { display: none !important; } #multi-selection > label > div.wrap > div.wrap-inner > div.token { display: none !important; } #multi-selection > label > div.wrap > div.wrap-inner > div.secondary-wrap::before { content: "Select_Any"; padding: 0 4px; margin-right: 2px; } #single-selection > label > div.wrap > div.wrap-inner > div.secondary-wrap > div.remove-all { display: none !important; } #single-selection > label > div.wrap > div.wrap-inner > div.token { display: none !important; } #single-selection > label > div.wrap > div.wrap-inner > div.secondary-wrap::before { content: "Select_One"; 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; } #rating1, #rating2, #rating3, #rating4, #rating5 { /* Target all star buttons */ all:unset ; font-size:2rem; display:flex ; width: 15px !important; /* Set your desired width */ padding-bottom: 15px !important; /* Set your desired transition: background-color 0.3s ease-in !important; transition: color 0.3s ease-in !important; background-color: rgba(173, 181, 189, 0.5) !important; clip-path: polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%); } """ 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
null
167,171
import gradio as gr import torch import os from transformers import AutoTokenizer, AutoModelForCausalLM from h2oai_pipeline import H2OTextGenerationPipeline def generate(query): return generate_text(query, max_new_tokens=150)[0]['generated_text'] def process_example(args): for x in generate(args): pass return x
null
167,172
import os import sys from functools import partial from typing import List, Union import numpy as np from src.loaders import get_loaders, get_tokenizer from src.prompter import generate_prompt, prompt_types, PromptType from src.utils import get_githash, copy_code, H2O_Fire import torch def train( save_code: bool = False, run_id: int = None, base_model: str = 'h2oai/h2ogpt-4096-llama2-7b', # base_model: str = 'h2oai/h2ogpt-4096-llama2-13b', # base_model: str = 'h2oai/h2ogpt-4096-llama2-70b', # only needed if base_model is self-exported HF state without tokenizer tokenizer_base_model: str = None, # tokenizer_base_model: str = 'EleutherAI/gpt-neox-20b', data_path: str = "h2oai/openassistant_oasst1_h2ogpt", data_col_dict: dict = None, # data_path: str = "./dai_docs.train.json", prompt_type: Union[str, int] = "plain", # "plain", "instruct", "quality", "human_bot", "dai_faq" valid_path: str = None, # valid_path: str = "./dai_docs.valid.json", # data_mix_in_path: str = "laion/OIG", # way too big, medium quality data_mix_in_path: str = "0-hero/OIG-small-chip2", # high quality, 50 MB, good enough for now data_mix_in_factor: float = 0.0, # >1: more mix-in data, <1: more of data_path data data_mix_in_col_dict: dict = {'user': 'instruction', 'chip2': 'output'}, data_mix_in_prompt_type: str = "instruct", # just instruction->output, same as instruct output_dir: str = None, # LoRA checkpoint continuation lora_weights: str = "", # batching training hyperparams batch_size: int = 128, micro_batch_size: int = 4, gradient_checkpointing=False, # unnecessary with gradient accumulation enabled bf16=False, # needed (and automatically enabled) for llama2-7b fp16=True, train_8bit=False, train_4bit=False, # general training hyperparams num_epochs: float = 1, learning_rate: float = 3e-4, # validation settings val_set_size: int = None, val_metrics: List[str] = [], eval_steps: int = None, # to control eval steps via steps eval_epochs: float = None, # to control eval steps via epochs # lora hyperparams lora_r: int = 8, lora_alpha: int = 16, lora_dropout: float = 0.05, lora_target_modules: List[str] = None, llama_type: bool = None, llama_flash_attn: bool = False, # llm hyperparams train_on_inputs: bool = True, # if False, masks out inputs in loss group_by_length: bool = False, # if True, faster, but produces an odd training loss curve resume_from_checkpoint: str = None, # either training checkpoint or final adapter cutoff_len: int = 512, # larger values use more memory drop_truncations: bool = False, # if True, drop any truncated long sequences # torch training params ddp: bool = True, # set to False if OOM with True, for multi-GPU model parallelism local_files_only: bool = False, # else will download new versions, normally unwanted resume_download: bool = True, use_auth_token: Union[str, bool] = False, # True requires CLI did huggingface-cli login before running warmup_steps: int = 100, logging_steps: int = 1, save_steps: int = None, # must be round multiple of eval_steps save_total_limit: int = 3, add_eos_token: bool = False, ): if llama_flash_attn: # Need to call this before importing transformers. from src.llama_flash_attn_monkey_patch import replace_llama_attn_with_flash_attn replace_llama_attn_with_flash_attn() if "llama2-7b" in base_model: fp16 = False bf16 = True # allow set token directly use_auth_token = os.environ.get("HUGGING_FACE_HUB_TOKEN", use_auth_token) prompt_type = str(prompt_type) # migration from integers assert prompt_type in prompt_types world_size = int(os.getenv("WORLD_SIZE", 1)) local_rank = int(os.getenv("LOCAL_RANK", 0)) rank = int(os.getenv("RANK", 0)) print(f"local_rank: {local_rank}") print(f"global rank: {rank}") gpus = max(world_size, torch.cuda.device_count()) run_id = run_id or 0 if not data_path: raise ValueError("No data_path provided") if not output_dir: output_dir = f"{base_model.split('/')[-1]}.{data_path.replace('/', '')}.{num_epochs}_epochs.{get_githash() or 'nogit'}.{run_id}" if os.path.exists(output_dir) and not resume_from_checkpoint: raise FileExistsError( f"output_dir {output_dir} based on run_id {run_id} already exists. Please pick a different run_id.") else: if os.path.exists(output_dir) and not resume_from_checkpoint: raise FileExistsError( f"output_dir {output_dir} already exists. Please pick a different output_dir, or specify a run_id instead.") device_map = "auto" if save_code: copy_code(run_id) if tokenizer_base_model is None: tokenizer_base_model = base_model if llama_type is None: llama_type = "llama" in base_model.lower() if llama_type and llama_flash_attn: from importlib.metadata import distribution, PackageNotFoundError try: distribution('flash_attn') can_do_flash_attn = True except (PackageNotFoundError, AssertionError): can_do_flash_attn = False if not can_do_flash_attn: raise RuntimeError("""Flash attention not installed. NOTE: for current pytorch 2.0, flash attention requires installing cuda 11.7 via https://developer.nvidia.com/cuda-11-7-0-download-archive?target_os=Linux&target_arch=x86_64&Distribution=Ubuntu&target_version=20.04&target_type=runfile_local and then when running, to avoid installing driver, docs, samples, just install toolkit. Then when pip installing flash attention do: CUDA_HOME=/usr/local/cuda-11.7 pip install flash-attn""") assert ( base_model ), "Please specify a --base_model, e.g. --base_model='decapoda-research/llama-7b-hf'" gradient_accumulation_steps = batch_size // micro_batch_size assert gradient_accumulation_steps >= world_size, "must increase batch_size for multi-GPU" device_map = "auto" locals_dict = locals() locals_print = '\n'.join(['%s: %s' % (k, v) for k, v in locals_dict.items()]) log(f"Training model with params:\n{locals_print}") log("Command: %s\nHash: %s" % (str(' '.join(sys.argv)), get_githash())) max_memory = None if gpus > 1: if ddp: log("Distributed: data parallel") device_map = {"": int(os.environ.get("LOCAL_RANK") or 0)} gradient_accumulation_steps = gradient_accumulation_steps // world_size else: free_in_GB = int(min(torch.cuda.mem_get_info()) / 1024 ** 3) max_memory = f"{free_in_GB - 2}GB" max_memory = {i: max_memory for i in range(gpus)} log("world_size: %d" % world_size) log("num_gpus: %d" % gpus) log("max mem: %s" % max_memory) model_loader, tokenizer_loader, conditional_type = ( get_loaders(model_name=base_model, reward_type=False, llama_type=llama_type)) model = model_loader( base_model, load_in_8bit=train_8bit, load_in_4bit=train_4bit, device_map=device_map, torch_dtype=torch.float16, max_memory=max_memory, local_files_only=local_files_only, trust_remote_code=True, resume_download=resume_download, token=use_auth_token, ) print(model) if gpus > 1: if not ddp: log("model parallel") model.is_parallelizable = True model.model_parallel = True tokenizer = get_tokenizer(tokenizer_loader, tokenizer_base_model, local_files_only, resume_download, use_auth_token) if train_8bit or train_4bit: from peft import ( prepare_model_for_kbit_training, ) model = prepare_model_for_kbit_training(model) from peft import LoraConfig, get_peft_model, set_peft_model_state_dict try: from peft import utils lora_mappings = utils.TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() except AttributeError: from peft import mapping lora_mappings = mapping.TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() lora_mappings['distilgpt2'] = ["c_attn"] if lora_weights: from peft import PeftModel model = PeftModel.from_pretrained( model, lora_weights, torch_dtype=torch.float16, device_map=device_map, local_files_only=local_files_only, resume_download=resume_download, token=use_auth_token, ) elif lora_r > 0: if lora_target_modules is None: base_model_lower = base_model.lower() if base_model_lower in lora_mappings: lora_target_modules_cand = [lora_mappings[base_model_lower]] else: lora_target_modules_cand = [["query_key_value"], ["q_proj", "v_proj"]] else: lora_target_modules_cand = [lora_target_modules] for lora_target_modules in lora_target_modules_cand: try: config = LoraConfig( r=lora_r, lora_alpha=lora_alpha, target_modules=lora_target_modules, lora_dropout=lora_dropout, bias="none", task_type="CAUSAL_LM", ) model = get_peft_model(model, config) break except ValueError as e: if "Target modules" in str(e) and "not found" in str(e): continue else: raise from peft import PeftModel assert isinstance(model, PeftModel), "LoRA failed. Please provide --lora_target_modules explicitly." if resume_from_checkpoint: # Check the available weights and load them checkpoint_name = os.path.join( resume_from_checkpoint, "pytorch_model.bin" ) # Full checkpoint if not os.path.exists(checkpoint_name): checkpoint_name = os.path.join( resume_from_checkpoint, "adapter_model.bin" ) # only LoRA model - LoRA config above has to fit resume_from_checkpoint = False # So the trainer won't try loading its state # The two files above have a different name depending on how they were saved, but are actually the same. if os.path.exists(checkpoint_name): log(f"Restarting from {checkpoint_name}") adapters_weights = torch.load(checkpoint_name) set_peft_model_state_dict(model, adapters_weights) else: log(f"Checkpoint {checkpoint_name} not found") print(model) try: # only for PeftModel model.print_trainable_parameters() # Be more transparent about the % of trainable params. except: pass metrics = {} for name in supported_metrics: if name in val_metrics: import evaluate # Causes hang for 'python generate.py' on dual 4090 if imported early, 100% reproducible metrics[name] = evaluate.load(name) log("Using Validation Metrics: %s" % str(list(metrics.keys()))) log("Supported Metrics: %s" % supported_metrics) if val_set_size is None: if len(metrics) == 0: val_set_size = 1000 else: val_set_size = 100 log("Auto set val_set_size %s" % val_set_size) elif val_set_size < 1.0 and val_set_size != 0: raise RuntimeError("Fractional validation size not supported.") from datasets import load_dataset, concatenate_datasets if valid_path: data = load_dataset("json", data_files={"train": data_path, "valid": valid_path}) else: if "json" in data_path: data = load_dataset("json", data_files={"train": data_path}) else: data = load_dataset(data_path) data = data.rename_columns(data_col_dict or {}) valid_data = None train_data_mix_in = None valid_data_mix_in = None if data_mix_in_path and data_mix_in_factor > 0: # get mix-in training/validation data - to keep model "sane" num_rows = data["train"].num_rows log("Loading mix-in dataset: %s" % data_mix_in_path) if "json" in data_mix_in_path: data_mix_in = load_dataset("json", data_files={"train": data_mix_in_path})["train"] else: data_mix_in = load_dataset(data_mix_in_path)["train"] # can be large data_mix_in = data_mix_in.rename_columns(data_mix_in_col_dict or {}) mix_in_rows = int(num_rows * data_mix_in_factor) if mix_in_rows > data_mix_in.num_rows: # duplicate rows if mix-in is smaller than required log("Duplicating mixin to compensate for its size for training size and mixin fraction") data_mix_in = concatenate_datasets([data_mix_in] * int(np.ceil(mix_in_rows / data_mix_in.num_rows))) # only get as much as we need to balance valid_size = min(data_mix_in.num_rows // 2, val_set_size or 0) train_size = max(1, min(data_mix_in.num_rows - valid_size, mix_in_rows)) mixin_small = data_mix_in.train_test_split( test_size=train_size + valid_size, shuffle=True, seed=np.random.randint(10000), )["test"] if valid_size: mixin_train_test = mixin_small.train_test_split( test_size=valid_size, shuffle=False, ) train_data_mix_in = mixin_train_test["train"] valid_data_mix_in = mixin_train_test["test"] else: train_data_mix_in = mixin_small if "prompt_type" not in train_data_mix_in.column_names: train_data_mix_in = train_data_mix_in.add_column( "prompt_type", [data_mix_in_prompt_type] * train_data_mix_in.num_rows, ) log("Added prompt type %s to mix-in training data" % data_mix_in_prompt_type) if valid_data_mix_in and "prompt_type" not in valid_data_mix_in.column_names: valid_data_mix_in = valid_data_mix_in.add_column( "prompt_type", [data_mix_in_prompt_type] * valid_data_mix_in.num_rows, ) log("Added prompt type %s to mix-in validation data" % data_mix_in_prompt_type) log("Created mix-in data:\nTrain %s\nValid %s" % (train_data_mix_in, valid_data_mix_in)) # get our own training/validation data - for fine-tuning if val_set_size > 0 and not valid_path and not data_mix_in_path: # create valid split from train train_val = data["train"].train_test_split( test_size=val_set_size, shuffle=True, seed=42 ) train_data = train_val["train"] valid_data = train_val["test"] else: train_data = data["train"] if valid_path: # use given valid split, has priority over data_mix_in_path valid_data = data["valid"] if "prompt_type" not in train_data.column_names: train_data = train_data.add_column( "prompt_type", [prompt_type] * train_data.num_rows, ) log("Added prompt type %s to training data" % prompt_type) if valid_data and "prompt_type" not in valid_data.column_names: valid_data = valid_data.add_column( "prompt_type", [prompt_type] * valid_data.num_rows, ) log("Added prompt type %s to validation data" % prompt_type) assert train_data is not None 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) # shuffle and tokenize data if train_data_mix_in: train_data = concatenate_datasets([train_data, train_data_mix_in]) log("Tokenizing %s training rows" % train_data.num_rows) train_data = train_data.shuffle().map(generate_and_tokenize_prompt_fun, num_proc=os.cpu_count() // torch.cuda.device_count()) if drop_truncations: log("avoid keeping truncated cases to avoid contaminating model with truncation cases. Original size: %s" % train_data.num_rows) prune_long_sequences_func = partial(prune_long_sequences, cutoff_len=cutoff_len) train_data = train_data.filter(prune_long_sequences_func, num_proc=os.cpu_count() // torch.cuda.device_count()) log("avoid keeping truncated cases to avoid contaminating model with truncation cases. New size: %s" % train_data.num_rows) train_set_size = len(train_data) if valid_data and valid_data_mix_in: valid_data = concatenate_datasets([valid_data, valid_data_mix_in]) elif valid_data_mix_in: valid_data = valid_data_mix_in if valid_data: log("Tokenizing %s validation rows" % valid_data.num_rows) valid_data = valid_data.shuffle().map(generate_and_tokenize_prompt_fun, num_proc=os.cpu_count() // torch.cuda.device_count()) val_set_size = len(valid_data) else: val_set_size = 0 log("Final fine-tuning data:\nTrain %s\nValid %s" % (train_data, valid_data)) sample_row_dict = train_data[:1] del sample_row_dict['input_ids'] del sample_row_dict['attention_mask'] del sample_row_dict['labels'] log("Sample input: %s" % sample_row_dict) try: import neptune from transformers.integrations import NeptuneCallback neptune_run = neptune.init_run( source_files=[], ) log("Connected to Neptune.") except ImportError: neptune_run = None log("Please pip install neptune for tracking.") except neptune.exceptions.NeptuneMissingApiTokenException: neptune_run = None os.environ["NEPTUNE_MODE"] = 'debug' log("No neptune configured, set NEPTUNE_API_TOKEN env var.") if neptune_run: neptune_callback = NeptuneCallback(run=neptune_run) callbacks = [neptune_callback] else: from transformers.integrations import TensorBoardCallback, is_tensorboard_available if is_tensorboard_available: # tensorboard --logdir=runs/ from torch.utils.tensorboard import SummaryWriter tb_writer = SummaryWriter() callbacks = [TensorBoardCallback(tb_writer=tb_writer)] else: callbacks = [] expected_steps = (train_set_size * num_epochs) // batch_size if eval_steps is None and eval_epochs is None: # 20 evaluations for a run eval_steps = max(1, int(expected_steps / 20)) log("Auto set eval_steps to %s out of %s total training steps" % (eval_steps, expected_steps)) elif eval_steps is None and eval_epochs is not None: eval_steps = max(1, int(expected_steps * eval_epochs / num_epochs)) log("Auto converted eval_epochs=%s to eval_steps %s" " out of %s total training steps" % (eval_epochs, eval_steps, expected_steps)) if save_steps is None: save_steps = eval_steps log("Auto step save_steps to %s" % save_steps) elif save_steps > eval_steps: # save steps must be round multiple of eval_steps save_steps0 = save_steps save_steps = max(1, (save_steps // eval_steps)) * eval_steps if save_steps0 != save_steps: log("Auto converted save_steps from %s to %s" % (save_steps0, save_steps)) def compute_metrics(eval_preds): # e.g. see: https://huggingface.co/docs/transformers/v4.25.1/en/tasks/translation#evaluate inputs = eval_preds.inputs label_ids = eval_preds.label_ids predictions = eval_preds.predictions # inputs = np.where(inputs != -100, inputs, tokenizer.pad_token_id) # decoded_inputs = tokenizer.batch_decode(inputs, skip_special_tokens=True) # decoded_inputs = [pred.strip() for pred in decoded_inputs] label_ids = np.where(label_ids != -100, label_ids, tokenizer.pad_token_id) # tokenizer behavior like generate time decoded_labels = tokenizer.batch_decode(label_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True) decoded_labels = [pred.strip() for pred in decoded_labels] predictions = np.argmax(predictions, -1) predictions = np.where(predictions != -100, predictions, tokenizer.pad_token_id) # tokenizer behavior like generate time decoded_predictions = tokenizer.batch_decode(predictions, skip_special_tokens=True, clean_up_tokenization_spaces=True) decoded_predictions = [pred.strip() for pred in decoded_predictions] result = {} for metric in metrics.values(): result1 = metric.compute(predictions=decoded_predictions, references=decoded_labels) # get rid of lists, for precision etc., for now numeric_results = {k: v for k, v in result1.items() if isinstance(v, (int, float))} result.update(numeric_results) return result # the callback that computes metrics of interest if val_metrics: trainer_kwargs = dict(compute_metrics=compute_metrics) else: trainer_kwargs = dict() import transformers trainer = transformers.Trainer( model=model, tokenizer=tokenizer, train_dataset=train_data, eval_dataset=valid_data, # FIXME: might need Seq2SeqTrainingArguments for some models args=transformers.TrainingArguments( per_device_train_batch_size=micro_batch_size, per_device_eval_batch_size=1, eval_accumulation_steps=10, # predict_with_generate=True, # SEQ2SEQ only include_inputs_for_metrics=True, gradient_accumulation_steps=gradient_accumulation_steps, warmup_steps=warmup_steps, num_train_epochs=num_epochs, learning_rate=learning_rate, gradient_checkpointing=gradient_checkpointing, bf16=bf16, fp16=fp16, # cosnider 8-bit adam: https://huggingface.co/docs/transformers/v4.18.0/en/performance#8bit-adam optim="adamw_torch", # consider "adafactor" to save memory logging_steps=logging_steps, logging_strategy="steps", evaluation_strategy="steps" if val_set_size > 0 else "no", save_strategy="steps", eval_steps=eval_steps if val_set_size > 0 else None, save_steps=save_steps, output_dir=output_dir, save_total_limit=save_total_limit, load_best_model_at_end=True if val_set_size > 0 else False, ddp_find_unused_parameters=False if ddp else None, group_by_length=group_by_length, # fsdp=gpus > 1 and not ddp, report_to='tensorboard' if not neptune_run else 'neptune', ), data_collator=transformers.DataCollatorForSeq2Seq( tokenizer, pad_to_multiple_of=8, return_tensors="pt", padding=True ), callbacks=callbacks, **trainer_kwargs, ) model.config.use_cache = False if torch.__version__ >= "2" and sys.platform != "win32": model = torch.compile(model) # WIP (not generally replacing layers until pytorch 2.1) if not llama_flash_attn: torch.backends.cuda.enable_flash_sdp(True) if gpus > 1 and not ddp: assert trainer.is_model_parallel else: assert not trainer.is_model_parallel trainer.train(resume_from_checkpoint=resume_from_checkpoint) model.save_pretrained(output_dir) log("\n If there's a warning about missing keys above, please disregard :)") def H2O_Fire(component=None): config_prefix = "H2OGPT_" args = sys.argv[1:] query_args = [arg.split("=")[0].split(" ")[0].lstrip("-") for arg in args] fn_spec = inspectutils.GetFullArgSpec(component) for key, value in os.environ.items(): if not ( (key.startswith(config_prefix) or key.startswith(config_prefix.lower())) and len(key) > len(config_prefix) ): continue # ignore as non H2OGPT argument new_key = key[len(config_prefix):].lower() if new_key in query_args: continue # ignore as already passed as script argument if new_key not in fn_spec.args: continue # ignore as not a valid H2OGPT argument args.append(f"--{new_key}={value}") fire.Fire(component=component, command=args) def test_debug(): H2O_Fire(train)
null
167,173
import os import sys from functools import partial from typing import List, Union import numpy as np if os.path.dirname(os.path.abspath(__file__)) not in sys.path: sys.path.append(os.path.dirname(os.path.abspath(__file__))) if os.path.dirname('src') not in sys.path: sys.path.append('src') from src.loaders import get_loaders, get_tokenizer from src.prompter import generate_prompt, prompt_types, PromptType from src.utils import get_githash, copy_code, H2O_Fire import torch def log(*args, **kwargs): if int(os.environ.get("LOCAL_RANK", 0)) == 0: if 'flush' not in kwargs: kwargs['flush'] = True print(*args, **kwargs) def train( save_code: bool = False, run_id: int = None, base_model: str = 'h2oai/h2ogpt-4096-llama2-7b', # base_model: str = 'h2oai/h2ogpt-4096-llama2-13b', # base_model: str = 'h2oai/h2ogpt-4096-llama2-70b', # only needed if base_model is self-exported HF state without tokenizer tokenizer_base_model: str = None, # tokenizer_base_model: str = 'EleutherAI/gpt-neox-20b', data_path: str = "h2oai/openassistant_oasst1_h2ogpt", data_col_dict: dict = None, # data_path: str = "./dai_docs.train.json", prompt_type: Union[str, int] = "plain", # "plain", "instruct", "quality", "human_bot", "dai_faq" valid_path: str = None, # valid_path: str = "./dai_docs.valid.json", # data_mix_in_path: str = "laion/OIG", # way too big, medium quality data_mix_in_path: str = "0-hero/OIG-small-chip2", # high quality, 50 MB, good enough for now data_mix_in_factor: float = 0.0, # >1: more mix-in data, <1: more of data_path data data_mix_in_col_dict: dict = {'user': 'instruction', 'chip2': 'output'}, data_mix_in_prompt_type: str = "instruct", # just instruction->output, same as instruct output_dir: str = None, # LoRA checkpoint continuation lora_weights: str = "", # batching training hyperparams batch_size: int = 128, micro_batch_size: int = 4, gradient_checkpointing=False, # unnecessary with gradient accumulation enabled bf16=False, # needed (and automatically enabled) for llama2-7b fp16=True, train_8bit=False, train_4bit=False, # general training hyperparams num_epochs: float = 1, learning_rate: float = 3e-4, # validation settings val_set_size: int = None, val_metrics: List[str] = [], eval_steps: int = None, # to control eval steps via steps eval_epochs: float = None, # to control eval steps via epochs # lora hyperparams lora_r: int = 8, lora_alpha: int = 16, lora_dropout: float = 0.05, lora_target_modules: List[str] = None, llama_type: bool = None, llama_flash_attn: bool = False, # llm hyperparams train_on_inputs: bool = True, # if False, masks out inputs in loss group_by_length: bool = False, # if True, faster, but produces an odd training loss curve resume_from_checkpoint: str = None, # either training checkpoint or final adapter cutoff_len: int = 512, # larger values use more memory drop_truncations: bool = False, # if True, drop any truncated long sequences # torch training params ddp: bool = True, # set to False if OOM with True, for multi-GPU model parallelism local_files_only: bool = False, # else will download new versions, normally unwanted resume_download: bool = True, use_auth_token: Union[str, bool] = False, # True requires CLI did huggingface-cli login before running warmup_steps: int = 100, logging_steps: int = 1, save_steps: int = None, # must be round multiple of eval_steps save_total_limit: int = 3, add_eos_token: bool = False, ): if llama_flash_attn: # Need to call this before importing transformers. from src.llama_flash_attn_monkey_patch import replace_llama_attn_with_flash_attn replace_llama_attn_with_flash_attn() if "llama2-7b" in base_model: fp16 = False bf16 = True # allow set token directly use_auth_token = os.environ.get("HUGGING_FACE_HUB_TOKEN", use_auth_token) prompt_type = str(prompt_type) # migration from integers assert prompt_type in prompt_types world_size = int(os.getenv("WORLD_SIZE", 1)) local_rank = int(os.getenv("LOCAL_RANK", 0)) rank = int(os.getenv("RANK", 0)) print(f"local_rank: {local_rank}") print(f"global rank: {rank}") gpus = max(world_size, torch.cuda.device_count()) run_id = run_id or 0 if not data_path: raise ValueError("No data_path provided") if not output_dir: output_dir = f"{base_model.split('/')[-1]}.{data_path.replace('/', '')}.{num_epochs}_epochs.{get_githash() or 'nogit'}.{run_id}" if os.path.exists(output_dir) and not resume_from_checkpoint: raise FileExistsError( f"output_dir {output_dir} based on run_id {run_id} already exists. Please pick a different run_id.") else: if os.path.exists(output_dir) and not resume_from_checkpoint: raise FileExistsError( f"output_dir {output_dir} already exists. Please pick a different output_dir, or specify a run_id instead.") device_map = "auto" if save_code: copy_code(run_id) if tokenizer_base_model is None: tokenizer_base_model = base_model if llama_type is None: llama_type = "llama" in base_model.lower() if llama_type and llama_flash_attn: from importlib.metadata import distribution, PackageNotFoundError try: distribution('flash_attn') can_do_flash_attn = True except (PackageNotFoundError, AssertionError): can_do_flash_attn = False if not can_do_flash_attn: raise RuntimeError("""Flash attention not installed. NOTE: for current pytorch 2.0, flash attention requires installing cuda 11.7 via https://developer.nvidia.com/cuda-11-7-0-download-archive?target_os=Linux&target_arch=x86_64&Distribution=Ubuntu&target_version=20.04&target_type=runfile_local and then when running, to avoid installing driver, docs, samples, just install toolkit. Then when pip installing flash attention do: CUDA_HOME=/usr/local/cuda-11.7 pip install flash-attn""") assert ( base_model ), "Please specify a --base_model, e.g. --base_model='decapoda-research/llama-7b-hf'" gradient_accumulation_steps = batch_size // micro_batch_size assert gradient_accumulation_steps >= world_size, "must increase batch_size for multi-GPU" device_map = "auto" locals_dict = locals() locals_print = '\n'.join(['%s: %s' % (k, v) for k, v in locals_dict.items()]) log(f"Training model with params:\n{locals_print}") log("Command: %s\nHash: %s" % (str(' '.join(sys.argv)), get_githash())) max_memory = None if gpus > 1: if ddp: log("Distributed: data parallel") device_map = {"": int(os.environ.get("LOCAL_RANK") or 0)} gradient_accumulation_steps = gradient_accumulation_steps // world_size else: free_in_GB = int(min(torch.cuda.mem_get_info()) / 1024 ** 3) max_memory = f"{free_in_GB - 2}GB" max_memory = {i: max_memory for i in range(gpus)} log("world_size: %d" % world_size) log("num_gpus: %d" % gpus) log("max mem: %s" % max_memory) model_loader, tokenizer_loader, conditional_type = ( get_loaders(model_name=base_model, reward_type=False, llama_type=llama_type)) model = model_loader( base_model, load_in_8bit=train_8bit, load_in_4bit=train_4bit, device_map=device_map, torch_dtype=torch.float16, max_memory=max_memory, local_files_only=local_files_only, trust_remote_code=True, resume_download=resume_download, token=use_auth_token, ) print(model) if gpus > 1: if not ddp: log("model parallel") model.is_parallelizable = True model.model_parallel = True tokenizer = get_tokenizer(tokenizer_loader, tokenizer_base_model, local_files_only, resume_download, use_auth_token) if train_8bit or train_4bit: from peft import ( prepare_model_for_kbit_training, ) model = prepare_model_for_kbit_training(model) from peft import LoraConfig, get_peft_model, set_peft_model_state_dict try: from peft import utils lora_mappings = utils.TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() except AttributeError: from peft import mapping lora_mappings = mapping.TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() lora_mappings['distilgpt2'] = ["c_attn"] if lora_weights: from peft import PeftModel model = PeftModel.from_pretrained( model, lora_weights, torch_dtype=torch.float16, device_map=device_map, local_files_only=local_files_only, resume_download=resume_download, token=use_auth_token, ) elif lora_r > 0: if lora_target_modules is None: base_model_lower = base_model.lower() if base_model_lower in lora_mappings: lora_target_modules_cand = [lora_mappings[base_model_lower]] else: lora_target_modules_cand = [["query_key_value"], ["q_proj", "v_proj"]] else: lora_target_modules_cand = [lora_target_modules] for lora_target_modules in lora_target_modules_cand: try: config = LoraConfig( r=lora_r, lora_alpha=lora_alpha, target_modules=lora_target_modules, lora_dropout=lora_dropout, bias="none", task_type="CAUSAL_LM", ) model = get_peft_model(model, config) break except ValueError as e: if "Target modules" in str(e) and "not found" in str(e): continue else: raise from peft import PeftModel assert isinstance(model, PeftModel), "LoRA failed. Please provide --lora_target_modules explicitly." if resume_from_checkpoint: # Check the available weights and load them checkpoint_name = os.path.join( resume_from_checkpoint, "pytorch_model.bin" ) # Full checkpoint if not os.path.exists(checkpoint_name): checkpoint_name = os.path.join( resume_from_checkpoint, "adapter_model.bin" ) # only LoRA model - LoRA config above has to fit resume_from_checkpoint = False # So the trainer won't try loading its state # The two files above have a different name depending on how they were saved, but are actually the same. if os.path.exists(checkpoint_name): log(f"Restarting from {checkpoint_name}") adapters_weights = torch.load(checkpoint_name) set_peft_model_state_dict(model, adapters_weights) else: log(f"Checkpoint {checkpoint_name} not found") print(model) try: # only for PeftModel model.print_trainable_parameters() # Be more transparent about the % of trainable params. except: pass metrics = {} for name in supported_metrics: if name in val_metrics: import evaluate # Causes hang for 'python generate.py' on dual 4090 if imported early, 100% reproducible metrics[name] = evaluate.load(name) log("Using Validation Metrics: %s" % str(list(metrics.keys()))) log("Supported Metrics: %s" % supported_metrics) if val_set_size is None: if len(metrics) == 0: val_set_size = 1000 else: val_set_size = 100 log("Auto set val_set_size %s" % val_set_size) elif val_set_size < 1.0 and val_set_size != 0: raise RuntimeError("Fractional validation size not supported.") from datasets import load_dataset, concatenate_datasets if valid_path: data = load_dataset("json", data_files={"train": data_path, "valid": valid_path}) else: if "json" in data_path: data = load_dataset("json", data_files={"train": data_path}) else: data = load_dataset(data_path) data = data.rename_columns(data_col_dict or {}) valid_data = None train_data_mix_in = None valid_data_mix_in = None if data_mix_in_path and data_mix_in_factor > 0: # get mix-in training/validation data - to keep model "sane" num_rows = data["train"].num_rows log("Loading mix-in dataset: %s" % data_mix_in_path) if "json" in data_mix_in_path: data_mix_in = load_dataset("json", data_files={"train": data_mix_in_path})["train"] else: data_mix_in = load_dataset(data_mix_in_path)["train"] # can be large data_mix_in = data_mix_in.rename_columns(data_mix_in_col_dict or {}) mix_in_rows = int(num_rows * data_mix_in_factor) if mix_in_rows > data_mix_in.num_rows: # duplicate rows if mix-in is smaller than required log("Duplicating mixin to compensate for its size for training size and mixin fraction") data_mix_in = concatenate_datasets([data_mix_in] * int(np.ceil(mix_in_rows / data_mix_in.num_rows))) # only get as much as we need to balance valid_size = min(data_mix_in.num_rows // 2, val_set_size or 0) train_size = max(1, min(data_mix_in.num_rows - valid_size, mix_in_rows)) mixin_small = data_mix_in.train_test_split( test_size=train_size + valid_size, shuffle=True, seed=np.random.randint(10000), )["test"] if valid_size: mixin_train_test = mixin_small.train_test_split( test_size=valid_size, shuffle=False, ) train_data_mix_in = mixin_train_test["train"] valid_data_mix_in = mixin_train_test["test"] else: train_data_mix_in = mixin_small if "prompt_type" not in train_data_mix_in.column_names: train_data_mix_in = train_data_mix_in.add_column( "prompt_type", [data_mix_in_prompt_type] * train_data_mix_in.num_rows, ) log("Added prompt type %s to mix-in training data" % data_mix_in_prompt_type) if valid_data_mix_in and "prompt_type" not in valid_data_mix_in.column_names: valid_data_mix_in = valid_data_mix_in.add_column( "prompt_type", [data_mix_in_prompt_type] * valid_data_mix_in.num_rows, ) log("Added prompt type %s to mix-in validation data" % data_mix_in_prompt_type) log("Created mix-in data:\nTrain %s\nValid %s" % (train_data_mix_in, valid_data_mix_in)) # get our own training/validation data - for fine-tuning if val_set_size > 0 and not valid_path and not data_mix_in_path: # create valid split from train train_val = data["train"].train_test_split( test_size=val_set_size, shuffle=True, seed=42 ) train_data = train_val["train"] valid_data = train_val["test"] else: train_data = data["train"] if valid_path: # use given valid split, has priority over data_mix_in_path valid_data = data["valid"] if "prompt_type" not in train_data.column_names: train_data = train_data.add_column( "prompt_type", [prompt_type] * train_data.num_rows, ) log("Added prompt type %s to training data" % prompt_type) if valid_data and "prompt_type" not in valid_data.column_names: valid_data = valid_data.add_column( "prompt_type", [prompt_type] * valid_data.num_rows, ) log("Added prompt type %s to validation data" % prompt_type) assert train_data is not None 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) # shuffle and tokenize data if train_data_mix_in: train_data = concatenate_datasets([train_data, train_data_mix_in]) log("Tokenizing %s training rows" % train_data.num_rows) train_data = train_data.shuffle().map(generate_and_tokenize_prompt_fun, num_proc=os.cpu_count() // torch.cuda.device_count()) if drop_truncations: log("avoid keeping truncated cases to avoid contaminating model with truncation cases. Original size: %s" % train_data.num_rows) prune_long_sequences_func = partial(prune_long_sequences, cutoff_len=cutoff_len) train_data = train_data.filter(prune_long_sequences_func, num_proc=os.cpu_count() // torch.cuda.device_count()) log("avoid keeping truncated cases to avoid contaminating model with truncation cases. New size: %s" % train_data.num_rows) train_set_size = len(train_data) if valid_data and valid_data_mix_in: valid_data = concatenate_datasets([valid_data, valid_data_mix_in]) elif valid_data_mix_in: valid_data = valid_data_mix_in if valid_data: log("Tokenizing %s validation rows" % valid_data.num_rows) valid_data = valid_data.shuffle().map(generate_and_tokenize_prompt_fun, num_proc=os.cpu_count() // torch.cuda.device_count()) val_set_size = len(valid_data) else: val_set_size = 0 log("Final fine-tuning data:\nTrain %s\nValid %s" % (train_data, valid_data)) sample_row_dict = train_data[:1] del sample_row_dict['input_ids'] del sample_row_dict['attention_mask'] del sample_row_dict['labels'] log("Sample input: %s" % sample_row_dict) try: import neptune from transformers.integrations import NeptuneCallback neptune_run = neptune.init_run( source_files=[], ) log("Connected to Neptune.") except ImportError: neptune_run = None log("Please pip install neptune for tracking.") except neptune.exceptions.NeptuneMissingApiTokenException: neptune_run = None os.environ["NEPTUNE_MODE"] = 'debug' log("No neptune configured, set NEPTUNE_API_TOKEN env var.") if neptune_run: neptune_callback = NeptuneCallback(run=neptune_run) callbacks = [neptune_callback] else: from transformers.integrations import TensorBoardCallback, is_tensorboard_available if is_tensorboard_available: # tensorboard --logdir=runs/ from torch.utils.tensorboard import SummaryWriter tb_writer = SummaryWriter() callbacks = [TensorBoardCallback(tb_writer=tb_writer)] else: callbacks = [] expected_steps = (train_set_size * num_epochs) // batch_size if eval_steps is None and eval_epochs is None: # 20 evaluations for a run eval_steps = max(1, int(expected_steps / 20)) log("Auto set eval_steps to %s out of %s total training steps" % (eval_steps, expected_steps)) elif eval_steps is None and eval_epochs is not None: eval_steps = max(1, int(expected_steps * eval_epochs / num_epochs)) log("Auto converted eval_epochs=%s to eval_steps %s" " out of %s total training steps" % (eval_epochs, eval_steps, expected_steps)) if save_steps is None: save_steps = eval_steps log("Auto step save_steps to %s" % save_steps) elif save_steps > eval_steps: # save steps must be round multiple of eval_steps save_steps0 = save_steps save_steps = max(1, (save_steps // eval_steps)) * eval_steps if save_steps0 != save_steps: log("Auto converted save_steps from %s to %s" % (save_steps0, save_steps)) def compute_metrics(eval_preds): # e.g. see: https://huggingface.co/docs/transformers/v4.25.1/en/tasks/translation#evaluate inputs = eval_preds.inputs label_ids = eval_preds.label_ids predictions = eval_preds.predictions # inputs = np.where(inputs != -100, inputs, tokenizer.pad_token_id) # decoded_inputs = tokenizer.batch_decode(inputs, skip_special_tokens=True) # decoded_inputs = [pred.strip() for pred in decoded_inputs] label_ids = np.where(label_ids != -100, label_ids, tokenizer.pad_token_id) # tokenizer behavior like generate time decoded_labels = tokenizer.batch_decode(label_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True) decoded_labels = [pred.strip() for pred in decoded_labels] predictions = np.argmax(predictions, -1) predictions = np.where(predictions != -100, predictions, tokenizer.pad_token_id) # tokenizer behavior like generate time decoded_predictions = tokenizer.batch_decode(predictions, skip_special_tokens=True, clean_up_tokenization_spaces=True) decoded_predictions = [pred.strip() for pred in decoded_predictions] result = {} for metric in metrics.values(): result1 = metric.compute(predictions=decoded_predictions, references=decoded_labels) # get rid of lists, for precision etc., for now numeric_results = {k: v for k, v in result1.items() if isinstance(v, (int, float))} result.update(numeric_results) return result # the callback that computes metrics of interest if val_metrics: trainer_kwargs = dict(compute_metrics=compute_metrics) else: trainer_kwargs = dict() import transformers trainer = transformers.Trainer( model=model, tokenizer=tokenizer, train_dataset=train_data, eval_dataset=valid_data, # FIXME: might need Seq2SeqTrainingArguments for some models args=transformers.TrainingArguments( per_device_train_batch_size=micro_batch_size, per_device_eval_batch_size=1, eval_accumulation_steps=10, # predict_with_generate=True, # SEQ2SEQ only include_inputs_for_metrics=True, gradient_accumulation_steps=gradient_accumulation_steps, warmup_steps=warmup_steps, num_train_epochs=num_epochs, learning_rate=learning_rate, gradient_checkpointing=gradient_checkpointing, bf16=bf16, fp16=fp16, # cosnider 8-bit adam: https://huggingface.co/docs/transformers/v4.18.0/en/performance#8bit-adam optim="adamw_torch", # consider "adafactor" to save memory logging_steps=logging_steps, logging_strategy="steps", evaluation_strategy="steps" if val_set_size > 0 else "no", save_strategy="steps", eval_steps=eval_steps if val_set_size > 0 else None, save_steps=save_steps, output_dir=output_dir, save_total_limit=save_total_limit, load_best_model_at_end=True if val_set_size > 0 else False, ddp_find_unused_parameters=False if ddp else None, group_by_length=group_by_length, # fsdp=gpus > 1 and not ddp, report_to='tensorboard' if not neptune_run else 'neptune', ), data_collator=transformers.DataCollatorForSeq2Seq( tokenizer, pad_to_multiple_of=8, return_tensors="pt", padding=True ), callbacks=callbacks, **trainer_kwargs, ) model.config.use_cache = False if torch.__version__ >= "2" and sys.platform != "win32": model = torch.compile(model) # WIP (not generally replacing layers until pytorch 2.1) if not llama_flash_attn: torch.backends.cuda.enable_flash_sdp(True) if gpus > 1 and not ddp: assert trainer.is_model_parallel else: assert not trainer.is_model_parallel trainer.train(resume_from_checkpoint=resume_from_checkpoint) model.save_pretrained(output_dir) log("\n If there's a warning about missing keys above, please disregard :)") def H2O_Fire(component=None): config_prefix = "H2OGPT_" args = sys.argv[1:] query_args = [arg.split("=")[0].split(" ")[0].lstrip("-") for arg in args] fn_spec = inspectutils.GetFullArgSpec(component) for key, value in os.environ.items(): if not ( (key.startswith(config_prefix) or key.startswith(config_prefix.lower())) and len(key) > len(config_prefix) ): continue # ignore as non H2OGPT argument new_key = key[len(config_prefix):].lower() if new_key in query_args: continue # ignore as already passed as script argument if new_key not in fn_spec.args: continue # ignore as not a valid H2OGPT argument args.append(f"--{new_key}={value}") fire.Fire(component=component, command=args) def entrypoint_main(): CONFIG = "NCCL_P2P_LEVEL=LOC WORLD_SIZE=5 torchrun --nnodes=5 --master_addr=10.10.10.2 --master_port=1111 --nproc_per_node=1" CMD = "finetune.py --data_path=config.json --num_epochs=1 --base_model=decapoda-research/llama-13b-hf" log(f""" Example runs on 4 GPUs: WORLD_SIZE=4 CUDA_VISIBLE_DEVICES="0,1,2,3" torchrun --nproc_per_node=4 finetune.py --base_model='decapoda-research/llama-7b-hf' --data_path=data/config.json --run_id=0 &> 0.log WORLD_SIZE=4 CUDA_VISIBLE_DEVICES="0,1,2,3" torchrun --nproc_per_node=4 finetune.py --base_model='decapoda-research/llama-30b-hf' --data_path=data/config.json --batch_size=16 --micro_batch_size=1 --run_id=1 --save_code=True &> 1.log WORLD_SIZE=4 CUDA_VISIBLE_DEVICES="0,1,2,3" torchrun --nproc_per_node=4 finetune.py --base_model='EleutherAI/gpt-j-6B' --data_path=data/config.json --run_id=2 &> 2.log WORLD_SIZE=4 CUDA_VISIBLE_DEVICES="0,1,2,3" torchrun --nproc_per_node=4 finetune.py --base_model='EleutherAI/gpt-neox-20b' --data_path=data/config.json --run_id=8 --batch_size=16 --micro_batch_size=4 &> 8.log WORLD_SIZE=4 CUDA_VISIBLE_DEVICES="0,1,2,3" torchrun --nproc_per_node=4 finetune.py --base_model='togethercomputer/GPT-NeoXT-Chat-Base-20B' --data_path=data/config.json --prompt_type='dai_faq' --run_id=13 --batch_size=16 --micro_batch_size=4 --num_epochs=100 --val_set_size=0 data_mix_in_path='' &> 13.log WORLD_SIZE=4 CUDA_VISIBLE_DEVICES="0,1,2,3" torchrun --nproc_per_node=4 finetune.py --base_model='togethercomputer/GPT-NeoXT-Chat-Base-20B' --data_path=data/config.json --run_id=28 --batch_size=16 --micro_batch_size=4 --num_epochs=8 --val_set_size=0 --data_mix_in_factor=0.1 --data_mix_in_prompt_type='human_bot' --save_code=True --cutoff_len=512 &> 28.log All metrics: CUDA_VISIBLE_DEVICES= finetune.py --data_mix_in_factor=0 --eval_steps=100 --warmup_steps=2 --val_set_size=100 --val_metrics="['bleu', 'rouge', 'sacrebleu', 'meteor']" # Fine-tune 20B on 24GB GPUs across 3 nodes with 3+2+2 GPUs rippa> NCCL_P2P_LEVEL=LOC WORLD_SIZE=7 CUDA_VISIBLE_DEVICES="0,1,2" torchrun --node_rank 0 --nproc_per_node=3 --master_port=1234 --nnodes=3 --master_addr=10.10.10.2 finetune.py --data_path=merged_shuffled_OIG_87f6a1e788.json --micro_batch_size=1 --batch_size=7 --cutoff_len=512 --run_id=17 &>log.17.rank0 ova> NCCL_P2P_LEVEL=LOC WORLD_SIZE=7 CUDA_VISIBLE_DEVICES="0,1" torchrun --node_rank 1 --nproc_per_node=2 --master_port=1234 --nnodes=3 --master_addr=10.10.10.2 finetune.py --data_path=merged_shuffled_OIG_87f6a1e788.json --micro_batch_size=1 --batch_size=7 --cutoff_len=512 --run_id=17 &>log.17.rank1 timemachine> NCCL_P2P_LEVEL=LOC WORLD_SIZE=7 CUDA_VISIBLE_DEVICES="0,1" torchrun --node_rank 2 --nproc_per_node=2 --master_port=1234 --nnodes=3 --master_addr=10.10.10.2 finetune.py --data_path=merged_shuffled_OIG_87f6a1e788.json --micro_batch_size=1 --batch_size=7 --cutoff_len=512 --run_id=17 &>log.17.rank2 """, flush=True) if os.environ.get("LOCAL_RANK") is None: # then not using torchrun, so can't do distributed, ensure CVD set assert os.environ.get( "CUDA_VISIBLE_DEVICES") is not None, "Run python script using: torchrun finetune.py OR set CUDA_VISIBLE_DEVICES to single GPU" H2O_Fire(train)
null
167,174
import shutil import pandas as pd import os import huggingface_hub import pytest from datasets import load_dataset def test_create_data_cards(dataset_name, link_to_source): if dataset_name != "openassistant_oasst1_h2ogpt_llama2_chat": return # assert os.path.exists("README-template.md"), "must be running this test from the data dir." shutil.rmtree(dataset_name, ignore_errors=True) try: repo = huggingface_hub.Repository( local_dir=dataset_name, clone_from="h2oai/%s" % dataset_name, repo_type="dataset", skip_lfs_files=True, token=True, ) repo.git_pull() except Exception as e: print(str(e)) print("call 'huggingface_cli login' first and provide access token with write permission") dataset = load_dataset("h2oai/%s" % dataset_name)["train"] pd.set_option('display.max_columns', None) with open("README-template.md", "r") as f: content = f.read() assert "<<DATASET_NAME>>" in content content = content.replace("<<DATASET_NAME>>", dataset_name) assert "<<NROWS>>" in content content = content.replace("<<NROWS>>", str(dataset.num_rows)) assert "<<NCOLS>>" in content content = content.replace("<<NCOLS>>", str(dataset.num_columns)) assert "<<COLNAMES>>" in content content = content.replace("<<COLNAMES>>", str(dataset.column_names)) # assert "<<PREVIEW>>" in content # content = content.replace("<<PREVIEW>>", str(dataset.to_pandas().iloc[:5, :])) assert "<<SOURCE_LINK>>" in content content = content.replace("<<SOURCE_LINK>>", link_to_source) assert "<<" not in content assert ">>" not in content with open(os.path.join(dataset_name, "README.md"), "w") as f: f.write(content) try: repo.commit("Update README.md") repo.push_to_hub() except Exception as e: print(str(e))
null
167,175
import os import sys from src.utils_sys import protect_stdout_stderr from src.gen import main from src.utils import H2O_Fire def main( load_8bit: bool = False, load_4bit: bool = False, low_bit_mode: int = 1, load_half: bool = None, use_flash_attention_2=False, load_gptq: str = '', use_autogptq: bool = False, load_awq: 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 = "", regenerate_clients: bool = True, regenerate_gradio_clients: bool = False, prompt_type: Union[int, str] = None, prompt_dict: typing.Dict = None, system_prompt: str = 'auto', allow_chat_system_prompt: bool = True, # llama and gpt4all settings llamacpp_path: str = 'llamacpp_path', llamacpp_dict: typing.Dict = dict(n_gpu_layers=100, use_mlock=True, n_batch=1024, n_gqa=0), model_path_llama: str = '', model_name_gptj: str = '', model_name_gpt4all_llama: str = '', model_name_exllama_if_no_config: str = '', exllama_dict: typing.Dict = dict(), gptq_dict: typing.Dict = dict(), attention_sinks: bool = False, sink_dict: typing.Dict = dict(), truncation_generation: bool = False, hf_model_dict: typing.Dict = dict(), model_lock: typing.List[typing.Dict[str, str]] = None, model_lock_columns: int = None, model_lock_layout_based_upon_initial_visible: bool = False, fail_if_cannot_connect: bool = False, # input to generation temperature: float = None, top_p: float = None, top_k: int = None, penalty_alpha: float = 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, 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, max_output_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, openai_server: bool = True, openai_port: int = 5001 if sys.platform == "darwin" else 5000, gradio_offline_level: int = 0, server_name: str = "0.0.0.0", share: bool = False, open_browser: bool = False, close_button: bool = True, shutdown_via_api: bool = False, root_path: str = "", ssl_verify: bool = True, ssl_keyfile: str | None = None, ssl_certfile: str | None = None, ssl_keyfile_password: str | None = None, 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, render_markdown: bool = True, 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 = None, 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, gradio_ui_stream_chunk_size: int = None, gradio_ui_stream_chunk_min_seconds: float = 0.2, gradio_ui_stream_chunk_seconds: float = 2.0, gradio_api_use_same_stream_limits: bool = True, gradio_upload_to_chatbot: bool = False, gradio_upload_to_chatbot_num_max: bool = 2, gradio_errors_to_chatbot: bool = True, pre_load_embedding_model: bool = True, embedding_gpu_id: Union[int, str] = 'auto', 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, enforce_h2ogpt_ui_key: bool = None, h2ogpt_api_keys: Union[list, str] = [], h2ogpt_key: str = None, extra_allowed_paths: list = [], blocked_paths: list = [], max_max_time=None, max_max_new_tokens=None, visible_models: list = None, max_visible_models: int = None, visible_ask_anything_high: bool = True, 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_links: bool = True, visible_h2ogpt_qrcode: bool = True, visible_h2ogpt_logo: bool = True, visible_chatbot_label: bool = True, visible_all_prompter_models: bool = False, visible_curated_models: bool = True, actions_in_sidebar: bool = False, document_choice_in_sidebar: bool = True, enable_add_models_to_list_ui: bool = False, max_raw_chunks: int = None, pdf_height: int = 800, avatars: bool = True, add_disk_models_to_ui: bool = True, page_title: str = "h2oGPT", model_label_prefix: str = "h2oGPT", favicon_path: str = None, visible_ratings: bool = False, reviews_file: str = 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', verifier_model: str = None, verifier_tokenizer_base_model: str = None, verifier_inference_server: str = None, 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 = base_langchain_actions.copy(), visible_langchain_agents: list = langchain_agents_list.copy(), document_subset: str = DocumentSubset.Relevant.name, document_choice: list = [DocumentChoice.ALL.value], document_source_substrings: list = [], document_source_substrings_op: str = 'and', document_content_substrings: list = [], document_content_substrings_op: str = 'and', 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 = False, append_sources_to_chat: bool = True, show_accordions: bool = True, top_k_docs_max_show: int = 10, show_link_in_sources: bool = True, langchain_instruct_mode: bool = True, pre_prompt_query: str = None, prompt_query: str = None, pre_prompt_summary: str = None, prompt_summary: str = None, hyde_llm_prompt: 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 = docs_ordering_types_default, min_max_new_tokens=512, max_input_tokens=None, max_total_input_tokens=None, docs_token_handling: str = docs_token_handling_default, docs_joiner: str = docs_joiner_default, hyde_level: int = 0, hyde_template: str = None, hyde_show_only_final: bool = False, hyde_show_intermediate_in_accordion: bool = True, doc_json_mode: bool = False, metadata_in_context: Union[str, list] = 'auto', auto_reduce_chunks: bool = True, max_chunks: int = 100, headsize: int = 50, n_jobs: int = -1, n_gpus: int = None, clear_torch_cache_level: int = 1, # urls use_unstructured: bool = True, use_playwright: bool = False, use_selenium: bool = False, use_scrapeplaywright: bool = False, use_scrapehttp: bool = False, # pdfs use_pymupdf: Union[bool, str] = 'auto', use_unstructured_pdf: Union[bool, str] = 'auto', use_pypdf: Union[bool, str] = 'auto', enable_pdf_ocr: Union[bool, str] = 'auto', enable_pdf_doctr: Union[bool, str] = 'auto', try_pdf_as_html: Union[bool, str] = 'auto', # images enable_ocr: bool = False, enable_doctr: bool = True, enable_pix2struct: bool = False, enable_captions: bool = True, enable_llava: bool = True, enable_transcriptions: bool = True, pre_load_image_audio_models: bool = False, caption_gpu: bool = True, caption_gpu_id: Union[int, str] = 'auto', captions_model: str = "Salesforce/blip-image-captioning-base", doctr_gpu: bool = True, doctr_gpu_id: Union[int, str] = 'auto', llava_model: str = None, llava_prompt: str = 'auto', image_file: str = None, image_control: str = None, asr_model: str = "openai/whisper-medium", asr_gpu: bool = True, asr_gpu_id: Union[int, str] = 'auto', asr_use_better: bool = True, asr_use_faster: bool = False, enable_stt: Union[str, bool] = 'auto', stt_model: str = "openai/whisper-base.en", stt_gpu: bool = True, stt_gpu_id: Union[int, str] = 'auto', stt_continue_mode: int = 1, enable_tts: Union[str, bool] = 'auto', tts_gpu: bool = True, tts_gpu_id: Union[int, str] = 'auto', tts_model: str = 'microsoft/speecht5_tts', tts_gan_model: str = 'microsoft/speecht5_hifigan', tts_coquiai_deepspeed: bool = True, tts_coquiai_roles: dict = None, chatbot_role: str = "None", # "Female AI Assistant", speaker: str = "None", # "SLT (female)", tts_language: str = 'autodetect', tts_speed: float = 1.0, tts_action_phrases: typing.List[str] = [], # ['Nimbus'], tts_stop_phrases: typing.List[str] = [], # ['Yonder'], sst_floor: float = 100, enable_imagegen: bool = False, # experimental enable_imagegen_high: bool = False, # experimental enable_imagegen_high_sd: bool = False, # experimental enable_imagechange: bool = False, # experimental imagegen_gpu_id: Union[str, int] = 'auto', imagechange_gpu_id: Union[str, int] = 'auto', enable_llava_chat: bool = False, # json jq_schema='.[]', extract_frames: int = 10, 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 use_flash_attention_2: Whether to try to use flash attention 2 if available when loading HF models Warning: We have seen nans and type mismatches with flash-attn==2.3.4 installed and this enabled, even for other models like embedding model that is unrelated to primary models. :param load_gptq: to load model with GPTQ, put model_basename here, e.g. 'model' for TheBloke models :param use_autogptq: whether to use AutoGPTQ (True) or HF Transformers (False) Some models are only supported by one or the other :param load_awq: load model with AWQ, e.g. 'model' for TheBloke models :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. If model is private or doesn't exist as HF model, can use "tiktoken" and pass max_seq_len and (if different) max_output_seq_len For inference servers like OpenAI etc. if have model name, we use tiktoken with known input/output sequence lengths. :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=HuggingFaceH4/zephyr-7b-beta 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:<deployment_name>:<baseurl>:<api_version>:<access key>" --base_model=gpt-3.5-turbo e.g. python generate.py --inference_server="openai_azure:<deployment_name>:<baseurl>:<api_version>:<access key>" --base_model=text-davinci-003 Optionals (Replace with None or just leave empty but keep :) <deployment_name> of some deployment name <baseurl>: e.g. "<endpoint>.openai.azure.com" for some <endpoint> without https:// <api_version> of some api, e.g. 2023-05-15 Or Address can be for vLLM: Use: "vllm:IP:port" for OpenAI-compliant vLLM endpoint Use: "vllm_chat:IP:port" for OpenAI-Chat-compliant vLLM endpoint Use: "vllm:http://IP:port/v1" for OpenAI-compliant vLLM endpoint Use: "vllm_chat:http://IP:port/v1" for OpenAI-Chat-compliant vLLM endpoint Use: "vllm:https://IP/v1" for OpenAI-compliant vLLM endpoint Use: "vllm_chat:https://IP/v1" for OpenAI-Chat-compliant vLLM endpoint For example, for non-standard URL and API key for vllm, one would do: vllm_chat:https://vllm.h2o.ai:None:/1b1219f7-4bb4-43e9-881f-fa8fa9fe6e04/v1:1234ABCD where vllm.h2o.ai is the DNS name of the IP, None means no extra port, so will be dropped from base_url when using API, /1b1219f7-4bb4-43e9-881f-fa8fa9fe6e04/v1 is the url of the "page" to access, and 1234ABCD is the api key Or for example: vllm_chat:https://vllm.h2o.ai:5001:/1b1219f7-4bb4-43e9-881f-fa8fa9fe6e04/v1:1234ABCD where vllm.h2o.ai is the DNS name of the IP, 5001 is the port, /1b1219f7-4bb4-43e9-881f-fa8fa9fe6e04/v1 is the url of the "page" to access, and 1234ABCD is the api key Or for groq, can use OpenAI API like: vllm:https://api.groq.com/openai:None:/v1:<api key>' with: other model_lock or CLI options: {'base_model':'mixtral-8x7b-32768', 'visible_models':'mixtral-8x7b-32768', 'max_seq_len': 31744, 'prompt_type':'plain'} i.e.ensure to use 'plain' prompt, not mixtral. Or Address can be replicate: Use: --inference_server=replicate:<model name string> will use a Replicate server, requiring a Replicate key. e.g. <model name string> looks like "a16z-infra/llama13b-v2-chat:df7690f1994d94e96ad9d568eac121aecf50684a0b0963b25a41cc40061269e5" Or Address can be for AWS SageMaker: Use: "sagemaker_chat:<endpoint name>" for chat models that AWS sets up as dialog Use: "sagemaker:<endpoint name>" for foundation models that AWS only text as inputs Or Address can be for Anthropic Claude. Ensure key is set in env ANTHROPIC_API_KEY Use: "anthropic E.g. --base_model=claude-2.1 --inference_server=anthropic Or Address can be for Google Gemini. Ensure key is set in env GOOGLE_API_KEY Use: "google" E.g. --base_model=gemini-pro --inference_server=google Or Address can be for MistralAI. Ensure key is set in env MISTRAL_API_KEY Use: "mistralai" E.g. --base_model=mistral-medium --inference_server=mistralai :param regenerate_clients: Whether to regenerate client every LLM call or use start-up version Benefit of doing each LLM call is timeout can be controlled to max_time in expert settings, else we use default of 600s. Maybe risky, some lack of thread safety: https://github.com/encode/httpx/discussions/3043, so disabled Because gradio clients take long time to start-up, we don't ever regenerate them each time (including llava models) :param regenerate_gradio_clients: Whether to also regenerate gradio clients (slow) :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 allow_chat_system_prompt: Whether to use conversation_history to pre-append system prompt :param llamacpp_path: Location to store downloaded gguf or load list of models from Note HF models go into hf cache folder, and gpt4all models go into their own cache folder Can override with ENV LLAMACPP_PATH :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 exllama_dict for setting various things for Exllama class E.g. compress_pos_emb, set_auto_map, gpu_peer_fix, alpha_value, matmul_recons_thd, fused_mlp_thd sdp_thd fused_attn matmul_fused_remap rmsnorm_no_half2 rope_no_half2 matmul_no_half2 silu_no_half2 concurrent_streams E.g. to set memory to be split across 2 GPUs, use --exllama_dict="{'set_auto_map':20,20}" :param gptq_dict: Choices for AutoGPTQ, e.g. one can change defaults to these non-defaults: inject_fused_attention=False disable_exllama=True use_triton=True :param attention_sinks: Whether to enable attention sinks. :param sink_dict: dict of options for attention sinks E.g. {'window_length': 1024, 'num_sink_tokens': 4} Default is window length same size as max_input_tokens (max_seq_len if max_input_tokens not set) :param hf_model_dict: dict of options for HF models using transformers :param truncation_generation: Whether (for torch) to terminate generation once reach context length of model. For some models, perplexity becomes critically large beyond context For other models like Mistral, one can generate beyond max_seq_len set to 4096 or 8192 without issue, since based upon 32k embeddings codellama can also generate beyond its 16k context length So default is off, but for simpler/older models True may be wise to avoid bad generations :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 model_lock_layout_based_upon_initial_visible: Whether to base any layout upon visible models (True) or upon all possible models. gradio does not allow dynamic objects, so all layouts are preset, and these are two reasonable options. False is best when there are many models and user excludes middle ones as being visible. :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 penalty_alpha: penalty_alpha>0 and top_k>1 enables contrastive search (not all models support) :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. Enable for sampling for given temperature, top_p, top_k, else greedy decoding and then temperature, top_p, top_k not used. https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig.do_sample https://txt.cohere.com/llm-parameters-best-outputs-language-ai/ https://medium.com/@daniel.puenteviejo/the-science-of-control-how-temperature-top-p-and-top-k-shape-large-language-models-853cb0480dae :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 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. For long context models that have been tuned for a specific size, you have to only use that specific size by setting the `--rope_scaling` exactly correctly e.g. --rope_scaling="{'type':'dynamic', 'factor':4}" e.g. --rope_scaling="{'type':'linear', 'factor':4}" e.g. python generate.py --rope_scaling="{'type':'linear','factor':4}" --base_model=lmsys/vicuna-13b-v1.5-16k --hf_embedding_model=sentence-transformers/all-MiniLM-L6-v2 --load_8bit=True --langchain_mode=UserData --user_path=user_path --prompt_type=vicuna11 --h2ocolors=False 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 max_output_seq_len: Manually set maximum output 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 openai_server: whether to launch OpenAI proxy server for local gradio server Disabled if API is disabled or --auth=closed :param openai_port: port for OpenAI proxy server :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 share: whether to share the gradio app with sharable URL :param open_browser: whether to automatically open browser tab with gradio UI :param close_button: Whether to show close button in system tab (if not public) :param shutdown_via_api: Whether to allow shutdown via API :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 ssl_verify: passed go gradio launch :param ssl_keyfile: passed go gradio launch :param ssl_certfile: passed go gradio launch :param ssl_keyfile_password: passed go gradio launch :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 render_markdown: Whether to render markdown in chatbot UI. In some cases this distorts the rendering. https://github.com/gradio-app/gradio/issues/4344#issuecomment-1771963021 :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 local LLMs to avoid sharing cache that messes up models, else 64 is used if hosting remote inference servers only) :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 gradio_ui_stream_chunk_size: Number of characters to wait before pushing text to ui. None is default, which is 0 when not doing model lock. Else 20 by default. 20 is reasonable value for fast models and fast systems when handling several models at once Choose 0 to disable (this disables use of gradio_ui_stream_chunk_min_seconds and gradio_ui_stream_chunk_seconds too) Work around for these bugs that lead to UI being overwhelmed under various cases https://github.com/gradio-app/gradio/issues/5914 https://github.com/gradio-app/gradio/issues/6609 :param gradio_ui_stream_chunk_min_seconds: Number of seconds before allow yield to avoid spamming yields at rate user would not care about, regardless of chunk_size :param gradio_ui_stream_chunk_seconds: Number of seconds to yield regardless of reaching gradio_ui_stream_chunk_size as long as something to yield Helps case when streaming is slow and want to see progress at least every couple seconds :param gradio_api_use_same_stream_limits: Whether to use same streaming limits as UI for API :param gradio_upload_to_chatbot: Whether to show upload in chatbots :param gradio_upload_to_chatbot_num_max: Max number of things to add to chatbot :param gradio_errors_to_chatbot: Whether to show errors in Accordion in chatbot or just in exceptions in each tab :param pre_load_embedding_model: Whether to preload embedding model for shared use across DBs and users (multi-thread safe only) :param embedding_gpu_id: which GPU to place embedding model on. Only used if preloading embedding model. If 'auto', then use first device as is default If 'cpu' or some other string like 'mps', then use that as device name. :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 good idea to control location) 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 enforce_h2ogpt_ui_key: Whether to enforce h2oGPT token usage for UI (same keys as API assumed) :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 Only applied for API at runtime when API accesses using gradio inference_server are made :param extra_allowed_paths: List of strings for extra allowed paths users could access for file viewing/downloading. '.' can be used but be careful what that exposes. Note by default all paths in langchain_mode_paths given at startup are allowed :param blocked_paths: Any blocked paths to add for gradio access for file viewing/downloading. :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 max_input_tokens: Max input tokens to place into model context for each LLM call -1 means auto, fully fill context for query, and fill by original document chunk for summarization >=0 means use that to limit context filling to that many tokens :param max_total_input_tokens: like max_input_tokens but instead of per LLM call, applies across all LLM calls for single summarization/extraction action :param docs_token_handling: 'chunk' means fill context with top_k_docs (limited by max_input_tokens or model_max_len) chunks for query or top_k_docs original document chunks summarization None or 'split_or_merge' means same as 'chunk' for query, while for summarization merges documents to fill up to max_input_tokens or model_max_len tokens :param docs_joiner: string to join lists of text when doing split_or_merge. None means '\n\n' :param hyde_level: HYDE level for HYDE approach (https://arxiv.org/abs/2212.10496) 0: No HYDE 1: Use non-document-based LLM response and original query for embedding query 2: Use document-based LLM response and original query for embedding query 3+: Continue iterations of embedding prior answer and getting new response :param hyde_template: None, 'None', 'auto' uses internal value and enable '{query}' is minimal template one can pass :param hyde_show_only_final: Whether to show only last result of HYDE, not intermediate steps :param hyde_show_intermediate_in_accordion: Whether to show intermediate HYDE, but inside HTML accordion :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. Note that unlike h2ogpt_key, this visible_models only applies to this running h2oGPT server, and the value is not used to access the inference server. If need a visible_models for an inference server, then use --model_lock and group together. :param max_visible_models: maximum visible models to allow to select in UI :param visible_ask_anything_high: Whether ask anything block goes near top or near bottom of UI Chat :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 (needed for persistence or to enter key for UI access to models and ingestion) :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_links: Whether github stars, URL are visible :param visible_h2ogpt_qrcode: Whether QR code is visible :param visible_h2ogpt_logo: Whether central logo is visible :param visible_chatbot_label: Whether to show label in chatbot (e.g. if only one model for own purpose, then can set to False) :param visible_all_prompter_models: Whether to show all prompt_type_to_model_name items or just curated ones :param visible_curated_models: Whether to show curated models (useful to see few good options) :param actions_in_sidebar: Whether to show sidebar with actions in old style :param document_choice_in_sidebar: Whether to show document choices in sidebar Useful if often changing picking specific document(s) :param enable_add_models_to_list_ui: Whether to show add model, lora, server to dropdown list Disabled by default since clutters Models tab in UI, and can just add custom item directly in dropdown :param max_raw_chunks: Maximum number of chunks to show in UI when asking for raw DB text from documents/collection :param pdf_height: Height of PDF viewer in UI :param avatars: Whether to show avatars in chatbot :param add_disk_models_to_ui: Whether to add HF cache models and llama.cpp models to UI :param page_title: Title of the web page, default is h2oGPT :param favicon_path: Path to favicon, default is h2oGPT favicon :param visible_ratings: Whether full review is visible, else just likable chatbots :param reviews_file: File to store reviews, set to `reviews.csv` if visible_ratings=True if this isn't set :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 verifier_model: model for verifier :param verifier_tokenizer_base_model: tokenizer server for verifier (if empty/None, infer from model) :param verifier_inference_server: inference server for verifier :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 Extract: Extract information from document(s) via map (no reduce) Currently enabled is Query, Summarize, and Extract. Summarize is a "map reduce" and extraction is "map". That is, map returns a text output (roughly) per input item, while reduce reduces all maps down to single text output. The "roughly" refers to fact that if one has docs_token_handling='split_or_merge' then we split or merge chunks, so you will get a map for some optimal-sized chunks given the model size. If you choose docs_token_handling='chunk', then you get back a map for each chunk you give, but you should ensure the model token limit is not exceeded yourself. Summarize is useful when wanting to reduce down to single text, while Extract is useful when want to operate the prompt on blocks of data and get back a result per block. :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 document_source_substrings: substrings in list to search in source names in metadata for chroma dbs :param document_source_substrings_op: 'and or 'or' for source search words :param document_content_substrings: substrings in list to search in content for chroma dbs :param document_content_substrings_op: 'and or 'or' for content search words :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 append_sources_to_chat: Whether to place sources information in chat response but in separate chat turn (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 langchain_instruct_mode: Whether to have langchain operate in instruct mode (True) or few-shot mode (False) Normally this might be decidable from --prompt_type=plain, but in some cases (like vllm_chat) we want inference server to handle all prompting, so need to tell h2oGPT to use plain prompting, but don't want to change langchain behavior :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/extract from, if None then use internal defaults :param prompt_summary: prompt after documents to summarize/extract from, if None then use internal defaults For summarize/extract, 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) For query, prompt template is: "{pre_prompt_query} \"\"\" {fstring} \"\"\" {prompt_query}{instruction}" For summarization or extraction, for some internal document part fstring, the template looks like: "{pre_prompt_summary} \"\"\" {fstring} \"\"\" {prompt_summary}" If added instruction for summarization or extraction, prompt template is "{pre_prompt_summary} \"\"\" {fstring} \"\"\" Focusing on {instruction}, {prompt_summary}" {fstring} is some document chunks separated by {docs_joiner} :param hyde_llm_prompt: hyde prompt for first step when using LLM :param doc_json_mode: Use system prompting approach with JSON input and output, e.g. for codellama or GPT-4 :param metadata_in_context: Keys of metadata to include in LLM context for Query 'all': Include all metadata 'auto': Includes these keys: ['date', 'file_path', 'input_type', 'keywords', 'chunk_id', 'page', 'source', 'title', 'total_pages'] ['key1', 'key2', ...]: Include only these keys NOTE: not all parsers have all keys, only keys that exist are added to each document chunk. Example key-values that some PDF parsers make: author = Zane Durante, Bidipta Sarkar, Ran Gong, Rohan Taori, Yusuke Noda, Paul Tang, Ehsan Adeli, Shrinidhi Kowshika Lakshmikanth, Kevin Schulman, Arnold Milstein, Demetri Terzopoulos, Ade Famoti, Noboru Kuno, Ashley Llorens, Hoi Vo, Katsu Ikeuchi, Li Fei-Fei, Jianfeng Gao, Naoki Wake, Qiuyuan Huang chunk_id = 21 creationDate = D:20240209020045Z creator = LaTeX with hyperref date = 2024-02-11 23:58:11.929155 doc_hash = 5db1d548-7 file_path = /tmp/gradio/15ac25af8610f21b9ab55252f1944841727ba157/2402.05929.pdf format = PDF 1.5 hashid = 3cfb31cea127c745c72554f4714105dd head = An Interactive Agent Foundation Model Figure 2. We input_type = .pdf keywords = Machine Learning, ICML modDate = D:20240209020045Z order_id = 2 page = 2 parser = PyMuPDFLoader producer = pdfTeX-1.40.25 source = /tmp/gradio/15ac25af8610f21b9ab55252f1944841727ba157/2402.05929.pdf subject = Proceedings of the International Conference on Machine Learning 2024 time = 1707724691.929157 title = An Interactive Agent Foundation Model total_pages = 22 :param add_chat_history_to_context: Include chat context when performing action 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/extract: 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 n_gpus: Number of GPUs (None = autodetect) :param clear_torch_cache_level: 0: never clear except where critically required 1: clear critical 2: clear aggressively and clear periodically every 20s to free-up GPU memory (may lead to lag in response) :param use_unstructured: Enable unstructured URL loader :param use_playwright: Enable PlayWright URL loader :param use_selenium: Enable Selenium URL loader :param use_scrapeplaywright: Enable Scrape PlayWright URL loader :param use_scrapehttp: Enable Scrape HTTP URL loader using aiohttp :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_image_audio_models=True :param enable_llava: If LLaVa IP port is set, whether to use response for image ingestion :param enable_transcriptions: Whether to enable audio transcriptions (youtube of from files) Preloaded if pre_load_image_audio_models=True :param pre_load_image_audio_models: Whether to preload caption model (True), or load after forking parallel doc loader (False) parallel loading disabled if preload and have images, to prevent deadlocking on cuda context Recommended if using larger caption model or doing production serving with many users to avoid GPU OOM if many would use model at same time Also applies to DocTR and ASR models :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 caption_gpu_id: Which GPU id to use, if 'auto' then select 0 :param doctr_gpu: If support doctr, then use GPU if exists :param doctr_gpu_id: Which GPU id to use, if 'auto' then select 0 :param llava_model: IP:port for h2oai version of LLaVa gradio server for hosted image chat E.g. http://192.168.1.46:7861 None means no such LLaVa support :param llava_prompt: Prompt passed to LLaVa for querying the image :param image_file: Initial image for UI (or actual image for CLI) Vision Q/A :param image_control: Initial image for UI Image Control :param asr_model: Name of model for ASR, e.g. openai/whisper-medium or openai/whisper-large-v3 or distil-whisper/distil-large-v2 or microsoft/speecht5_asr whisper-medium uses about 5GB during processing, while whisper-large-v3 needs about 10GB during processing :param asr_gpu: Whether to use GPU for ASR model :param asr_gpu_id: Which GPU to put ASR model on (only used if preloading model) :param asr_use_better: Whether to use BetterTransformer :param asr_use_faster: Whether to use faster_whisper package and models (loads normal whisper then unloads it, to get this into pipeline) :param enable_stt: Whether to enable and show Speech-to-Text (STT) with microphone in UI Note STT model is always preloaded, but if stt_model=asr_model and pre_load_image_audio_models=True, then asr model is used as STT model. :param stt_model: Name of model for STT, can be same as asr_model, which will then use same model for conserving GPU :param stt_gpu: Whether to use gpu for STT model :param stt_gpu_id: If not using asr_model, then which GPU to go on if using cuda :param stt_continue_mode: How to continue speech with button control 0: Always append audio regardless of start/stop of recording, so always appends in STT model for full STT conversion Only can edit after hit stop and then submit, if hit record again edits are lost since using only audio stream for STT conversion 1: If hit stop, text made so far is saved and audio cleared, so next recording will be separate text conversion Can make edits on any text after hitting stop and they are preserved :param enable_tts: Whether to enable TTS :param tts_gpu: Whether to use GPU if present for TTS :param tts_gpu_id: Which GPU ID to use for TTS :param tts_model: Which model to use. For microsoft, use 'microsoft/speecht5_tts' For coqui.ai use one given by doing in python: ```python from src.tts_coqui import list_models list_models() ``` e.g. 'tts_models/multilingual/multi-dataset/xtts_v2' Note that coqui.ai models are better, but some have non-commercial research license, while microsoft models are MIT. So coqui.ai ones can be used for non-commercial activities only, and one should agree to their license, see: https://coqui.ai/cpml Commercial use of xtts_v2 should be obtained through their product offering at https://coqui.ai/ :param tts_gan_model: For microsoft model, which gan model to use, e.g. 'microsoft/speecht5_hifigan' :param tts_coquiai_deepspeed: For coqui.ai models, whether to use deepspeed for faster inference :param tts_coquiai_roles: role dictionary mapping name (key) to wave file (value) If None, then just use default from get_role_to_wave_map() :param chatbot_role: Default role for coqui models. If 'None', then don't by default speak when launching h2oGPT for coqui model choice. :param speaker: Default speaker for microsoft models If 'None', then don't by default speak when launching h2oGPT for microsoft model choice. :param tts_language: Default language for coqui models :param tts_speed: Default speed of TTS, < 1.0 (needs rubberband) for slower than normal, > 1.0 for faster. Tries to keep fixed pitch. :param tts_action_phrases: Phrases or words to use as action word to trigger click of Submit hands-free assistant style Set to None or empty list to avoid any special action words :param tts_stop_phrases: Like tts_action_phrases but to stop h2oGPT from speaking and generating NOTE: Action/Stop phrases should be rare but easy (phonetic) words for Whisper to recognize. E.g. asking GPT-4 a couple good ones are ['Nimbus'] and ['Yonder'], and one can help Whisper by saying "Nimbus Clouds" which still works as "stop word" as trigger. :param sst_floor: Floor in wave square amplitude below which ignores the chunk of audio This helps avoid long silence messing up the transcription. :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 extract_frames: How many unique frames to extract from video (if 0, then just do audio if audio type file as well) :param enable_imagegen: Whether to enable image generation model :param enable_imagegen_high: Whether to enable image generation model with high resolution :param enable_imagegen_high_sd: Whether to use Stable Diffusion for high res model :param enable_imagechange: Whether to enable image change model :param imagegen_gpu_id: GPU id to use for imagegen model :param imagechange_gpu_id: GPU id to use for imagechange model :param enable_llava_chat: Whether to use LLaVa model to chat directly against instead of just for ingestion :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) tts_coquiai_roles = str_to_dict(tts_coquiai_roles) roles_state0 = tts_coquiai_roles tts_action_phrases = str_to_list(tts_action_phrases) tts_stop_phrases = str_to_list(tts_stop_phrases) # defaults, but not keep around if not used so can use model_path_llama for prompt_type auto-setting # NOTE: avoid defaults for model_lock, require to be specified if base_model == 'llama': if not model_path_llama: model_path_llama = 'https://huggingface.co/TheBloke/Llama-2-7b-Chat-GGUF/resolve/main/llama-2-7b-chat.Q6_K.gguf?download=true' if not prompt_type: prompt_type = 'llama2' elif base_model == 'gptj' and not model_name_gptj: model_name_gptj = 'ggml-gpt4all-j-v1.3-groovy.bin' elif base_model == 'gpt4all_llama' and not model_name_gpt4all_llama: model_name_gpt4all_llama = 'ggml-wizardLM-7B.q4_2.bin' if load_exllama and not model_name_exllama_if_no_config: model_name_exllama_if_no_config = 'TheBloke/Nous-Hermes-Llama2-GPTQ' # switch-a-roo on base_model so can pass GGUF/GGML as base model base_model0 = base_model # for prompt infer base_model, model_path_llama, load_gptq, load_awq, llamacpp_dict['n_gqa'] = \ switch_a_roo_llama(base_model, model_path_llama, load_gptq, load_awq, llamacpp_dict.get('n_gqa', 0), llamacpp_path) # 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 # ensure not used by accident del model_path_llama del model_name_gptj del model_name_gpt4all_llama del 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 exllama_dict = str_to_dict(exllama_dict) gptq_dict = str_to_dict(gptq_dict) sink_dict = str_to_dict(sink_dict) hf_model_dict = str_to_dict(hf_model_dict) 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 (not have_diffusers or not enable_imagegen) and \ LangChainAction.IMAGE_GENERATE.value in visible_langchain_actions: visible_langchain_actions.remove(LangChainAction.IMAGE_GENERATE.value) if (not have_diffusers or not enable_imagegen_high) and \ LangChainAction.IMAGE_GENERATE_HIGH.value in visible_langchain_actions: visible_langchain_actions.remove(LangChainAction.IMAGE_GENERATE_HIGH.value) if (not have_diffusers or not enable_imagechange) and \ LangChainAction.IMAGE_CHANGE.value in visible_langchain_actions: visible_langchain_actions.remove(LangChainAction.IMAGE_CHANGE.value) if (not llava_model or not enable_llava or not enable_llava_chat) and \ LangChainAction.IMAGE_QUERY.value in visible_langchain_actions: visible_langchain_actions.remove(LangChainAction.IMAGE_QUERY.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" if gradio_ui_stream_chunk_size is None: gradio_ui_stream_chunk_size = 20 else: # for faster default feel of speed if gradio_ui_stream_chunk_size is None: gradio_ui_stream_chunk_size = 0 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 enforce_h2ogpt_ui_key is None: # nominally allow UI access public or not enforce_h2ogpt_ui_key = False if is_public: if max_visible_models is None and gradio: is_gradio_h2oai = get_is_gradio_h2oai() max_visible_models = 4 if is_gradio_h2oai else None 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 isinstance(extra_allowed_paths, str): extra_allowed_paths = str_to_list(extra_allowed_paths) 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))) if is_public: gradio_upload_to_chatbot_num_max = 1 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) if auth_access == 'closed': # ensure, but should be protected inside anyways guest_name = '' h2ogpt_pid = os.getpid() if close_button and not is_public else None # 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 llamacpp_path: llamacpp_path = makedirs(llamacpp_path, use_base=True) 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=<chosen 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: # See also get_minmax_top_k_docs() # as another restriction apart from top_k_docs and when using long context models # model will limit more if required max_input_tokens = max_input_tokens_public if max_input_tokens is None else max_input_tokens max_total_input_tokens = max_total_input_tokens_public if max_total_input_tokens is None else max_total_input_tokens 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 penalty_alpha = 0.0 if penalty_alpha is None else penalty_alpha 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 # now 10 since also limiting total tokens, in case some pages (for summarization) are small top_k_docs = max_top_k_docs_public 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 = max_top_k_docs_public 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 = max_top_k_docs_default if max_input_tokens is None: max_input_tokens = -1 if max_total_input_tokens is None: max_total_input_tokens = -1 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 = '' # prioritize verifier model to replace output if verifier_model: score_model = '' all_inference_server = inference_server or model_lock and all(x.get('inference_server') for x in model_lock) if inference_server == 'openai' and base_model in openai_gpts: # deprecate chat models with non-chat API inference_server = 'openai_chat' if os.getenv('CONCURRENCY_COUNT'): concurrency_count = int(os.getenv('CONCURRENCY_COUNT')) elif concurrency_count: pass else: if all_inference_server: concurrency_count = 64 else: # can't share LLM state across user requests due to k-v cache for LLMs # FIXME: In gradio 4 could use 1 for only LLM tasks, higher for rest concurrency_count = 1 if concurrency_count > 1 and not all_inference_server: # FIXME: Could use semaphore to manage each LLM concurrency, in case mix of local and remote raise ValueError( "Concurrency count > 1 will lead mixup in cache use for local LLMs, disable this raise at own risk.") api_open = bool(int(os.getenv('API_OPEN', str(int(api_open))))) allow_api = bool(int(os.getenv('ALLOW_API', str(int(allow_api))))) if openai_server and not allow_api: print("Cannot enable OpenAI server when allow_api=False or auth is closed") openai_server = False if not os.getenv('CLEAR_CLEAR_TORCH'): if clear_torch_cache_level == 0: os.environ['CLEAR_CLEAR_TORCH'] = '0' elif clear_torch_cache_level == 1: os.environ['CLEAR_CLEAR_TORCH'] = '1' n_gpus1 = torch.cuda.device_count() if torch.cuda.is_available() else 0 n_gpus1, gpu_ids = cuda_vis_check(n_gpus1) if n_gpus is None: n_gpus = n_gpus1 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(n_gpus=n_gpus) == "mps": # No CUDA GPUs usable if get_device(n_gpus=n_gpus) != "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 use_flash_attention_2 = False load_gptq = '' load_awq = '' load_exllama = False use_gpu_id = False if get_device(n_gpus=n_gpus) == "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 not have_flash_attention_2: use_flash_attention_2 = False 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() model_lower0 = base_model0.lower() elif model_lock: assert len(model_lock) > 0 and model_lock[0]['base_model'], "model_lock: %s" % model_lock # set to '' so don't contaminate other models in lock with first one model_lower = '' model_lower0 = '' else: model_lower = '' model_lower0 = '' 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 offload_folder: offload_folder = makedirs(offload_folder, exist_ok=True, tmp_ok=True, use_base=True) # auto-set stt and tts. # Done early here for lg_to_gr() and preload of db to know what's enabled if cli or not gradio: enable_stt = enable_tts = False if not (have_soundfile and have_librosa and have_wavio): if enable_stt == 'auto': print("soundfile, librosa, and wavio not installed, disabling STT", flush=True) enable_stt = False elif enable_stt is True: raise RuntimeError("STT packages (soundfile, librosa, wavio) not installed") elif enable_stt == 'auto': enable_stt = False if n_gpus != 0 and enable_stt: print("STT enabled, may use more GPU, set --enable_stt=False for low-memory systems", flush=True) if not (have_soundfile and have_librosa and have_wavio): if enable_tts == 'auto': print("soundfile, librosa, and wavio not installed, disabling TTS", flush=True) enable_tts = False elif enable_tts is True: raise RuntimeError("TTS packages (soundfile, librosa, wavio) not installed") elif enable_tts == 'auto': enable_tts = False if not have_langchain and enable_transcriptions: print("Must install langchain for transcription, disabling", flush=True) enable_transcriptions = False if not (have_soundfile and have_librosa and have_wavio) and enable_tts: enable_tts = False print("soundfile, librosa, and wavio not installed, disabling TTS", flush=True) if n_gpus != 0 and enable_tts: print("TTS enabled, may use more GPU, set --enable_tts=False for low-memory systems", flush=True) if n_gpus == 0: tts_gpu = False stt_gpu = False caption_gpu = False asr_gpu = False if is_public: stt_model = 'distil-whisper/distil-large-v2' # defaults caption_loader = None doctr_loader = None pix2struct_loader = None asr_loader = None image_audio_loaders_options0, image_audio_loaders_options, \ pdf_loaders_options0, pdf_loaders_options, \ url_loaders_options0, url_loaders_options = lg_to_gr(**locals()) jq_schema0 = jq_schema extract_frames0 = extract_frames # transcribe image_audio_loaders = image_audio_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, penalty_alpha, 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, model_lower0, llamacpp_dict, chat, stream_output, show_examples, prompt_type, prompt_dict, system_prompt, pre_prompt_query, prompt_query, pre_prompt_summary, prompt_summary, hyde_llm_prompt, temperature, top_p, top_k, penalty_alpha, 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_audio_loaders, pdf_loaders, url_loaders, jq_schema, extract_frames, llava_prompt, docs_ordering_type, min_max_new_tokens, max_input_tokens, max_total_input_tokens, docs_token_handling, docs_joiner, hyde_level, hyde_template, hyde_show_only_final, doc_json_mode, metadata_in_context, chatbot_role, speaker, tts_language, tts_speed, image_file, image_control, verbose, ) git_hash = 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) # PRELOAD if enable_captions: if pre_load_image_audio_models: from image_captions import H2OImageCaptionLoader caption_loader = H2OImageCaptionLoader(caption_gpu=caption_gpu, gpu_id=caption_gpu_id).load_model() else: caption_loader = 'gpu' if n_gpus > 0 and caption_gpu else 'cpu' else: caption_loader = False if not have_langchain and pre_load_embedding_model: print("Must install langchain for preloading embedding model, disabling", flush=True) pre_load_embedding_model = False if use_openai_embedding: # makes later code simpler hf_embedding_model = '' 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, gpu_id=embedding_gpu_id)) if not (have_doctr and have_langchain) and enable_doctr: print("Must install DocTR and LangChain installed if enabled DocTR, disabling", flush=True) enable_doctr = False enable_pdf_ocr = 'off' if enable_doctr or enable_pdf_ocr in [True, 'auto', 'on']: if pre_load_image_audio_models: from image_doctr import H2OOCRLoader doctr_loader = H2OOCRLoader(layout_aware=True, gpu_id=doctr_gpu_id).load_model() else: doctr_loader = 'gpu' if n_gpus > 0 and caption_gpu else 'cpu' else: doctr_loader = False if enable_transcriptions: if pre_load_image_audio_models: from src.audio_langchain import H2OAudioCaptionLoader asr_loader = H2OAudioCaptionLoader(asr_gpu=asr_gpu, gpu_id=asr_gpu_id, asr_model=asr_model, use_better=asr_use_better, use_faster=asr_use_faster).load_model() else: asr_loader = 'gpu' if n_gpus > 0 and asr_gpu else 'cpu' else: asr_loader = False if enable_stt: from src.stt import transcribe if pre_load_image_audio_models and \ stt_model == asr_model: transcriber = asr_loader.model.pipe else: from src.stt import get_transcriber transcriber = get_transcriber(model=stt_model, use_gpu=stt_gpu, gpu_id=stt_gpu_id) transcriber_func = functools.partial(transcribe, transcriber=transcriber, debug=debug, max_chunks=30 if is_public else None, sst_floor=sst_floor, ) model_xtt, supported_languages_xtt = None, None predict_from_text_func = None generate_speech_func = None return_as_byte = True # outside conditional since used without other checks if enable_tts: # NOTE: required bytes for now for audio streaming to work, else untested combine_audios() if tts_model.startswith('microsoft'): from src.tts import predict_from_text, get_tts_model, generate_speech processor_tts, model_tts, vocoder_tts = \ get_tts_model(t5_model=tts_model, t5_gan_model=tts_gan_model, use_gpu=tts_gpu, gpu_id=tts_gpu_id, ) predict_from_text_func = functools.partial(predict_from_text, processor=processor_tts, model=model_tts, return_as_byte=return_as_byte, vocoder=vocoder_tts) generate_speech_func = functools.partial(generate_speech, processor=processor_tts, model=model_tts, vocoder=vocoder_tts, return_as_byte=return_as_byte, verbose=verbose) elif tts_model.startswith('tts_models/'): if not have_TTS: raise ImportError("Selected non-default Coqui models, but did not install TTS") if not have_deepspeed and tts_coquiai_deepspeed: tts_coquiai_deepspeed = False print("deepspeed not installed, disabling", flush=True) from src.tts_coqui import get_xtt, predict_from_text, generate_speech model_xtt, supported_languages_xtt = get_xtt(model_name=tts_model, deepspeed=tts_coquiai_deepspeed, use_gpu=tts_gpu, gpu_id=tts_gpu_id, ) predict_from_text_func = functools.partial(predict_from_text, model=model_xtt, supported_languages=supported_languages_xtt, return_as_byte=return_as_byte, verbose=verbose, ) generate_speech_func = functools.partial(generate_speech, model=model_xtt, supported_languages=supported_languages_xtt, return_as_byte=return_as_byte, verbose=verbose) if enable_imagegen: # always preloaded from src.vision.sdxl import get_pipe_make_image image_gen_loader = get_pipe_make_image(gpu_id=imagegen_gpu_id) else: image_gen_loader = None if enable_imagegen_high: # always preloaded if enable_imagegen_high_sd: from src.vision.stable_diffusion_xl import get_pipe_make_image else: from src.vision.playv2 import get_pipe_make_image image_gen_loader_high = get_pipe_make_image(gpu_id=imagegen_gpu_id) else: image_gen_loader_high = None if enable_imagechange: from src.vision.sdxl import get_pipe_change_image image_change_loader = get_pipe_change_image(gpu_id=imagegen_gpu_id) else: image_change_loader = None # DB SETUP 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: if langchain_mode1 in langchain_modes_intrinsic: # don't store intrinsic dbs in dbs if db, and don't worry about LLM/Disabled continue 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, embedding_gpu_id=embedding_gpu_id, kwargs_make_db=locals(), verbose=verbose) finally: # in case updated embeddings or created new embeddings clear_torch_cache(allow_skip=True) 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" # MODEL SETUP if attention_sinks: if use_cache is False: raise ValueError("attention sinks requires use_cache=True") else: use_cache = True # never truncate if using attention sinks truncation_generation = truncation_generation and not attention_sinks other_model_state_defaults = dict(load_8bit=load_8bit, load_4bit=load_4bit, low_bit_mode=low_bit_mode, load_half=load_half, use_flash_attention_2=use_flash_attention_2, load_gptq=load_gptq, load_awq=load_awq, 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, rope_scaling=rope_scaling, max_seq_len=max_seq_len, max_output_seq_len=max_output_seq_len, exllama_dict=exllama_dict, gptq_dict=gptq_dict, attention_sinks=attention_sinks, sink_dict=sink_dict, truncation_generation=truncation_generation, hf_model_dict=hf_model_dict, ) model_state_none = dict(model=None, tokenizer=None, device=None, base_model=None, base_mode0=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, hyde_llm_prompt = \ get_langchain_prompts(pre_prompt_query, prompt_query, pre_prompt_summary, prompt_summary, hyde_llm_prompt, model_name, inference_server, llamacpp_dict['model_path_llama'], doc_json_mode) # get score model score_model_state0 = dict(model=None, tokenizer=None, device=None, base_model=None, tokenizer_base_model='', lora_weights='', inference_server='', prompt_type='', prompt_dict='', visible_models=None, h2ogpt_key=None, reward_model=None) if 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.update(dict(model=smodel, tokenizer=stokenizer, device=sdevice, base_model=score_model, reward_model=True)) # get verifier model, replaces score_model if exists if verifier_model: score_model = verifier_model all_kwargs = locals().copy() all_kwargs.update(base_model=verifier_model, tokenizer_base_model=verifier_tokenizer_base_model, inference_server=verifier_inference_server, prompt_type='plain', prompt_dict={}, visible_models=None, h2ogpt_key=None) smodel, stokenizer, sdevice = get_model_retry(reward_type=False, **get_kwargs(get_model, exclude_names=['reward_type'], **all_kwargs)) score_model_state0.update(dict(model=smodel, tokenizer=stokenizer, device=sdevice, base_model=verifier_model, tokenizer_base_model=verifier_tokenizer_base_model, inference_server=verifier_inference_server, prompt_type='plain', reward_model=False)) # get default model(s) model_states = [] model_list = [dict(base_model=base_model, base_model0=base_model0, 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] # make so don't have to pass dict in dict so more like CLI for these options inner_dict_keys = ['model_path_llama', 'model_name_gptj', 'model_name_gpt4all_llama', 'model_name_exllama_if_no_config'] for key in inner_dict_keys: if key in model_dict: model_dict['llamacpp_dict'][key] = model_dict.pop(key) model_dict['llamacpp_dict'] = model_dict.get('llamacpp_dict', {}) model_dict['base_model0'] = model_dict['base_model'] model_dict['base_model'], model_dict['llamacpp_dict']['model_path_llama'], \ model_dict['load_gptq'], \ model_dict['load_awq'], \ model_dict['llamacpp_dict']['n_gqa'] = \ switch_a_roo_llama(model_dict['base_model'], model_dict['llamacpp_dict']['model_path_llama'], model_dict['load_gptq'], model_dict['load_awq'], model_dict['llamacpp_dict'].get('n_gqa', 0), llamacpp_path) # 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, hyde_llm_prompt1 = ( get_langchain_prompts(pre_prompt_query, prompt_query, pre_prompt_summary, prompt_summary, hyde_llm_prompt, model_dict['base_model'], model_dict['inference_server'], model_dict['llamacpp_dict']['model_path_llama'], doc_json_mode)) # 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 hyde_llm_prompt = hyde_llm_prompt or hyde_llm_prompt1 # try to infer, ignore empty initial state leading to get_generate_params -> 'plain' if prompt_type_infer: prompt_type1_trial = model_name_to_prompt_type(model_dict['base_model'], model_name0=model_dict['base_model0'], llamacpp_dict=model_dict['llamacpp_dict']) if prompt_type1_trial: model_dict['prompt_type'] = prompt_type1_trial get_prompt_kwargs = dict(context='', reduced=False, making_context=False, return_dict=True, system_prompt=system_prompt) model_dict['prompt_dict'], error0 = get_prompt(model_dict['prompt_type'], '', **get_prompt_kwargs) 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_retry(reward_type=False, **get_kwargs(get_model, exclude_names=['reward_type'], **all_kwargs)) # update model state if hasattr(tokenizer0, 'model_max_length'): model_dict['max_seq_len'] = tokenizer0.model_max_length 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_possible_visible_models = [ x.get('base_model', xi) if x.get('base_model', '') != 'llama' or not x.get('llamacpp_dict').get('model_path_llama', '') else x.get('llamacpp_dict').get('model_path_llama', '') for xi, x in enumerate(model_states)] visible_models_state0 = [x for xi, x in enumerate(all_possible_visible_models) if visible_models is None or x 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 elif model_state0 is not None and \ 'tokenizer' in model_state0 and \ hasattr(model_state0['tokenizer'], 'model_max_length'): max_seq_len = model_state0['tokenizer'].model_max_length # run if cli: from cli import run_cli return run_cli(**get_kwargs(run_cli, **locals())) elif not gradio: from eval import run_eval return run_eval(**get_kwargs(run_eval, **locals())) elif gradio or prepare_offline_level > 0: # imported here so don't require gradio to run generate from gradio_runner import go_gradio # assume gradio needs everything go_gradio(**locals()) def H2O_Fire(component=None): config_prefix = "H2OGPT_" args = sys.argv[1:] query_args = [arg.split("=")[0].split(" ")[0].lstrip("-") for arg in args] fn_spec = inspectutils.GetFullArgSpec(component) for key, value in os.environ.items(): if not ( (key.startswith(config_prefix) or key.startswith(config_prefix.lower())) and len(key) > len(config_prefix) ): continue # ignore as non H2OGPT argument new_key = key[len(config_prefix):].lower() if new_key in query_args: continue # ignore as already passed as script argument if new_key not in fn_spec.args: continue # ignore as not a valid H2OGPT argument args.append(f"--{new_key}={value}") fire.Fire(component=component, command=args) def entrypoint_main(): H2O_Fire(main)
null
167,182
import abc import ast import collections from typing import ( Any, AsyncGenerator, Dict, Generator, List, Optional, OrderedDict, Union, ) from h2ogpt_client._gradio_client import GradioClientWrapper from h2ogpt_client._h2ogpt_enums import ( DocumentSubset, LangChainAction, LangChainMode, PromptType, ) from h2ogpt_client._models import Model _H2OGPT_PARAMETERS_TO_CLIENT = collections.OrderedDict( instruction="instruction", iinput="input", context="system_pre_context", stream_output="stream_output", prompt_type="prompt_type", prompt_dict="prompt_dict", temperature="temperature", top_p="top_p", top_k="top_k", penalty_alpha="penalty_alpha", num_beams="beams", max_new_tokens="max_output_length", min_new_tokens="min_output_length", early_stopping="early_stopping", max_time="max_time", repetition_penalty="repetition_penalty", num_return_sequences="number_returns", do_sample="enable_sampler", chat="chat", instruction_nochat="instruction_nochat", iinput_nochat="input_context_for_instruction", 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="langchain_top_k_docs", chunk="langchain_enable_chunk", chunk_size="langchain_chunk_size", document_subset="langchain_document_subset", document_choice="langchain_document_choice", document_source_substrings="langchain_document_source_substrings", document_source_substrings_op="langchain_document_source_substrings_op", document_content_substrings="langchain_document_content_substrings", document_content_substrings_op="langchain_document_content_substrings_op", pre_prompt_query="pre_prompt_query", prompt_query="prompt_query", pre_prompt_summary="pre_prompt_summary", prompt_summary="prompt_summary", hyde_llm_prompt="hyde_llm_prompt", system_prompt="system_prompt", image_audio_loaders="image_audio_loaders", pdf_loaders="pdf_loaders", url_loaders="url_loaders", jq_schema="jq_schema", visible_models="model", 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="docs_ordering_type", min_max_new_tokens="min_max_new_tokens", max_input_tokens="max_input_tokens", max_total_input_tokens="max_total_input_tokens", docs_token_handling="docs_token_handling", docs_joiner="docs_joiner", hyde_level="hyde_level", hyde_template="hyde_template", hyde_show_only_final="hyde_show_only_final", doc_json_mode="doc_json_mode", chatbot_role="chatbot_role", speaker="speaker", tts_language="tts_language", tts_speed="tts_speed", ) The provided code snippet includes necessary dependencies for implementing the `_to_h2ogpt_params` function. Write a Python function `def _to_h2ogpt_params(client_params: Dict[str, Any]) -> OrderedDict[str, Any]` to solve the following problem: Convert given params to the order of params in h2oGPT. Here is the function: def _to_h2ogpt_params(client_params: Dict[str, Any]) -> OrderedDict[str, Any]: """Convert given params to the order of params in h2oGPT.""" h2ogpt_params: OrderedDict[str, Any] = collections.OrderedDict() for h2ogpt_param_name, client_param_name in _H2OGPT_PARAMETERS_TO_CLIENT.items(): if client_param_name in client_params: h2ogpt_params[h2ogpt_param_name] = client_params[client_param_name] return h2ogpt_params
Convert given params to the order of params in h2oGPT.
167,183
import json import platform import re import time import traceback from pathlib import Path from time import sleep from urllib import parse import requests import uigf_converter from config import Config, version from gacha_metadata import ( WEB_CACHE_PATH, WEB_CACHE_PATH_GLOB, gacha_query_type_ids, gacha_query_type_dict, ) from utils import config_path, gen_path, logger, press_any_key_to_exit query_type_ids, gacha_query_type_names)) logger.configure( handlers=[ {"sink": sys.stdout, "level": "INFO"}, {"sink": "log.txt", "level": "DEBUG"}, ] ) logger.debug("gen_path: {}", gen_path) logger.debug("config_path: {}", config_path) logger.debug("gachaReportPath: {}", gacha_report_path) def merge_data_func(local_data, gacha_data): for banner in gacha_query_type_dict: banner_local = local_data["gachaLog"][banner] banner_get = gacha_data["gachaLog"][banner] if banner_get == banner_local: pass else: flaglist = [1] * len(banner_get) loc = [[i["time"], i["name"]] for i in banner_local] for i in range(len(banner_get)): gachaGet = banner_get[i] get = [gachaGet["time"], gachaGet["name"]] if get in loc: pass else: flaglist[i] = 0 tempData = [] for i in range(len(banner_get)): if flaglist[i] == 0: gachaGet = banner_get[i] tempData.insert(0, gachaGet) logger.info("合并 {} 追加了 {} 条记录".format(gacha_query_type_dict[banner], len(tempData))) for i in tempData: local_data["gachaLog"][banner].insert(0, i) return local_data
null
167,184
import json import platform import re import time import traceback from pathlib import Path from time import sleep from urllib import parse import requests import uigf_converter from config import Config, version from gacha_metadata import ( WEB_CACHE_PATH, WEB_CACHE_PATH_GLOB, gacha_query_type_ids, gacha_query_type_dict, ) from utils import config_path, gen_path, logger, press_any_key_to_exit def get_api(gachaType, size, page, end_id=""): param_dict = url_query_dict(url) param_dict["size"] = size param_dict["gacha_type"] = gachaType param_dict["page"] = page param_dict["lang"] = "zh-cn" param_dict["end_id"] = end_id param = parse.urlencode(param_dict) path = str(url).split("?")[0] api = path + "?" + param return api query_type_ids, gacha_query_type_names)) logger.configure( handlers=[ {"sink": sys.stdout, "level": "INFO"}, {"sink": "log.txt", "level": "DEBUG"}, ] ) logger.debug("gen_path: {}", gen_path) logger.debug("config_path: {}", config_path) logger.debug("gachaReportPath: {}", gacha_report_path) def get_gacha_logs(gacha_type_id): size = "20" # api限制一页最大20 gacha_list = [] end_id = "0" for page in range(1, 9999): logger.info(f"正在获取 {gacha_query_type_dict[gacha_type_id]} 第 {page} 页") api = get_api(gacha_type_id, size, page, end_id) r = requests.get(api) s = r.content.decode() j = json.loads(s) gacha = j["data"]["list"] if not len(gacha): break for i in gacha: gacha_list.append(i) end_id = j["data"]["list"][-1]["id"] sleep(0.5) return gacha_list
null
167,185
import json import platform import re import time import traceback from pathlib import Path from time import sleep from urllib import parse import requests import uigf_converter from config import Config, version from gacha_metadata import ( WEB_CACHE_PATH, WEB_CACHE_PATH_GLOB, gacha_query_type_ids, gacha_query_type_dict, ) from utils import config_path, gen_path, logger, press_any_key_to_exit logger.configure( handlers=[ {"sink": sys.stdout, "level": "INFO"}, {"sink": "log.txt", "level": "DEBUG"}, ] ) logger.debug("gen_path: {}", gen_path) logger.debug("config_path: {}", config_path) logger.debug("gachaReportPath: {}", gacha_report_path) def to_api(url): url = str(url) logger.debug(url) spliturl = url.split("?") if "hoyoverse" in spliturl[0] or "webstatic-sea" in spliturl[0] or "hk4e-api-os" in spliturl[0]: # https://gs.hoyoverse.com/genshin/event/e20190909gacha-v2/index.html?lang=zh-cn#/log spliturl[0] = "https://hk4e-api-os.hoyoverse.com/gacha_info/api/getGachaLog" else: # https://webstatic.mihoyo.com/hk4e/event/e20190909gacha-v2/index.html?lang=zh-cn#/log spliturl[0] = "https://public-operation-hk4e.mihoyo.com/gacha_info/api/getGachaLog" url = "?".join(spliturl) return url
null
167,186
import json import platform import re import time import traceback from pathlib import Path from time import sleep from urllib import parse import requests import uigf_converter from config import Config, version from gacha_metadata import ( WEB_CACHE_PATH, WEB_CACHE_PATH_GLOB, gacha_query_type_ids, gacha_query_type_dict, ) from utils import config_path, gen_path, logger, press_any_key_to_exit def safe_int(s): try: return int(s) except ValueError: return 0
null
167,187
import json import platform import re import time import traceback from pathlib import Path from time import sleep from urllib import parse import requests import uigf_converter from config import Config, version from gacha_metadata import ( WEB_CACHE_PATH, WEB_CACHE_PATH_GLOB, gacha_query_type_ids, gacha_query_type_dict, ) from utils import config_path, gen_path, logger, press_any_key_to_exit logger.configure( handlers=[ {"sink": sys.stdout, "level": "INFO"}, {"sink": "log.txt", "level": "DEBUG"}, ] ) logger.debug("gen_path: {}", gen_path) logger.debug("config_path: {}", config_path) logger.debug("gachaReportPath: {}", gacha_report_path) def check_api(url): if "?" not in url: logger.error("链接错误") return False try: r = requests.get(url) s = r.content.decode("utf-8") j = json.loads(s) except Exception: logger.error("API请求解析出错: " + traceback.format_exc()) return False logger.debug(j) if not j["data"]: if j["message"] == "authkey timeout": logger.warning("链接过期") elif j["message"] == "authkey error": logger.warning("链接错误") else: logger.warning("数据为空,错误代码:" + j["message"]) return False return True
null
167,188
import pathlib import os import sys import time from gacha_metadata import ( gacha_query_type_ids, gacha_query_type_names, gacha_query_type_dict, gacha_type_dict, ) from utils import logger from config import version def id_generator(): id = 1000000000000000000 while True: id = id + 1 yield str(id) gacha_query_type_ids = ["100", "200", "301", "302"] logger.configure( handlers=[ {"sink": sys.stdout, "level": "INFO"}, {"sink": "log.txt", "level": "DEBUG"}, ] ) logger.debug("gen_path: {}", gen_path) logger.debug("config_path: {}", config_path) logger.debug("gachaReportPath: {}", gacha_report_path) version = "v4.2.0.11162254" def convert(uid, gachaLog): logger.debug("开始转换UIGF") if "gachaLog" in gachaLog: logger.debug("gachaLog key 存在") gachaLog = gachaLog["gachaLog"] UIGF_data = {} UIGF_data["info"] = {} UIGF_data["info"]["uid"] = uid UIGF_data["info"]["lang"] = "zh-cn" UIGF_data["info"]["export_time"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) UIGF_data["info"]["export_app"] = "genshin-gacha-export" UIGF_data["info"]["export_app_version"] = version UIGF_data["info"]["uigf_version"] = "v2.2" UIGF_data["info"]["export_timestamp"] = int(time.time()) all_gachaDictList = [] for gacha_type in gacha_query_type_ids: gacha_log = gachaLog.get(gacha_type, []) gacha_log = sorted(gacha_log, key=lambda gacha: gacha["time"], reverse=True) gacha_log.reverse() for gacha in gacha_log: gacha["uigf_gacha_type"] = gacha_type all_gachaDictList.extend(gacha_log) all_gachaDictList = sorted(all_gachaDictList, key=lambda gacha: gacha["time"]) id = id_generator() for gacha in all_gachaDictList: if gacha.get("id", "") == "": gacha["id"] = next(id) all_gachaDictList = sorted(all_gachaDictList, key=lambda gacha: gacha["id"]) UIGF_data["list"] = all_gachaDictList logger.debug("转换完成 {} 条", len(all_gachaDictList)) return UIGF_data
null
167,189
import json import os import pathlib from typing import Union from utils import logger version = "v4.2.0.11162254" The provided code snippet includes necessary dependencies for implementing the `get_version` function. Write a Python function `def get_version()` to solve the following problem: 从PC启动器api获取游戏版本号 Here is the function: def get_version(): """从PC启动器api获取游戏版本号""" j = requests.get("https://sdk-static.mihoyo.com/hk4e_cn/mdk/launcher/api/resource?key=eYd89JmJ&launcher_id=18").json() version = j["data"]["game"]["latest"]["version"] return "v{}.{}".format(version, time.strftime("%m%d%H%M"))
从PC启动器api获取游戏版本号
167,190
import json import os import gacha_metadata import uigf_converter from utils import logger, gen_path from gacha_metadata import ( gacha_query_type_ids, gacha_query_type_names, gacha_query_type_dict, gacha_type_dict, ) def write_logs(uid, gacha_log): import xlsxwriter import time t = time.strftime("%Y%m%d%H%M%S", time.localtime()) workbook_path = gen_path / f"gachaExport-{uid}-{t}.xlsx" logger.debug(f"创建工作簿: f{workbook_path}") workbook = xlsxwriter.Workbook(workbook_path) for key in gacha_log: gachaDictList = gacha_log[key][::-1] gachaTypeName = gacha_query_type_dict[key] logger.debug("开始写入 {} {}", gachaTypeName, len(gachaDictList)) worksheet = workbook.add_worksheet(gachaTypeName) content_css = workbook.add_format({"align": "left", "font_name": "微软雅黑", "border_color": "#c4c2bf", "bg_color": "#ebebeb", "border": 1}) title_css = workbook.add_format( {"align": "left", "font_name": "微软雅黑", "color": "#757575", "bg_color": "#dbd7d3", "border_color": "#c4c2bf", "border": 1, "bold": True} ) excel_header = ["时间", "名称", "类别", "星级", "祈愿类型", "总次数", "保底内"] worksheet.set_column("A:A", 22) worksheet.set_column("B:B", 14) worksheet.set_column("E:E", 14) worksheet.write_row(0, 0, excel_header, title_css) worksheet.freeze_panes(1, 0) counter = 0 pity_counter = 0 for gacha in gachaDictList: time_str = gacha["time"] name = gacha["name"] item_type = gacha["item_type"] rank_type = gacha["rank_type"] gacha_type = gacha["gacha_type"] uid = gacha["uid"] gacha_type_name = gacha_type_dict.get(gacha_type, "") counter = counter + 1 pity_counter = pity_counter + 1 excel_data = [time_str, name, item_type, rank_type, gacha_type_name, counter, pity_counter] excel_data[3] = int(excel_data[3]) worksheet.write_row(counter, 0, excel_data, content_css) if excel_data[3] == 5: pity_counter = 0 star_5 = workbook.add_format({"color": "#bd6932", "bold": True}) star_4 = workbook.add_format({"color": "#a256e1", "bold": True}) star_3 = workbook.add_format({"color": "#8e8e8e"}) first_row = 1 # 不包含表头第一行 (zero indexed) first_col = 0 # 第一列 last_row = len(gachaDictList) # 最后一行 last_col = len(excel_header) - 1 # 最后一列,zero indexed 所以要减 1 worksheet.conditional_format(first_row, first_col, last_row, last_col, {"type": "formula", "criteria": "=$D2=5", "format": star_5}) worksheet.conditional_format(first_row, first_col, last_row, last_col, {"type": "formula", "criteria": "=$D2=4", "format": star_4}) worksheet.conditional_format(first_row, first_col, last_row, last_col, {"type": "formula", "criteria": "=$D2=3", "format": star_3}) worksheet = workbook.add_worksheet("原始数据") raw_data_header = ["count", "gacha_type", "id", "item_id", "item_type", "lang", "name", "rank_type", "time", "uid", "uigf_gacha_type"] worksheet.write_row(0, 0, raw_data_header) uigf_data = uigf_converter.convert(uid, gacha_log) all_gachaDictList = uigf_data["list"] all_counter = 0 for gacha in all_gachaDictList: count = gacha.get("count", "") gacha_type = gacha.get("gacha_type", "") id = gacha.get("id", "") item_id = gacha.get("item_id", "") item_type = gacha.get("item_type", "") lang = gacha.get("lang", "") name = gacha.get("name", "") rank_type = gacha.get("rank_type", "") time_str = gacha.get("time", "") uid = gacha.get("uid", "") uigf_gacha_type = gacha.get("uigf_gacha_type", "") excel_data = [count, gacha_type, id, item_id, item_type, lang, name, rank_type, time_str, uid, uigf_gacha_type] worksheet.write_row(all_counter + 1, 0, excel_data) all_counter += 1 workbook.close() logger.debug("工作簿写入完成") logger.configure( handlers=[ {"sink": sys.stdout, "level": "INFO"}, {"sink": "log.txt", "level": "DEBUG"}, ] ) logger.debug("gen_path: {}", gen_path) logger.debug("config_path: {}", config_path) logger.debug("gachaReportPath: {}", gacha_report_path) def write(uid, gachaLog): if "gachaLog" in gachaLog: logger.debug("gachaLog key 存在") gachaLog = gachaLog["gachaLog"] logger.info("开始写入XLSX") write_logs(uid, gachaLog) logger.debug("写入完成")
null
167,191
from clipboard_utils import get_url_from_clipboard from utils import logger import subprocess def get_url_from_clipboard(): text = get_clipboad_text_or_html() logger.debug(f"get_clipboad_text_or_html {text}") url = get_url_from_string(text) logger.debug(f"get_url_from_string {url}") return url def capture(FLAG_USE_CAPTURE_BINARY): subprocess.Popen(FLAG_USE_CAPTURE_BINARY, stdout=subprocess.PIPE, shell=True).communicate() url = get_url_from_clipboard() return url
null
167,192
import re import os import sympy import pandas as pd from tot.tasks.base import Task, DATA_PATH from tot.prompts.game24 import * def get_current_numbers(y: str) -> str: last_line = y.strip().split('\n')[-1] return last_line.split('left: ')[-1].split(')')[0]
null
167,193
import os import json import argparse from tot.tasks import get_task from tot.methods.bfs import solve, naive_solve from tot.models import gpt_usage def get_task(name): def solve(args, task, idx, to_print=True): def naive_solve(args, task, idx, to_print=True): def gpt_usage(backend="gpt-4"): def run(args): task = get_task(args.task) logs, cnt_avg, cnt_any = [], 0, 0 if args.naive_run: file = f'./logs/{args.task}/{args.backend}_{args.temperature}_naive_{args.prompt_sample}_sample_{args.n_generate_sample}_start{args.task_start_index}_end{args.task_end_index}.json' else: file = f'./logs/{args.task}/{args.backend}_{args.temperature}_{args.method_generate}{args.n_generate_sample}_{args.method_evaluate}{args.n_evaluate_sample}_{args.method_select}{args.n_select_sample}_start{args.task_start_index}_end{args.task_end_index}.json' os.makedirs(os.path.dirname(file), exist_ok=True) for i in range(args.task_start_index, args.task_end_index): # solve if args.naive_run: ys, info = naive_solve(args, task, i) else: ys, info = solve(args, task, i) # log infos = [task.test_output(i, y) for y in ys] info.update({'idx': i, 'ys': ys, 'infos': infos, 'usage_so_far': gpt_usage(args.backend)}) logs.append(info) with open(file, 'w') as f: json.dump(logs, f, indent=4) # log main metric accs = [info['r'] for info in infos] cnt_avg += sum(accs) / len(accs) cnt_any += any(accs) print(i, 'sum(accs)', sum(accs), 'cnt_avg', cnt_avg, 'cnt_any', cnt_any, '\n') n = args.task_end_index - args.task_start_index print(cnt_avg / n, cnt_any / n) print('usage_so_far', gpt_usage(args.backend))
null
167,194
import os import json import argparse from tot.tasks import get_task from tot.methods.bfs import solve, naive_solve from tot.models import gpt_usage def parse_args(): args = argparse.ArgumentParser() args.add_argument('--backend', type=str, choices=['gpt-4', 'gpt-3.5-turbo'], default='gpt-4') args.add_argument('--temperature', type=float, default=0.7) args.add_argument('--task', type=str, required=True, choices=['game24', 'text', 'crosswords']) args.add_argument('--task_start_index', type=int, default=900) args.add_argument('--task_end_index', type=int, default=1000) args.add_argument('--naive_run', action='store_true') args.add_argument('--prompt_sample', type=str, choices=['standard', 'cot']) # only used when method_generate = sample, or naive_run args.add_argument('--method_generate', type=str, choices=['sample', 'propose']) args.add_argument('--method_evaluate', type=str, choices=['value', 'vote']) args.add_argument('--method_select', type=str, choices=['sample', 'greedy'], default='greedy') args.add_argument('--n_generate_sample', type=int, default=1) # only thing needed if naive_run args.add_argument('--n_evaluate_sample', type=int, default=1) args.add_argument('--n_select_sample', type=int, default=1) args = args.parse_args() return args
null
167,195
import argparse import os, sys import uuid from pathlib import Path import main as detection import submitit def parse_args(): detection_parser = detection.get_args_parser() parser = argparse.ArgumentParser("Submitit for detection", parents=[detection_parser]) parser.add_argument("--ngpus", default=8, type=int, help="Number of gpus to request on each node") parser.add_argument("--nodes", default=1, type=int, help="Number of nodes to request") parser.add_argument("--timeout", default=60, type=int, help="Duration of the job") parser.add_argument("--cpus_per_task", default=16, type=int, help="Duration of the job") parser.add_argument("--job_dir", default="", type=str, help="Job dir. Leave empty for automatic.") parser.add_argument("--job_name", type=str, help="Job name.") parser.add_argument("--qos", type=str, default=None, help="specify preemptive QOS.") parser.add_argument("--requeue", action='store_true', help="job requeue if preempted.") parser.add_argument("--mail_type", type=str, default='ALL', help=" send email when job begins, ends, fails or preempted.") parser.add_argument("--mail_user", type=str, default='', help=" email address.") # refer to https://slurm.schedmd.com/sbatch.html & \ # https://github.com/facebookincubator/submitit/blob/11d8f87f785669e8a01aa9773a107f9180a63b09/submitit/slurm/slurm.py \ # for more details about parameters of slurm. return parser.parse_args()
null
167,196
import argparse import os, sys import uuid from pathlib import Path import main as detection import submitit def get_shared_folder() -> Path: user = os.getenv("USER") if Path("/comp_robot").is_dir(): p = Path(f"/comp_robot/{user}/experiments") p.mkdir(exist_ok=True) return p raise RuntimeError("No shared folder available") def get_init_file(): # Init file must not exist, but it's parent dir must exist. os.makedirs(str(get_shared_folder()), exist_ok=True) init_file = get_shared_folder() / f"{uuid.uuid4().hex}_init" if init_file.exists(): os.remove(str(init_file)) return init_file
null
167,197
import argparse import datetime import json import random import time from pathlib import Path import os, sys import numpy as np import torch from torch.utils.data import DataLoader, DistributedSampler from util.get_param_dicts import get_param_dict from util.logger import setup_logger from util.slconfig import DictAction, SLConfig from util.utils import ModelEma, BestMetricHolder import util.misc as utils import datasets from datasets import build_dataset, get_coco_api_from_dataset from engine import evaluate, train_one_epoch, test class DictAction(Action): """ argparse action to split an argument into KEY=VALUE form on the first = and append to a dictionary. List options should be passed as comma separated values, i.e KEY=V1,V2,V3 """ def _parse_int_float_bool(val): try: return int(val) except ValueError: pass try: return float(val) except ValueError: pass if val.lower() in ['true', 'false']: return True if val.lower() == 'true' else False if val.lower() in ['none', 'null']: return None return val def __call__(self, parser, namespace, values, option_string=None): options = {} for kv in values: key, val = kv.split('=', maxsplit=1) val = [self._parse_int_float_bool(v) for v in val.split(',')] if len(val) == 1: val = val[0] options[key] = val setattr(namespace, self.dest, options) def get_args_parser(): parser = argparse.ArgumentParser('Set transformer detector', add_help=False) parser.add_argument('--config_file', '-c', type=str, required=True) parser.add_argument('--options', nargs='+', action=DictAction, help='override some settings in the used config, the key-value pair ' 'in xxx=yyy format will be merged into config file.') # dataset parameters parser.add_argument('--dataset_file', default='coco') parser.add_argument('--coco_path', type=str, default='/comp_robot/cv_public_dataset/COCO2017/') parser.add_argument('--coco_panoptic_path', type=str) parser.add_argument('--remove_difficult', action='store_true') parser.add_argument('--fix_size', action='store_true') # training parameters parser.add_argument('--output_dir', default='', help='path where to save, empty for no saving') parser.add_argument('--note', default='', help='add some notes to the experiment') parser.add_argument('--device', default='cuda', help='device to use for training / testing') parser.add_argument('--seed', default=42, type=int) parser.add_argument('--resume', default='', help='resume from checkpoint') parser.add_argument('--pretrain_model_path', help='load from other checkpoint') parser.add_argument('--finetune_ignore', type=str, nargs='+') parser.add_argument('--start_epoch', default=0, type=int, metavar='N', help='start epoch') parser.add_argument('--eval', action='store_true') parser.add_argument('--num_workers', default=10, type=int) parser.add_argument('--test', action='store_true') parser.add_argument('--debug', action='store_true') parser.add_argument('--find_unused_params', action='store_true') parser.add_argument('--save_results', action='store_true') parser.add_argument('--save_log', action='store_true') # distributed training parameters parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes') parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training') parser.add_argument('--rank', default=0, type=int, help='number of distributed processes') parser.add_argument("--local_rank", type=int, help='local rank for DistributedDataParallel') parser.add_argument('--amp', action='store_true', help="Train with mixed precision") return parser
null
167,200
import os import contextlib import copy import numpy as np import torch from pycocotools.cocoeval import COCOeval from pycocotools.coco import COCO import pycocotools.mask as mask_util from util.misc import all_gather The provided code snippet includes necessary dependencies for implementing the `evaluate` function. Write a Python function `def evaluate(self)` to solve the following problem: Run per image evaluation on given images and store results (a list of dict) in self.evalImgs :return: None Here is the function: def evaluate(self): ''' Run per image evaluation on given images and store results (a list of dict) in self.evalImgs :return: None ''' p = self.params # add backward compatibility if useSegm is specified in params if p.useSegm is not None: p.iouType = 'segm' if p.useSegm == 1 else 'bbox' print('useSegm (deprecated) is not None. Running {} evaluation'.format(p.iouType)) p.imgIds = list(np.unique(p.imgIds)) if p.useCats: p.catIds = list(np.unique(p.catIds)) p.maxDets = sorted(p.maxDets) self.params = p self._prepare() # loop through images, area range, max detection number catIds = p.catIds if p.useCats else [-1] if p.iouType == 'segm' or p.iouType == 'bbox': computeIoU = self.computeIoU elif p.iouType == 'keypoints': computeIoU = self.computeOks self.ious = { (imgId, catId): computeIoU(imgId, catId) for imgId in p.imgIds for catId in catIds} evaluateImg = self.evaluateImg maxDet = p.maxDets[-1] evalImgs = [ evaluateImg(imgId, catId, areaRng, maxDet) for catId in catIds for areaRng in p.areaRng for imgId in p.imgIds ] # this is NOT in the pycocotools code, but could be done outside evalImgs = np.asarray(evalImgs).reshape(len(catIds), len(p.areaRng), len(p.imgIds)) self._paramsEval = copy.deepcopy(self.params) return p.imgIds, evalImgs
Run per image evaluation on given images and store results (a list of dict) in self.evalImgs :return: None
167,203
import random import PIL import torch import torchvision.transforms as T import torchvision.transforms.functional as F from util.box_ops import box_xyxy_to_cxcywh from util.misc import interpolate def interpolate(input, size=None, scale_factor=None, mode="nearest", align_corners=None): # type: (Tensor, Optional[List[int]], Optional[float], str, Optional[bool]) -> Tensor """ Equivalent to nn.functional.interpolate, but with support for empty batch sizes. This will eventually be supported natively by PyTorch, and this class can go away. """ if __torchvision_need_compat_flag < 0.7: if input.numel() > 0: return torch.nn.functional.interpolate( input, size, scale_factor, mode, align_corners ) output_shape = _output_size(2, input, size, scale_factor) output_shape = list(input.shape[:-2]) + list(output_shape) return _new_empty_tensor(input, output_shape) else: return torchvision.ops.misc.interpolate(input, size, scale_factor, mode, align_corners) def resize(image, target, size, max_size=None): # size can be min_size (scalar) or (w, h) tuple def get_size_with_aspect_ratio(image_size, size, max_size=None): w, h = image_size if max_size is not None: min_original_size = float(min((w, h))) max_original_size = float(max((w, h))) if max_original_size / min_original_size * size > max_size: size = int(round(max_size * min_original_size / max_original_size)) if (w <= h and w == size) or (h <= w and h == size): return (h, w) if w < h: ow = size oh = int(size * h / w) else: oh = size ow = int(size * w / h) return (oh, ow) def get_size(image_size, size, max_size=None): if isinstance(size, (list, tuple)): return size[::-1] else: return get_size_with_aspect_ratio(image_size, size, max_size) size = get_size(image.size, size, max_size) rescaled_image = F.resize(image, size) if target is None: return rescaled_image, None ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(rescaled_image.size, image.size)) ratio_width, ratio_height = ratios target = target.copy() if "boxes" in target: boxes = target["boxes"] scaled_boxes = boxes * torch.as_tensor([ratio_width, ratio_height, ratio_width, ratio_height]) target["boxes"] = scaled_boxes if "area" in target: area = target["area"] scaled_area = area * (ratio_width * ratio_height) target["area"] = scaled_area h, w = size target["size"] = torch.tensor([h, w]) if "masks" in target: target['masks'] = interpolate( target['masks'][:, None].float(), size, mode="nearest")[:, 0] > 0.5 return rescaled_image, target
null
167,205
import PIL from PIL import Image import torch import os import torchvision.transforms.functional as F import numpy as np import random from .random_crop import random_crop from util.box_ops import box_cxcywh_to_xyxy, box_xyxy_to_cxcywh The provided code snippet includes necessary dependencies for implementing the `lighting_noise` function. Write a Python function `def lighting_noise(image)` to solve the following problem: color channel swap in image image: A PIL image Here is the function: def lighting_noise(image): ''' color channel swap in image image: A PIL image ''' new_image = image perms = ((0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)) swap = perms[random.randint(0, len(perms)- 1)] new_image = F.to_tensor(new_image) new_image = new_image[swap, :, :] new_image = F.to_pil_image(new_image) return new_image
color channel swap in image image: A PIL image
167,206
import PIL from PIL import Image import torch import os import torchvision.transforms.functional as F import numpy as np import random from .random_crop import random_crop from util.box_ops import box_cxcywh_to_xyxy, box_xyxy_to_cxcywh The provided code snippet includes necessary dependencies for implementing the `rotate` function. Write a Python function `def rotate(image, boxes, angle)` to solve the following problem: Rotate image and bounding box image: A Pil image (w, h) boxes: A tensors of dimensions (#objects, 4) Out: rotated image (w, h), rotated boxes Here is the function: def rotate(image, boxes, angle): ''' Rotate image and bounding box image: A Pil image (w, h) boxes: A tensors of dimensions (#objects, 4) Out: rotated image (w, h), rotated boxes ''' new_image = image.copy() new_boxes = boxes.clone() #Rotate image, expand = True w = image.width h = image.height cx = w/2 cy = h/2 new_image = new_image.rotate(angle, expand=True) angle = np.radians(angle) alpha = np.cos(angle) beta = np.sin(angle) #Get affine matrix AffineMatrix = torch.tensor([[alpha, beta, (1-alpha)*cx - beta*cy], [-beta, alpha, beta*cx + (1-alpha)*cy]]) #Rotation boxes box_width = (boxes[:,2] - boxes[:,0]).reshape(-1,1) box_height = (boxes[:,3] - boxes[:,1]).reshape(-1,1) #Get corners for boxes x1 = boxes[:,0].reshape(-1,1) y1 = boxes[:,1].reshape(-1,1) x2 = x1 + box_width y2 = y1 x3 = x1 y3 = y1 + box_height x4 = boxes[:,2].reshape(-1,1) y4 = boxes[:,3].reshape(-1,1) corners = torch.stack((x1,y1,x2,y2,x3,y3,x4,y4), dim= 1) # corners.reshape(-1, 8) #Tensors of dimensions (#objects, 8) corners = corners.reshape(-1,2) #Tensors of dimension (4* #objects, 2) corners = torch.cat((corners, torch.ones(corners.shape[0], 1)), dim= 1) #(Tensors of dimension (4* #objects, 3)) cos = np.abs(AffineMatrix[0, 0]) sin = np.abs(AffineMatrix[0, 1]) nW = int((h * sin) + (w * cos)) nH = int((h * cos) + (w * sin)) AffineMatrix[0, 2] += (nW / 2) - cx AffineMatrix[1, 2] += (nH / 2) - cy #Apply affine transform rotate_corners = torch.mm(AffineMatrix, corners.t().to(torch.float64)).t() rotate_corners = rotate_corners.reshape(-1,8) x_corners = rotate_corners[:,[0,2,4,6]] y_corners = rotate_corners[:,[1,3,5,7]] #Get (x_min, y_min, x_max, y_max) x_min, _ = torch.min(x_corners, dim= 1) x_min = x_min.reshape(-1, 1) y_min, _ = torch.min(y_corners, dim= 1) y_min = y_min.reshape(-1, 1) x_max, _ = torch.max(x_corners, dim= 1) x_max = x_max.reshape(-1, 1) y_max, _ = torch.max(y_corners, dim= 1) y_max = y_max.reshape(-1, 1) new_boxes = torch.cat((x_min, y_min, x_max, y_max), dim= 1) scale_x = new_image.width / w scale_y = new_image.height / h #Resize new image to (w, h) new_image = new_image.resize((w, h)) #Resize boxes new_boxes /= torch.Tensor([scale_x, scale_y, scale_x, scale_y]) new_boxes[:, 0] = torch.clamp(new_boxes[:, 0], 0, w) new_boxes[:, 1] = torch.clamp(new_boxes[:, 1], 0, h) new_boxes[:, 2] = torch.clamp(new_boxes[:, 2], 0, w) new_boxes[:, 3] = torch.clamp(new_boxes[:, 3], 0, h) return new_image, new_boxes
Rotate image and bounding box image: A Pil image (w, h) boxes: A tensors of dimensions (#objects, 4) Out: rotated image (w, h), rotated boxes
167,207
import json from pathlib import Path import numpy as np import torch from PIL import Image from panopticapi.utils import rgb2id from util.box_ops import masks_to_boxes from .coco import make_coco_transforms class CocoPanoptic: def __init__(self, img_folder, ann_folder, ann_file, transforms=None, return_masks=True): with open(ann_file, 'r') as f: self.coco = json.load(f) # sort 'images' field so that they are aligned with 'annotations' # i.e., in alphabetical order self.coco['images'] = sorted(self.coco['images'], key=lambda x: x['id']) # sanity check if "annotations" in self.coco: for img, ann in zip(self.coco['images'], self.coco['annotations']): assert img['file_name'][:-4] == ann['file_name'][:-4] self.img_folder = img_folder self.ann_folder = ann_folder self.ann_file = ann_file self.transforms = transforms self.return_masks = return_masks def __getitem__(self, idx): ann_info = self.coco['annotations'][idx] if "annotations" in self.coco else self.coco['images'][idx] img_path = Path(self.img_folder) / ann_info['file_name'].replace('.png', '.jpg') ann_path = Path(self.ann_folder) / ann_info['file_name'] img = Image.open(img_path).convert('RGB') w, h = img.size if "segments_info" in ann_info: masks = np.asarray(Image.open(ann_path), dtype=np.uint32) masks = rgb2id(masks) ids = np.array([ann['id'] for ann in ann_info['segments_info']]) masks = masks == ids[:, None, None] masks = torch.as_tensor(masks, dtype=torch.uint8) labels = torch.tensor([ann['category_id'] for ann in ann_info['segments_info']], dtype=torch.int64) target = {} target['image_id'] = torch.tensor([ann_info['image_id'] if "image_id" in ann_info else ann_info["id"]]) if self.return_masks: target['masks'] = masks target['labels'] = labels target["boxes"] = masks_to_boxes(masks) target['size'] = torch.as_tensor([int(h), int(w)]) target['orig_size'] = torch.as_tensor([int(h), int(w)]) if "segments_info" in ann_info: for name in ['iscrowd', 'area']: target[name] = torch.tensor([ann[name] for ann in ann_info['segments_info']]) if self.transforms is not None: img, target = self.transforms(img, target) return img, target def __len__(self): return len(self.coco['images']) def get_height_and_width(self, idx): img_info = self.coco['images'][idx] height = img_info['height'] width = img_info['width'] return height, width def make_coco_transforms(image_set, fix_size=False, strong_aug=False, args=None): normalize = T.Compose([ T.ToTensor(), T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) # config the params for data aug scales = [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800] max_size = 1333 scales2_resize = [400, 500, 600] scales2_crop = [384, 600] # update args from config files scales = getattr(args, 'data_aug_scales', scales) max_size = getattr(args, 'data_aug_max_size', max_size) scales2_resize = getattr(args, 'data_aug_scales2_resize', scales2_resize) scales2_crop = getattr(args, 'data_aug_scales2_crop', scales2_crop) # resize them data_aug_scale_overlap = getattr(args, 'data_aug_scale_overlap', None) if data_aug_scale_overlap is not None and data_aug_scale_overlap > 0: data_aug_scale_overlap = float(data_aug_scale_overlap) scales = [int(i*data_aug_scale_overlap) for i in scales] max_size = int(max_size*data_aug_scale_overlap) scales2_resize = [int(i*data_aug_scale_overlap) for i in scales2_resize] scales2_crop = [int(i*data_aug_scale_overlap) for i in scales2_crop] datadict_for_print = { 'scales': scales, 'max_size': max_size, 'scales2_resize': scales2_resize, 'scales2_crop': scales2_crop } print("data_aug_params:", json.dumps(datadict_for_print, indent=2)) if image_set == 'train': if fix_size: return T.Compose([ T.RandomHorizontalFlip(), T.RandomResize([(max_size, max(scales))]), # T.RandomResize([(512, 512)]), normalize, ]) if strong_aug: import datasets.sltransform as SLT return T.Compose([ T.RandomHorizontalFlip(), T.RandomSelect( T.RandomResize(scales, max_size=max_size), T.Compose([ T.RandomResize(scales2_resize), T.RandomSizeCrop(*scales2_crop), T.RandomResize(scales, max_size=max_size), ]) ), SLT.RandomSelectMulti([ SLT.RandomCrop(), SLT.LightingNoise(), SLT.AdjustBrightness(2), SLT.AdjustContrast(2), ]), normalize, ]) return T.Compose([ T.RandomHorizontalFlip(), T.RandomSelect( T.RandomResize(scales, max_size=max_size), T.Compose([ T.RandomResize(scales2_resize), T.RandomSizeCrop(*scales2_crop), T.RandomResize(scales, max_size=max_size), ]) ), normalize, ]) if image_set in ['val', 'eval_debug', 'train_reg', 'test']: if os.environ.get("GFLOPS_DEBUG_SHILONG", False) == 'INFO': print("Under debug mode for flops calculation only!!!!!!!!!!!!!!!!") return T.Compose([ T.ResizeDebug((1280, 800)), normalize, ]) return T.Compose([ T.RandomResize([max(scales)], max_size=max_size), normalize, ]) raise ValueError(f'unknown {image_set}') def build(image_set, args): img_folder_root = Path(args.coco_path) ann_folder_root = Path(args.coco_panoptic_path) assert img_folder_root.exists(), f'provided COCO path {img_folder_root} does not exist' assert ann_folder_root.exists(), f'provided COCO path {ann_folder_root} does not exist' mode = 'panoptic' PATHS = { "train": ("train2017", Path("annotations") / f'{mode}_train2017.json'), "val": ("val2017", Path("annotations") / f'{mode}_val2017.json'), } img_folder, ann_file = PATHS[image_set] img_folder_path = img_folder_root / img_folder ann_folder = ann_folder_root / f'{mode}_{img_folder}' ann_file = ann_folder_root / ann_file dataset = CocoPanoptic(img_folder_path, ann_folder, ann_file, transforms=make_coco_transforms(image_set), return_masks=args.masks) return dataset
null
167,208
import json from pathlib import Path import random import os import torch import torch.utils.data import torchvision from pycocotools import mask as coco_mask from datasets.data_util import preparing_dataset import datasets.transforms as T from util.box_ops import box_cxcywh_to_xyxy, box_iou The provided code snippet includes necessary dependencies for implementing the `label2onehot` function. Write a Python function `def label2onehot(label, num_classes)` to solve the following problem: label: Tensor(K) Here is the function: def label2onehot(label, num_classes): """ label: Tensor(K) """ res = torch.zeros(num_classes) for i in label: itm = int(i.item()) res[itm] = 1.0 return res
label: Tensor(K)
167,209
import json from pathlib import Path import random import os import torch import torch.utils.data import torchvision from pycocotools import mask as coco_mask from datasets.data_util import preparing_dataset import datasets.transforms as T from util.box_ops import box_cxcywh_to_xyxy, box_iou def convert_coco_poly_to_mask(segmentations, height, width): masks = [] for polygons in segmentations: rles = coco_mask.frPyObjects(polygons, height, width) mask = coco_mask.decode(rles) if len(mask.shape) < 3: mask = mask[..., None] mask = torch.as_tensor(mask, dtype=torch.uint8) mask = mask.any(dim=2) masks.append(mask) if masks: masks = torch.stack(masks, dim=0) else: masks = torch.zeros((0, height, width), dtype=torch.uint8) return masks
null