Spaces:
Runtime error
Runtime error
Delete clipseg/general_utils.py
Browse files- clipseg/general_utils.py +0 -272
clipseg/general_utils.py
DELETED
|
@@ -1,272 +0,0 @@
|
|
| 1 |
-
import json
|
| 2 |
-
import inspect
|
| 3 |
-
import torch
|
| 4 |
-
import os
|
| 5 |
-
import sys
|
| 6 |
-
import yaml
|
| 7 |
-
from shutil import copy, copytree
|
| 8 |
-
from os.path import join, dirname, realpath, expanduser, isfile, isdir, basename
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
class Logger(object):
|
| 12 |
-
|
| 13 |
-
def __getattr__(self, k):
|
| 14 |
-
return print
|
| 15 |
-
|
| 16 |
-
log = Logger()
|
| 17 |
-
|
| 18 |
-
def training_config_from_cli_args():
|
| 19 |
-
experiment_name = sys.argv[1]
|
| 20 |
-
experiment_id = int(sys.argv[2])
|
| 21 |
-
|
| 22 |
-
yaml_config = yaml.load(open(f'experiments/{experiment_name}'), Loader=yaml.SafeLoader)
|
| 23 |
-
|
| 24 |
-
config = yaml_config['configuration']
|
| 25 |
-
config = {**config, **yaml_config['individual_configurations'][experiment_id]}
|
| 26 |
-
config = AttributeDict(config)
|
| 27 |
-
return config
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
def score_config_from_cli_args():
|
| 31 |
-
experiment_name = sys.argv[1]
|
| 32 |
-
experiment_id = int(sys.argv[2])
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
yaml_config = yaml.load(open(f'experiments/{experiment_name}'), Loader=yaml.SafeLoader)
|
| 36 |
-
|
| 37 |
-
config = yaml_config['test_configuration_common']
|
| 38 |
-
|
| 39 |
-
if type(yaml_config['test_configuration']) == list:
|
| 40 |
-
test_id = int(sys.argv[3])
|
| 41 |
-
config = {**config, **yaml_config['test_configuration'][test_id]}
|
| 42 |
-
else:
|
| 43 |
-
config = {**config, **yaml_config['test_configuration']}
|
| 44 |
-
|
| 45 |
-
if 'test_configuration' in yaml_config['individual_configurations'][experiment_id]:
|
| 46 |
-
config = {**config, **yaml_config['individual_configurations'][experiment_id]['test_configuration']}
|
| 47 |
-
|
| 48 |
-
train_checkpoint_id = yaml_config['individual_configurations'][experiment_id]['name']
|
| 49 |
-
|
| 50 |
-
config = AttributeDict(config)
|
| 51 |
-
return config, train_checkpoint_id
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
def get_from_repository(local_name, repo_files, integrity_check=None, repo_dir='~/dataset_repository',
|
| 55 |
-
local_dir='~/datasets'):
|
| 56 |
-
""" copies files from repository to local folder.
|
| 57 |
-
|
| 58 |
-
repo_files: list of filenames or list of tuples [filename, target path]
|
| 59 |
-
|
| 60 |
-
e.g. get_from_repository('MyDataset', [['data/dataset1.tar', 'other/path/ds03.tar'])
|
| 61 |
-
will create a folder 'MyDataset' in local_dir, and extract the content of
|
| 62 |
-
'<repo_dir>/data/dataset1.tar' to <local_dir>/MyDataset/other/path.
|
| 63 |
-
"""
|
| 64 |
-
|
| 65 |
-
local_dir = realpath(join(expanduser(local_dir), local_name))
|
| 66 |
-
|
| 67 |
-
dataset_exists = True
|
| 68 |
-
|
| 69 |
-
# check if folder is available
|
| 70 |
-
if not isdir(local_dir):
|
| 71 |
-
dataset_exists = False
|
| 72 |
-
|
| 73 |
-
if integrity_check is not None:
|
| 74 |
-
try:
|
| 75 |
-
integrity_ok = integrity_check(local_dir)
|
| 76 |
-
except BaseException:
|
| 77 |
-
integrity_ok = False
|
| 78 |
-
|
| 79 |
-
if integrity_ok:
|
| 80 |
-
log.hint('Passed custom integrity check')
|
| 81 |
-
else:
|
| 82 |
-
log.hint('Custom integrity check failed')
|
| 83 |
-
|
| 84 |
-
dataset_exists = dataset_exists and integrity_ok
|
| 85 |
-
|
| 86 |
-
if not dataset_exists:
|
| 87 |
-
|
| 88 |
-
repo_dir = realpath(expanduser(repo_dir))
|
| 89 |
-
|
| 90 |
-
for i, filename in enumerate(repo_files):
|
| 91 |
-
|
| 92 |
-
if type(filename) == str:
|
| 93 |
-
origin, target = filename, filename
|
| 94 |
-
archive_target = join(local_dir, basename(origin))
|
| 95 |
-
extract_target = join(local_dir)
|
| 96 |
-
else:
|
| 97 |
-
origin, target = filename
|
| 98 |
-
archive_target = join(local_dir, dirname(target), basename(origin))
|
| 99 |
-
extract_target = join(local_dir, dirname(target))
|
| 100 |
-
|
| 101 |
-
archive_origin = join(repo_dir, origin)
|
| 102 |
-
|
| 103 |
-
log.hint(f'copy: {archive_origin} to {archive_target}')
|
| 104 |
-
|
| 105 |
-
# make sure the path exists
|
| 106 |
-
os.makedirs(dirname(archive_target), exist_ok=True)
|
| 107 |
-
|
| 108 |
-
if os.path.isfile(archive_target):
|
| 109 |
-
# only copy if size differs
|
| 110 |
-
if os.path.getsize(archive_target) != os.path.getsize(archive_origin):
|
| 111 |
-
log.hint(f'file exists but filesize differs: target {os.path.getsize(archive_target)} vs. origin {os.path.getsize(archive_origin)}')
|
| 112 |
-
copy(archive_origin, archive_target)
|
| 113 |
-
else:
|
| 114 |
-
copy(archive_origin, archive_target)
|
| 115 |
-
|
| 116 |
-
extract_archive(archive_target, extract_target, noarchive_ok=True)
|
| 117 |
-
|
| 118 |
-
# concurrent processes might have deleted the file
|
| 119 |
-
if os.path.isfile(archive_target):
|
| 120 |
-
os.remove(archive_target)
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
def extract_archive(filename, target_folder=None, noarchive_ok=False):
|
| 124 |
-
from subprocess import run, PIPE
|
| 125 |
-
|
| 126 |
-
if filename.endswith('.tgz') or filename.endswith('.tar'):
|
| 127 |
-
command = f'tar -xf {filename}'
|
| 128 |
-
command += f' -C {target_folder}' if target_folder is not None else ''
|
| 129 |
-
elif filename.endswith('.tar.gz'):
|
| 130 |
-
command = f'tar -xzf {filename}'
|
| 131 |
-
command += f' -C {target_folder}' if target_folder is not None else ''
|
| 132 |
-
elif filename.endswith('zip'):
|
| 133 |
-
command = f'unzip {filename}'
|
| 134 |
-
command += f' -d {target_folder}' if target_folder is not None else ''
|
| 135 |
-
else:
|
| 136 |
-
if noarchive_ok:
|
| 137 |
-
return
|
| 138 |
-
else:
|
| 139 |
-
raise ValueError(f'unsuppored file ending of {filename}')
|
| 140 |
-
|
| 141 |
-
log.hint(command)
|
| 142 |
-
result = run(command.split(), stdout=PIPE, stderr=PIPE)
|
| 143 |
-
if result.returncode != 0:
|
| 144 |
-
print(result.stdout, result.stderr)
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
class AttributeDict(dict):
|
| 148 |
-
"""
|
| 149 |
-
An extended dictionary that allows access to elements as atttributes and counts
|
| 150 |
-
these accesses. This way, we know if some attributes were never used.
|
| 151 |
-
"""
|
| 152 |
-
|
| 153 |
-
def __init__(self, *args, **kwargs):
|
| 154 |
-
from collections import Counter
|
| 155 |
-
super().__init__(*args, **kwargs)
|
| 156 |
-
self.__dict__['counter'] = Counter()
|
| 157 |
-
|
| 158 |
-
def __getitem__(self, k):
|
| 159 |
-
self.__dict__['counter'][k] += 1
|
| 160 |
-
return super().__getitem__(k)
|
| 161 |
-
|
| 162 |
-
def __getattr__(self, k):
|
| 163 |
-
self.__dict__['counter'][k] += 1
|
| 164 |
-
return super().get(k)
|
| 165 |
-
|
| 166 |
-
def __setattr__(self, k, v):
|
| 167 |
-
return super().__setitem__(k, v)
|
| 168 |
-
|
| 169 |
-
def __delattr__(self, k, v):
|
| 170 |
-
return super().__delitem__(k, v)
|
| 171 |
-
|
| 172 |
-
def unused_keys(self, exceptions=()):
|
| 173 |
-
return [k for k in super().keys() if self.__dict__['counter'][k] == 0 and k not in exceptions]
|
| 174 |
-
|
| 175 |
-
def assume_no_unused_keys(self, exceptions=()):
|
| 176 |
-
if len(self.unused_keys(exceptions=exceptions)) > 0:
|
| 177 |
-
log.warning('Unused keys:', self.unused_keys(exceptions=exceptions))
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
def get_attribute(name):
|
| 181 |
-
import importlib
|
| 182 |
-
|
| 183 |
-
if name is None:
|
| 184 |
-
raise ValueError('The provided attribute is None')
|
| 185 |
-
|
| 186 |
-
name_split = name.split('.')
|
| 187 |
-
mod = importlib.import_module('.'.join(name_split[:-1]))
|
| 188 |
-
return getattr(mod, name_split[-1])
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
def filter_args(input_args, default_args):
|
| 193 |
-
|
| 194 |
-
updated_args = {k: input_args[k] if k in input_args else v for k, v in default_args.items()}
|
| 195 |
-
used_args = {k: v for k, v in input_args.items() if k in default_args}
|
| 196 |
-
unused_args = {k: v for k, v in input_args.items() if k not in default_args}
|
| 197 |
-
|
| 198 |
-
return AttributeDict(updated_args), AttributeDict(used_args), AttributeDict(unused_args)
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
def load_model(checkpoint_id, weights_file=None, strict=True, model_args='from_config', with_config=False):
|
| 202 |
-
|
| 203 |
-
config = json.load(open(join('logs', checkpoint_id, 'config.json')))
|
| 204 |
-
|
| 205 |
-
if model_args != 'from_config' and type(model_args) != dict:
|
| 206 |
-
raise ValueError('model_args must either be "from_config" or a dictionary of values')
|
| 207 |
-
|
| 208 |
-
model_cls = get_attribute(config['model'])
|
| 209 |
-
|
| 210 |
-
# load model
|
| 211 |
-
if model_args == 'from_config':
|
| 212 |
-
_, model_args, _ = filter_args(config, inspect.signature(model_cls).parameters)
|
| 213 |
-
|
| 214 |
-
model = model_cls(**model_args)
|
| 215 |
-
|
| 216 |
-
if weights_file is None:
|
| 217 |
-
weights_file = realpath(join('logs', checkpoint_id, 'weights.pth'))
|
| 218 |
-
else:
|
| 219 |
-
weights_file = realpath(join('logs', checkpoint_id, weights_file))
|
| 220 |
-
|
| 221 |
-
if isfile(weights_file):
|
| 222 |
-
weights = torch.load(weights_file)
|
| 223 |
-
for _, w in weights.items():
|
| 224 |
-
assert not torch.any(torch.isnan(w)), 'weights contain NaNs'
|
| 225 |
-
model.load_state_dict(weights, strict=strict)
|
| 226 |
-
else:
|
| 227 |
-
raise FileNotFoundError(f'model checkpoint {weights_file} was not found')
|
| 228 |
-
|
| 229 |
-
if with_config:
|
| 230 |
-
return model, config
|
| 231 |
-
|
| 232 |
-
return model
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
class TrainingLogger(object):
|
| 236 |
-
|
| 237 |
-
def __init__(self, model, log_dir, config=None, *args):
|
| 238 |
-
super().__init__()
|
| 239 |
-
self.model = model
|
| 240 |
-
self.base_path = join(f'logs/{log_dir}') if log_dir is not None else None
|
| 241 |
-
|
| 242 |
-
os.makedirs('logs/', exist_ok=True)
|
| 243 |
-
os.makedirs(self.base_path, exist_ok=True)
|
| 244 |
-
|
| 245 |
-
if config is not None:
|
| 246 |
-
json.dump(config, open(join(self.base_path, 'config.json'), 'w'))
|
| 247 |
-
|
| 248 |
-
def iter(self, i, **kwargs):
|
| 249 |
-
if i % 100 == 0 and 'loss' in kwargs:
|
| 250 |
-
loss = kwargs['loss']
|
| 251 |
-
print(f'iteration {i}: loss {loss:.4f}')
|
| 252 |
-
|
| 253 |
-
def save_weights(self, only_trainable=False, weight_file='weights.pth'):
|
| 254 |
-
if self.model is None:
|
| 255 |
-
raise AttributeError('You need to provide a model reference when initializing TrainingTracker to save weights.')
|
| 256 |
-
|
| 257 |
-
weights_path = join(self.base_path, weight_file)
|
| 258 |
-
|
| 259 |
-
weight_dict = self.model.state_dict()
|
| 260 |
-
|
| 261 |
-
if only_trainable:
|
| 262 |
-
weight_dict = {n: weight_dict[n] for n, p in self.model.named_parameters() if p.requires_grad}
|
| 263 |
-
|
| 264 |
-
torch.save(weight_dict, weights_path)
|
| 265 |
-
log.info(f'Saved weights to {weights_path}')
|
| 266 |
-
|
| 267 |
-
def __enter__(self):
|
| 268 |
-
return self
|
| 269 |
-
|
| 270 |
-
def __exit__(self, type, value, traceback):
|
| 271 |
-
""" automatically stop processes if used in a context manager """
|
| 272 |
-
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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