-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
utils.py
3083 lines (2601 loc) · 103 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ast
import asyncio
import base64
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 array import array
from collections import deque
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
from urllib.parse import urlparse
import filelock
import fire
import numpy as np
import pandas as pd
import requests
import uuid
import re
from packaging import version
import tabulate
from fire import inspectutils
from joblib import Parallel
from tqdm.auto import tqdm
from enums import split_google, invalid_json_str, docs_joiner_default, git_hash_unset, is_json_model, \
openai_supports_functiontools, openai_supports_parallel_functiontools, does_support_functiontools
from utils_procs import reulimit
reulimit()
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 set_seed(seed: int):
"""
Sets the seed of the entire notebook so results are the same every time we run.
This is for REPRODUCIBILITY.
"""
import torch
np.random.seed(seed)
random_state = np.random.RandomState(seed)
random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
os.environ['PYTHONHASHSEED'] = str(seed)
return random_state
def flatten_list(lis):
"""Given a list, possibly nested to any level, return it flattened."""
new_lis = []
for item in lis:
if type(item) == type([]):
new_lis.extend(flatten_list(item))
else:
new_lis.append(item)
return new_lis
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 ping():
try:
print('Ping: %s' % str(datetime.now()), flush=True)
except AttributeError:
# some programs wrap print and will fail with flush passed
pass
def ping_gpu():
try:
print('Ping_GPU: %s %s' % (str(datetime.now()), system_info()), flush=True)
except AttributeError:
# some programs wrap print and will fail with flush passed
pass
try:
ping_gpu_memory()
except Exception as e:
print('Ping_GPU memory failure: %s' % str(e), flush=True)
def ping_gpu_memory():
from models.gpu_mem_track import MemTracker
gpu_tracker = MemTracker() # define a GPU tracker
from torch.cuda import memory_summary
gpu_tracker.track()
def get_torch_allocated():
import torch
return torch.cuda.memory_allocated()
def get_device(n_gpus=None):
import torch
if torch.cuda.is_available() and n_gpus != 0:
device = "cuda"
elif torch.backends.mps.is_built():
device = "mps"
else:
device = "cpu"
return device
def system_info():
import psutil
system = {}
# https://stackoverflow.com/questions/48951136/plot-multiple-graphs-in-one-plot-using-tensorboard
# https://arshren.medium.com/monitoring-your-devices-in-python-5191d672f749
try:
temps = psutil.sensors_temperatures(fahrenheit=False)
if 'coretemp' in temps:
coretemp = temps['coretemp']
temp_dict = {k.label: k.current for k in coretemp}
for k, v in temp_dict.items():
system['CPU_C/%s' % k] = v
except AttributeError:
pass
# https://github.com/gpuopenanalytics/pynvml/blob/master/help_query_gpu.txt
try:
from pynvml.smi import nvidia_smi
nvsmi = nvidia_smi.getInstance()
gpu_power_dict = {'W_gpu%d' % i: x['power_readings']['power_draw'] for i, x in
enumerate(nvsmi.DeviceQuery('power.draw')['gpu'])}
for k, v in gpu_power_dict.items():
system['GPU_W/%s' % k] = v
gpu_temp_dict = {'C_gpu%d' % i: x['temperature']['gpu_temp'] for i, x in
enumerate(nvsmi.DeviceQuery('temperature.gpu')['gpu'])}
for k, v in gpu_temp_dict.items():
system['GPU_C/%s' % k] = v
gpu_memory_free_dict = {'MiB_gpu%d' % i: x['fb_memory_usage']['free'] for i, x in
enumerate(nvsmi.DeviceQuery('memory.free')['gpu'])}
gpu_memory_total_dict = {'MiB_gpu%d' % i: x['fb_memory_usage']['total'] for i, x in
enumerate(nvsmi.DeviceQuery('memory.total')['gpu'])}
gpu_memory_frac_dict = {k: gpu_memory_free_dict[k] / gpu_memory_total_dict[k] for k in gpu_memory_total_dict}
for k, v in gpu_memory_frac_dict.items():
system[f'GPU_M/%s' % k] = v
except (KeyError, ModuleNotFoundError):
pass
system['hash'] = get_githash()
debug_mem = False
if debug_mem:
try:
# pip install guppy3
from guppy import hpy
h = hpy()
print(h.heap())
print(h.heap().byvia)
print(h.heap().byid)
except:
pass
return system
def system_info_print():
try:
df = pd.DataFrame.from_dict(system_info(), orient='index')
# avoid slamming GPUs
time.sleep(1)
return df.to_markdown()
except Exception as e:
return "Error: %s" % str(e)
def zip_data(root_dirs=None, zip_file=None, base_dir='./', fail_any_exception=False):
try:
return _zip_data(zip_file=zip_file, base_dir=base_dir, root_dirs=root_dirs)
except Exception as e:
traceback.print_exc()
print('Exception in zipping: %s' % str(e))
if not fail_any_exception:
raise
def _zip_data(root_dirs=None, zip_file=None, base_dir='./'):
if isinstance(root_dirs, str):
root_dirs = [root_dirs]
if zip_file is None:
datetime_str = str(datetime.now()).replace(" ", "_").replace(":", "_")
host_name = os.getenv('HF_HOSTNAME', 'emptyhost')
zip_file = "data_%s_%s.zip" % (datetime_str, host_name)
assert root_dirs is not None
base_path = os.path.dirname(zip_file)
if not os.path.isdir(base_path) and os.path.dirname(zip_file):
base_path = makedirs(base_path, exist_ok=True, tmp_ok=True, use_base=True)
zip_file = os.path.join(base_path, os.path.basename(zip_file))
with zipfile.ZipFile(zip_file, "w") as expt_zip:
for root_dir in root_dirs:
if root_dir is None:
continue
for root, d, files in os.walk(root_dir):
for file in files:
file_to_archive = os.path.join(root, file)
assert os.path.exists(file_to_archive)
path_to_archive = os.path.relpath(file_to_archive, base_dir)
expt_zip.write(filename=file_to_archive, arcname=path_to_archive)
return zip_file, zip_file
def tar_data(root_dirs=None, tar_file=None, base_dir='./', fail_any_exception=False):
try:
return _tar_data(tar_file=tar_file, base_dir=base_dir, root_dirs=root_dirs)
except Exception as e:
traceback.print_exc()
print('Exception in tar archiving: %s' % str(e))
if not fail_any_exception:
raise
def _tar_data(root_dirs=None, tar_file=None, base_dir='./'):
if isinstance(root_dirs, str):
root_dirs = [root_dirs]
if tar_file is None:
datetime_str = str(datetime.now()).replace(" ", "_").replace(":", "_")
host_name = os.getenv('HF_HOSTNAME', 'emptyhost')
tar_file = "data_%s_%s.tar.gz" % (datetime_str, host_name)
assert root_dirs is not None
base_path = os.path.dirname(tar_file)
if not os.path.isdir(base_path) and os.path.dirname(tar_file):
base_path = makedirs(base_path, exist_ok=True, tmp_ok=True, use_base=True)
tar_file = os.path.join(base_path, os.path.basename(tar_file))
with tarfile.open(tar_file, "w:gz") as expt_tar:
for root_dir in root_dirs:
if root_dir is None:
continue
for root, d, files in os.walk(root_dir):
for file in files:
file_to_archive = os.path.join(root, file)
assert os.path.exists(file_to_archive)
path_to_archive = os.path.relpath(file_to_archive, base_dir)
expt_tar.add(name=file_to_archive, arcname=path_to_archive)
return tar_file, tar_file
def save_generate_output(prompt=None, output=None, base_model=None, save_dir=None, where_from='unknown where from',
extra_dict={}, error='', sources=[], which_api='', valid_key=None,
h2ogpt_key='', return_dict=False, **kwargs_extra):
if not save_dir:
return
try:
return _save_generate_output(prompt=prompt, output=output, base_model=base_model, save_dir=save_dir,
where_from=where_from, extra_dict=extra_dict, error=error, sources=sources,
which_api=which_api, valid_key=valid_key, h2ogpt_key=h2ogpt_key,
return_dict=return_dict, **kwargs_extra)
except Exception as e:
traceback.print_exc()
print('Exception in saving: %s' % str(e))
def _save_generate_tokens(response_no_refs, extra_dict):
# tokenize at end if need to, so doesn't block generation in multi-generator case
if extra_dict.get('ntokens') is None:
extra_dict['ntokens'] = FakeTokenizer().num_tokens_from_string(str(response_no_refs))
# only do below if didn't already compute ntokens, else assume also computed rate
if extra_dict.get('ntokens') is not None and extra_dict.get('t_generate') is not None:
extra_dict['tokens_persecond'] = extra_dict['ntokens'] / extra_dict['t_generate']
return extra_dict
def _save_generate_output(prompt=None, output=None, base_model=None, save_dir=None, where_from='unknown where from',
extra_dict={}, error='', sources=[], which_api='',
valid_key=None, h2ogpt_key='',
return_dict=False, **kwargs_extra):
"""
Save conversation to .json, row by row.
json_file_path is path to final JSON file. If not in ., then will attempt to make directories.
Appends if file exists
"""
prompt = '<not set>' if prompt is None else prompt
output = '<not set>' if output is None else output
extra_dict = _save_generate_tokens(output, extra_dict)
dict_to_save = dict(prompt=prompt, text=output, time=time.ctime(),
base_model=base_model,
where_from=where_from,
error=error,
sources=sources,
which_api=which_api,
valid_key=valid_key,
h2ogpt_key=h2ogpt_key,
)
dict_to_save.update(extra_dict)
dict_to_save.update(kwargs_extra)
if return_dict:
return dict_to_save
if os.path.exists(save_dir) and not os.path.isdir(save_dir):
raise RuntimeError("save_dir already exists and is not a directory!")
makedirs(save_dir, exist_ok=True) # already should be made, can't change at this point
import json
with filelock.FileLock("%s.lock" % os.path.basename(save_dir)):
# lock logging in case have concurrency
with open(os.path.join(save_dir, "history.json"), "a") as f:
# just add [ at start, and ] at end, and have proper JSON dataset
f.write(
" " + json.dumps(
dict_to_save
) + ",\n"
)
def s3up(filename):
try:
return _s3up(filename)
except Exception as e:
traceback.print_exc()
print('Exception for file %s in s3up: %s' % (filename, str(e)))
return "Failed to upload %s: Error: %s" % (filename, str(e))
def _s3up(filename):
import boto3
aws_access_key_id = os.getenv('AWS_SERVER_PUBLIC_KEY')
aws_secret_access_key = os.getenv('AWS_SERVER_SECRET_KEY')
bucket = os.getenv('AWS_BUCKET')
assert aws_access_key_id, "Set AWS key"
assert aws_secret_access_key, "Set AWS secret"
assert bucket, "Set AWS Bucket"
s3 = boto3.client('s3',
aws_access_key_id=os.getenv('AWS_SERVER_PUBLIC_KEY'),
aws_secret_access_key=os.getenv('AWS_SERVER_SECRET_KEY'),
)
ret = s3.upload_file(
Filename=filename,
Bucket=os.getenv('AWS_BUCKET'),
Key=filename,
)
if ret in [None, '']:
return "Successfully uploaded %s" % filename
def get_githash():
githash = git_hash_unset
try:
githash = subprocess.run(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE).stdout.decode('utf-8')[0:-1]
if githash in ['', None]:
githash = git_hash_unset
except Exception as e:
print("git failed to run: %s" % str(e))
if githash == git_hash_unset:
try:
from version import __version__
githash = __version__
except:
pass
if os.getenv('HARD_ASSERTS'):
assert is_full_git_hash(githash)
return githash
def copy_code(run_id):
"""
copy code to track changes
:param run_id:
:return:
"""
rnd_num = str(random.randint(0, 2 ** 31))
run_id = 'run_' + str(run_id)
os.makedirs(run_id, exist_ok=True)
me_full = os.path.join(pathlib.Path(__file__).parent.resolve(), __file__)
me_file = os.path.basename(__file__)
new_me = os.path.join(run_id, me_file + '_' + get_githash())
if os.path.isfile(new_me):
new_me = os.path.join(run_id, me_file + '_' + get_githash() + '_' + rnd_num)
shutil.copy(me_full, new_me)
else:
shutil.copy(me_full, new_me)
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
class AsyncNullContext(threading.local):
"""No-op async 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 async context manager:
"""
def __init__(self, *args, **kwargs):
pass
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_value, exc_traceback):
await self.finally_act()
async 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 ThreadException(Exception):
pass
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,
async_output=False):
self.bucket = bucket
self.streamer = streamer
self.exc = None
self._return = None
self.async_output = async_output
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:
if self.async_output:
self._return = asyncio.run(self._target(*self._args, **self._kwargs))
else:
self._return = self._target(*self._args, **self._kwargs)
except BaseException as e:
print("thread exception: %s" % str(traceback.format_exc()))
self.bucket.put(sys.exc_info())
self.exc = e
if self.streamer:
print("make stop: %s" % str(traceback.format_exc()), 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 import_matplotlib():
import matplotlib
matplotlib.use('agg')
# KEEP THESE HERE! START
import matplotlib.pyplot as plt
import pandas as pd
# to avoid dlopen deadlock in fork
import pandas.core.computation.expressions as pd_expressions
import pandas.core.algorithms as pd_algorithms
import pandas.core.common as pd_com
import numpy as np
# KEEP THESE HERE! END
def get_sha(value):
return hashlib.md5(str(value).encode('utf-8')).hexdigest()
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 shutil_rmtree(*args, **kwargs):
path = args[0]
assert not os.path.samefile(path,
'/'), "Should not be trying to remove entire root directory: %s" % str(path)
assert not os.path.samefile(path,
'./'), "Should not be trying to remove entire local directory: %s" % str(path)
return shutil.rmtree(*args, **kwargs)
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
def atomic_move_simple(src, dst):
try:
shutil.move(src, dst)
except (shutil.Error, FileExistsError):
pass
remove(src)
def atomic_copy(src="", dst=None, content=None):
my_uuid = uuid.uuid4()
src_tmp = None
if content is not None:
src_tmp = os.path.join('./', str(my_uuid))
with open(src_tmp, 'wt') as f:
f.write(content)
elif src != "":
src_tmp = src + str(my_uuid)
shutil.copy(src, src_tmp)
if src_tmp is not None:
makedirs(os.path.dirname(dst), exist_ok=True)
shutil.move(src_tmp, dst)
remove(src_tmp)
def move_tree(src, dst, include_root=True):
makedirs(dst, exist_ok=True)
if include_root:
shutil.move(src, dst)
else:
for (path, dirs, files) in os.walk(src):
new_path = path.replace(src, dst)
makedirs(new_path, exist_ok=True)
for file in files:
filename = os.path.join(path, file)
new_filename = os.path.join(new_path, file)
# print("%s -> %s" % (filename, new_filename))
try:
# only move if file doesn't already exist
# this ensures use earliest installation if used for pip install race avoidance
if not os.path.isfile(new_filename):
shutil.move(filename, new_filename)
except FileExistsError:
pass
for (path, dirs, files) in os.walk(src):
shutil.rmtree(path, ignore_errors=True)
def copy_tree(src, dst, follow_symlink=False):
makedirs(dst, exist_ok=True)
for (path, dirs, files) in os.walk(src, followlinks=follow_symlink):
new_path = path.replace(src, dst)
makedirs(new_path, exist_ok=True)
for file in files:
filename = os.path.join(path, file)
new_filename = os.path.join(new_path, file)
# print("%s -> %s" % (filename, new_filename))
try:
atomic_copy(filename, new_filename)
except FileNotFoundError:
pass
def download_simple(url, dest=None, overwrite=False, verbose=False):
if dest is None:
dest = os.path.basename(url)
base_path = os.path.dirname(dest)
if base_path: # else local path
base_path = makedirs(base_path, exist_ok=True, tmp_ok=True, use_base=True)
dest = os.path.join(base_path, os.path.basename(dest))
if os.path.isfile(dest):
if not overwrite:
print("Already have %s from url %s, delete file if invalid" % (dest, str(url)), flush=True)
return dest
else:
remove(dest)
if verbose:
print("BEGIN get url %s" % str(url), flush=True)
if url.startswith("file://"):
from requests_file import FileAdapter
s = requests.Session()
s.mount('file://', FileAdapter())
url_data = s.get(url, stream=True)
else:
url_data = requests.get(url, stream=True)
if verbose:
print("GOT url %s" % str(url), flush=True)
if url_data.status_code != requests.codes.ok:
msg = "Cannot get url %s, code: %s, reason: %s" % (
str(url),
str(url_data.status_code),
str(url_data.reason),
)
raise requests.exceptions.RequestException(msg)
url_data.raw.decode_content = True
uuid_tmp = str(uuid.uuid4())[:6]
dest_tmp = dest + "_dl_" + uuid_tmp + ".tmp"
# Sizes in bytes.
total_size = int(url_data.headers.get("content-length", 0))
block_size = 1024
with tqdm(total=total_size, unit="B", unit_scale=True) as progress_bar:
with open(dest_tmp, "wb") as file:
for data in url_data.iter_content(block_size):
progress_bar.update(len(data))
file.write(data)
if total_size != 0 and progress_bar.n != total_size:
raise RuntimeError("Could not download file")
atomic_move_simple(dest_tmp, dest)
if verbose:
print("DONE url %s" % str(url), flush=True)
return dest
def download(url, dest=None, dest_path=None):
if dest_path is not None:
dest = os.path.join(dest_path, os.path.basename(url))
if os.path.isfile(dest):
print("already downloaded %s -> %s" % (url, dest))
return dest
elif dest is not None:
if os.path.exists(dest):
print("already downloaded %s -> %s" % (url, dest))
return dest
else:
uuid_tmp = "dl2_" + str(uuid.uuid4())[:6]
dest = uuid_tmp + os.path.basename(url)
print("downloading %s to %s" % (url, dest))
if url.startswith("file://"):
from requests_file import FileAdapter
s = requests.Session()
s.mount('file://', FileAdapter())
url_data = s.get(url, stream=True)
else:
url_data = requests.get(url, stream=True)
if url_data.status_code != requests.codes.ok:
msg = "Cannot get url %s, code: %s, reason: %s" % (
str(url), str(url_data.status_code), str(url_data.reason))
raise requests.exceptions.RequestException(msg)
url_data.raw.decode_content = True
dirname = os.path.dirname(dest)
if dirname != "" and not os.path.isdir(dirname):
base_path = os.path.dirname(dest)
base_path = makedirs(base_path, exist_ok=True, tmp_ok=True, use_base=True)
dest = os.path.join(base_path, os.path.basename(dest))
uuid_tmp = "dl3_" + str(uuid.uuid4())[:6]
dest_tmp = dest + "_" + uuid_tmp + ".tmp"
with open(dest_tmp, 'wb') as f:
shutil.copyfileobj(url_data.raw, f)
try:
shutil.move(dest_tmp, dest)
except FileExistsError:
pass
remove(dest_tmp)
return dest
def get_doc(x):
return x.page_content
def get_source(x):
return x.metadata.get('source', "UNKNOWN SOURCE")
def markdown_to_html(content):
import markdown
# Create a Markdown object
markdowner = markdown.Markdown()
# Convert the Markdown block to HTML
try:
html = markdowner.reset().convert(content)
except Exception as e:
# FIXME:
print("Invalid conversion of markdown to html: %s\n\n%s" % (content, str(e)))
html = content
return html
def is_markdown(string):
"""Returns True if the string is markdown, False otherwise."""
# Check for the presence of double square brackets
if re.search(r'\[\[.+?\]\]', string):
return True
# Check for the presence of angle brackets
if re.search(r'<.+?>', string):
return False
# If neither of the above patterns are found, assume the string is markdown
return True
def get_accordion_named(content, title, font_size=8):
# content = content.replace('\n', '<br>')
if is_markdown(content):
content = markdown_to_html(content)
return f"""<details><summary><font size="{font_size}">{title}</font></summary><font size="{font_size}">{content}</font></details>"""
def hyde_titles(level):
if level == 0:
title = "HYDE 0: LLM"
elif level == 1:
title = "HYDE 1: Prompt+LLM embedding"
elif level == 2:
title = "HYDE 2: Prompt+LLM+HYDE 1 embedding"
elif level == 3:
title = "HYDE 3: Prompt+LLM+HYDE 1&2 embedding"
else:
title = "HYDE 4: Prompt+LLM+HYDE 1&2&3 embedding"
return title
def get_accordion(x, font_size=2, head_acc=50):
title = x.page_content[:head_acc].replace("\n", ' ').replace("<br>", ' ').replace("<p>", ' ').replace("\r", ' ')
content = x.page_content
return f"""<details><summary><font size="{font_size}">{title}</font></summary><font size="{font_size}">{content}</font></details>"""
def get_url(x, from_str=False, short_name=False, font_size=2):
if not from_str:
source = x.metadata['source']
else:
source = x
if short_name:
source_name = get_short_name(source)
else:
source_name = source
if source.startswith('http://') or source.startswith('https://'):
return """<font size="%s"><a href="%s" target="_blank" rel="noopener noreferrer">%s</a></font>""" % (
font_size, source, source_name)
elif '<a href=' not in source:
return """<font size="%s"><a href="file/%s" target="_blank" rel="noopener noreferrer">%s</a></font>""" % (
font_size, source, source_name)
else:
# already filled
return source
def get_short_name(name, maxl=50):
if name is None:
return ''
length = len(name)
if length > maxl:
allow_length = maxl - 3
half_allowed = max(1, int(allow_length / 2))
name = name[0:half_allowed] + "..." + name[length - half_allowed:length]
return name
def cuda_vis_check(total_gpus):
"""Helper function to count GPUs by environment variable
Stolen from Jon's h2o4gpu utils
"""
cudavis = os.getenv("CUDA_VISIBLE_DEVICES")
which_gpus = []
if cudavis is not None:
# prune away white-space, non-numerics,
# except commas for simple checking
cudavis = "".join(cudavis.split())
import re
cudavis = re.sub("[^0-9,]", "", cudavis)
lencudavis = len(cudavis)
if lencudavis == 0:
total_gpus = 0
else:
total_gpus = min(
total_gpus,
os.getenv("CUDA_VISIBLE_DEVICES").count(",") + 1)
which_gpus = os.getenv("CUDA_VISIBLE_DEVICES").split(",")
which_gpus = [int(x) for x in which_gpus]
else:
which_gpus = list(range(0, total_gpus))
return total_gpus, which_gpus
def get_ngpus_vis(raise_if_exception=True):
ngpus_vis1 = None
shell = False
if shell:
cmd = "nvidia-smi -L 2> /dev/null"
else:
cmd = ["nvidia-smi", "-L"]
try:
timeout = 5 * 3
o = subprocess.check_output(cmd, shell=shell, timeout=timeout)
lines = o.decode("utf-8").splitlines()
ngpus_vis1 = 0
for line in lines:
if 'Failed to initialize NVML' not in line:
ngpus_vis1 += 1
except (FileNotFoundError, subprocess.CalledProcessError, OSError):
# GPU systems might not have nvidia-smi, so can't fail
pass
except subprocess.TimeoutExpired as e:
print('Failed get_ngpus_vis: %s' % str(e))
if raise_if_exception:
raise
if ngpus_vis1 is None:
import torch
if get_device() == 'cuda':
ngpus_vis1 = torch.cuda.device_count() if torch.cuda.is_available() else 0
else:
ngpus_vis1 = 0
ngpus_vis1, which_gpus = cuda_vis_check(ngpus_vis1)
return ngpus_vis1
def get_mem_gpus(raise_if_exception=True, ngpus=None):
totalmem_gpus1 = 0
usedmem_gpus1 = 0
freemem_gpus1 = 0
if ngpus == 0:
return totalmem_gpus1, usedmem_gpus1, freemem_gpus1
try:
cmd = "nvidia-smi -q 2> /dev/null | grep -A 3 'FB Memory Usage'"
o = subprocess.check_output(cmd, shell=True, timeout=15)
lines = o.decode("utf-8").splitlines()
for line in lines:
if 'Total' in line:
totalmem_gpus1 += int(line.split()[2]) * 1024 ** 2
if 'Used' in line:
usedmem_gpus1 += int(line.split()[2]) * 1024 ** 2
if 'Free' in line:
freemem_gpus1 += int(line.split()[2]) * 1024 ** 2
except (FileNotFoundError, subprocess.CalledProcessError, OSError):
# GPU systems might not have nvidia-smi, so can't fail
pass
except subprocess.TimeoutExpired as e:
print('Failed get_mem_gpus: %s' % str(e))
if raise_if_exception: