| import datetime |
| import logging |
| import logging.handlers |
| import os |
| import sys |
| import time |
|
|
| import requests |
|
|
| from vtimellm.constants import LOGDIR |
|
|
| server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**" |
| moderation_msg = "YOUR INPUT VIOLATES OUR CONTENT MODERATION GUIDELINES. PLEASE TRY AGAIN." |
|
|
| handler = None |
|
|
|
|
| def build_logger(logger_name, logger_filename): |
| global handler |
|
|
| formatter = logging.Formatter( |
| fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s", |
| datefmt="%Y-%m-%d %H:%M:%S", |
| ) |
|
|
| |
| if not logging.getLogger().handlers: |
| logging.basicConfig(level=logging.INFO) |
| logging.getLogger().handlers[0].setFormatter(formatter) |
|
|
| |
| stdout_logger = logging.getLogger("stdout") |
| stdout_logger.setLevel(logging.INFO) |
| sl = StreamToLogger(stdout_logger, logging.INFO) |
| sys.stdout = sl |
|
|
| stderr_logger = logging.getLogger("stderr") |
| stderr_logger.setLevel(logging.ERROR) |
| sl = StreamToLogger(stderr_logger, logging.ERROR) |
| sys.stderr = sl |
|
|
| |
| logger = logging.getLogger(logger_name) |
| logger.setLevel(logging.INFO) |
|
|
| |
| if handler is None: |
| os.makedirs(LOGDIR, exist_ok=True) |
| filename = os.path.join(LOGDIR, logger_filename) |
| handler = logging.handlers.TimedRotatingFileHandler( |
| filename, when='D', utc=True) |
| handler.setFormatter(formatter) |
|
|
| for name, item in logging.root.manager.loggerDict.items(): |
| if isinstance(item, logging.Logger): |
| item.addHandler(handler) |
|
|
| return logger |
|
|
|
|
| class StreamToLogger(object): |
| """ |
| Fake file-like stream object that redirects writes to a logger instance. |
| """ |
| def __init__(self, logger, log_level=logging.INFO): |
| self.terminal = sys.stdout |
| self.logger = logger |
| self.log_level = log_level |
| self.linebuf = '' |
|
|
| def __getattr__(self, attr): |
| return getattr(self.terminal, attr) |
|
|
| def write(self, buf): |
| temp_linebuf = self.linebuf + buf |
| self.linebuf = '' |
| for line in temp_linebuf.splitlines(True): |
| |
| |
| |
| |
| |
| if line[-1] == '\n': |
| self.logger.log(self.log_level, line.rstrip()) |
| else: |
| self.linebuf += line |
|
|
| def flush(self): |
| if self.linebuf != '': |
| self.logger.log(self.log_level, self.linebuf.rstrip()) |
| self.linebuf = '' |
|
|
|
|
| def disable_torch_init(): |
| """ |
| Disable the redundant torch default initialization to accelerate model creation. |
| """ |
| import torch |
| setattr(torch.nn.Linear, "reset_parameters", lambda self: None) |
| setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None) |
|
|
|
|
| def violates_moderation(text): |
| """ |
| Check whether the text violates OpenAI moderation API. |
| """ |
| url = "https://api.openai.com/v1/moderations" |
| headers = {"Content-Type": "application/json", |
| "Authorization": "Bearer " + os.environ["OPENAI_API_KEY"]} |
| text = text.replace("\n", "") |
| data = "{" + '"input": ' + f'"{text}"' + "}" |
| data = data.encode("utf-8") |
| try: |
| ret = requests.post(url, headers=headers, data=data, timeout=5) |
| flagged = ret.json()["results"][0]["flagged"] |
| except requests.exceptions.RequestException as e: |
| flagged = False |
| except KeyError as e: |
| flagged = False |
|
|
| return flagged |
|
|
|
|
| def pretty_print_semaphore(semaphore): |
| if semaphore is None: |
| return "None" |
| return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})" |
|
|
| def get_gpu_status(): |
| """ |
| Check the gpu stats and return the valid number of available gpus |
| """ |
| from gpustat.core import GPUStatCollection |
|
|
| gpus_stats = GPUStatCollection.new_query() |
|
|
| info = gpus_stats.jsonify()["gpus"] |
| gpu_list = [] |
|
|
| mem_ratio_threshold = 0.1 |
| util_ratio_threshold = 10 |
| for idx, each in enumerate(info): |
| mem_ratio = each["memory.used"] / each["memory.total"] |
| util_ratio = each["utilization.gpu"] |
| if mem_ratio < mem_ratio_threshold and util_ratio < util_ratio_threshold: |
| gpu_list.append(idx) |
| print("Scan GPUs to get {} free GPU ({})".format(len(gpu_list), gpu_list)) |
| return gpu_list |
|
|
| def check_gpu_status(gpu_option): |
| if gpu_option == 'cuda': |
| env_var = 'CUDA_VISIBLE_DEVICES' |
| elif gpu_option == 'gpu_vis': |
| env_var = 'gpu_vis' |
| print(f'gpu option is {env_var}') |
| gpu_list = [int(x) for x in os.environ[env_var].split(',')] |
| if len(gpu_list) == 0: |
| assert False, 'Please specify the gpu_vis in the environment variable with export.' |
| available_gpu = get_gpu_status() |
| while gpu_list != available_gpu: |
| print("No available GPU, waiting for 1 minutes until {} get freed. Current time : {}".format(gpu_list, time.ctime())) |
| time.sleep(60) |
| available_gpu = get_gpu_status() |
| print("GPU is available now. Current time : {}".format(time.ctime())) |