Download playground/Abbie-b200/dataloader/utils.py from jasonfan/devboxbackup: direct link, hf CLI and curl.
- Browser
- Download file 9.74 kB
-
https://huggingface.co/datasets/jasonfan/devboxbackup/resolve/main/playground/Abbie-b200/dataloader/utils.py
- Command line
-
hf download hf://datasets/jasonfan/devboxbackup/playground/Abbie-b200/dataloader/utils.py
-
curl -L -o utils.py https://huggingface.co/datasets/jasonfan/devboxbackup/resolve/main/playground/Abbie-b200/dataloader/utils.py
9.74 kB
| import os | |
| import time | |
| import importlib | |
| from typing import List | |
| import torch | |
| import torch.distributed as dist | |
| import json | |
| import multiprocessing as mp | |
| from types import ModuleType | |
| import pyarrow.fs as pf | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| from dataloader.hdfs_io import hisdir, hlist_files | |
| def is_bitwise_ckpt_enable(): | |
| return os.getenv("SAHARA_ENABLE_BITWISE_CKPT", '1') == '1' | |
| _HADOOP_COMMAND_TEMPLATE = 'hadoop fs {command}' | |
| NATIVE_LIBHDFS_FOLDER = "/opt/tiger/native_libhdfs" | |
| if os.path.isdir(NATIVE_LIBHDFS_FOLDER): | |
| NATIVE_HDFS_FOLDER = NATIVE_LIBHDFS_FOLDER | |
| else: | |
| NATIVE_HDFS_FOLDER = os.path.realpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), | |
| "../3rdparty/native_dfs_client")) | |
| try: | |
| with open('/etc/os-release', 'r') as f: | |
| os_release = f.read() | |
| if 'VERSION_ID="11' in os_release: | |
| NATIVE_HDFS_FOLDER = os.path.realpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), | |
| "../3rdparty/native_dfs_client_debian11")) | |
| except Exception as e: | |
| print(f"unable to update NATIVE_HDFS_FOLDER with exception: {e}. use default.") | |
| NATIVE_HDFS_PATH = os.getenv("NATIVE_HDFS_PATH", NATIVE_HDFS_FOLDER) | |
| if os.getenv("CRUISE_LOCAL_CACHE_DIR", None): | |
| CRUISE_LOADER_WS = os.getenv("CRUISE_LOCAL_CACHE_DIR") | |
| elif os.getenv("ARNOLD_TRIAL_ID", None): | |
| CRUISE_LOADER_WS = "/opt/tiger/cruise_loader_ws" | |
| else: | |
| CRUISE_LOADER_WS = None | |
| def get_fname_from_url(url): | |
| if CRUISE_LOADER_WS is None: | |
| return None | |
| # try to create work space | |
| if not os.path.exists(CRUISE_LOADER_WS): | |
| try: | |
| os.makedirs(CRUISE_LOADER_WS) | |
| except: | |
| pass | |
| return "{}/{}".format(CRUISE_LOADER_WS, url.split(":")[-1].replace("/", "_")) | |
| def acquire_file_lock(url): | |
| lock_file = url + '.lock_file' | |
| try: | |
| # Open a file | |
| fd = os.open(lock_file, os.O_CREAT | os.O_EXCL) | |
| # Close opened file | |
| os.close(fd) | |
| return True | |
| except: | |
| return False | |
| def get_parquet_row_group_info_from_meta(parquet_file): | |
| meta = parquet_file.metadata | |
| rg = meta.num_row_groups | |
| group_sizes = [meta.row_group(i).num_rows for i in range(rg)] | |
| return group_sizes | |
| def use_native_hdfs(): | |
| return os.path.exists(NATIVE_HDFS_PATH) and int(os.getenv("USE_NATIVE_HDFS_CLIENT", "1")) > 0 | |
| def set_native_hdfs_security_permission(): | |
| os.environ["INFSEC_HADOOP_ENABLED"] = "1" | |
| os.environ["INFSEC_HADDOP_ENABLED"] = "1" | |
| def native_hdfs_check(): | |
| if use_native_hdfs(): | |
| set_native_hdfs_security_permission() | |
| def _get_hdfs_command(command): | |
| """Return hadoop fs command""" | |
| return _HADOOP_COMMAND_TEMPLATE.format(command=command) | |
| def get_hdfs_host(): | |
| arnold_base_dir = os.environ.get('ARNOLD_BASE_DIR', '') | |
| if arnold_base_dir.startswith('hdfs://harunava'): | |
| return 'hdfs://harunava' | |
| elif arnold_base_dir.startswith('hdfs://harunaoci'): | |
| return 'hdfs://harunaoci' | |
| elif arnold_base_dir.startswith('hdfs://harunacompass'): | |
| return 'hdfs://harunacompass' | |
| elif arnold_base_dir.startswith('hdfs://haruna'): | |
| return 'hdfs://haruna' | |
| elif os.environ.get('ARNOLD_WORKSPACE_CLUSTER_NAME') == 'candy-maliva': | |
| return 'hdfs://harunava' | |
| try: | |
| import xml.etree.ElementTree as ET | |
| tree = ET.parse('/opt/tiger/yarn_deploy/hadoop/conf/core-site.xml') | |
| root = tree.getroot() | |
| for child in root: | |
| if child.tag == 'property' and child[0].text == 'fs.defaultFS': | |
| return child[1].text | |
| except: | |
| return 'hdfs://haruna' | |
| def get_hdfs_block_size(): | |
| try: | |
| import xml.etree.ElementTree as ET | |
| tree = ET.parse('/opt/tiger/yarn_deploy/hadoop/conf/hdfs-site.xml') | |
| root = tree.getroot() | |
| for child in root: | |
| if child.tag == 'property' and child[0].text == 'dfs.block.size': | |
| return int(child[1].text) | |
| except: | |
| pass | |
| return 134217728 | |
| def get_hdfs_extra_conf(): | |
| hdfs_celer = os.environ.get("ARNOLD_HDFS_CELER", "false") | |
| hdfs_celer = hdfs_celer.lower() in ('y', 'yes', 't', 'true', 'on', '1') | |
| if hdfs_celer: | |
| try: | |
| import xml.etree.ElementTree as ET | |
| tree = ET.parse("/opt/tiger/arnold/hdfs_client/conf/celer.xml") | |
| conf = {} | |
| for prop in tree.getroot(): | |
| if prop.tag != "property": | |
| continue | |
| key, val = None, None | |
| for elem in prop: | |
| if elem.tag == "name": | |
| key = elem.text | |
| elif elem.tag == "value": | |
| val = elem.text | |
| if key is None or val is None: | |
| continue | |
| conf[key] = val | |
| return conf | |
| except Exception as e: | |
| print(f"fail to parse celer conf: {e}. nothing changed.") | |
| pass | |
| return None | |
| def init_arrow_hdfs_fs(): | |
| return pf.HadoopFileSystem( | |
| host=get_hdfs_host(), | |
| port=0, | |
| buffer_size=get_hdfs_block_size(), | |
| extra_conf=get_hdfs_extra_conf(), | |
| ) | |
| def get_parquet_file_handle(url): | |
| pq = LazyLoader('pq', globals(), 'pyarrow.parquet') | |
| pf = LazyLoader('pf', globals(), 'pyarrow.fs') | |
| if url.startswith("hdfs"): | |
| fs = init_arrow_hdfs_fs() | |
| f = fs.open_input_file(url) | |
| else: | |
| f = open(url, 'rb') | |
| fs = pf.LocalFileSystem() | |
| parquet_file = pq.ParquetFile(f) | |
| return parquet_file, fs, f | |
| # process_file: read parquet metadata | |
| def process_file(file_path: str): | |
| pq = LazyLoader('pq', globals(), 'pyarrow.parquet') | |
| try: | |
| num_rows = pq.read_metadata(file_path).num_rows | |
| return (file_path, num_rows) | |
| except Exception as e: | |
| print(f"Error processing {file_path}: {e}") | |
| return None | |
| def build_dataset(total_files: List[str], num_worker: int = 1): | |
| data_map = {} | |
| data_list = [] | |
| if dist.get_rank() != 0: | |
| print("Not rank 0, skipping query to prevent overwhelming HDFS hit.") | |
| data_list = [None for i in total_files] | |
| else: | |
| print(f"Total files num: {len(total_files)}") | |
| with ThreadPoolExecutor(max_workers=num_worker) as executor: | |
| futures = {executor.submit(process_file, file): file for file in total_files} | |
| for future in as_completed(futures): | |
| result = future.result() | |
| if result: | |
| file_name_i, num_rows = result | |
| file_name = file_name_i.split('/')[-1] | |
| data_map[file_name] = num_rows | |
| print("Rank 0 finished query file length ..") | |
| data_list = [v for k, v in data_map.items()] | |
| dist.broadcast_object_list(data_list, src=0) | |
| return data_list | |
| def get_single_parquet_length(url): | |
| if url.startswith('hdfs') and mp.current_process().name == 'MainProcess': | |
| print('use pyarrow fs hdfs api in main process may have fork issue!') | |
| parquet_file, _, handle = get_parquet_file_handle(url) | |
| rows = parquet_file.metadata.num_rows | |
| # close file handle | |
| handle.close() | |
| return rows | |
| def get_worker_info(): | |
| local_worker_id = 0 | |
| local_num_workers = 1 | |
| worker_info = torch.utils.data.get_worker_info() | |
| if worker_info is not None: | |
| local_worker_id = worker_info.id | |
| local_num_workers = worker_info.num_workers | |
| return local_worker_id, local_num_workers | |
| class LazyLoader(ModuleType): | |
| """Lazily import a module, mainly to avoid pulling in large dependencies. | |
| `contrib`, and `ffmpeg` are examples of modules that are large and not always | |
| needed, and this allows them to only be loaded when they are used. | |
| """ | |
| # The lint error here is incorrect. | |
| def __init__(self, local_name, parent_module_globals, name): # pylint: disable=super-on-old-class | |
| self._local_name = local_name | |
| self._parent_module_globals = parent_module_globals | |
| super(LazyLoader, self).__init__(name) | |
| def _load(self): | |
| # Import the target module and insert it into the parent's namespace | |
| module = importlib.import_module(self.__name__) | |
| self._parent_module_globals[self._local_name] = module | |
| # Update this object's dict so that if someone keeps a reference to the | |
| # LazyLoader, lookups are efficient (__getattr__ is only called on lookups | |
| # that fail). | |
| self.__dict__.update(module.__dict__) | |
| return module | |
| def __getattr__(self, item): | |
| module = self._load() | |
| return getattr(module, item) | |
| def __dir__(self): | |
| module = self._load() | |
| return dir(module) | |
| class PerfTimer: | |
| """Perf timer for a region. If the duration is longer than the | |
| threshold, [PERF WARN] will be printed | |
| Args: | |
| name (str): the name of the current region | |
| threshold (float): the warning threshold in seconds | |
| verbose (bool): whether to log when the duration is under the threshold | |
| """ | |
| def __init__(self, name: str, threshold: float = 10, verbose: bool = True): | |
| self.t0 = 0 | |
| self.t1 = 0 | |
| self.name = name | |
| self.threshold = threshold | |
| self.verbose = verbose | |
| self.logged = False | |
| self.above_threshold = False | |
| def __enter__(self): | |
| self.t0 = time.time() | |
| def __exit__(self, exc_type, exc_value, exc_tb): | |
| self.t1 = time.time() | |
| duration = self.t1 - self.t0 | |
| msg = '' | |
| if duration > self.threshold: | |
| msg += '[PERF WARN] ' | |
| self.above_threshold = True | |