File size: 9,743 Bytes
f0d6538 | 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 | 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
|