Skip to content

Instantly share code, notes, and snippets.

@vadimkantorov
Last active December 10, 2022 17:38
Show Gist options
  • Save vadimkantorov/f830d249ee3b8613ac422bc6bcaba149 to your computer and use it in GitHub Desktop.
Save vadimkantorov/f830d249ee3b8613ac422bc6bcaba149 to your computer and use it in GitHub Desktop.
Config proxy file to simplify porting of detectron2-like codebases
class ConfigProxy:
def __init__(self, cfgobj = None, ConfigProxyPath = '', ConfigProxyRoot = '', ConfigProxySep = '__', **cfgdict):
self.cfgobj = cfgobj
self.cfgdict = cfgdict
self.ConfigProxyRoot = ConfigProxyRoot
self.ConfigProxyPath = ConfigProxyPath
self.ConfigProxySep = ConfigProxySep
def __getattr__(self, key):
ConfigProxyPath = self.ConfigProxyPath + self.ConfigProxySep + key if self.ConfigProxyPath else key
ConfigProxyPathWithRoot = self.ConfigProxyRoot + self.ConfigProxySep + ConfigProxyPath if self.ConfigProxyRoot else ConfigProxyPath
if ConfigProxyPathWithRoot in self.cfgdict:
return self.cfgdict[ConfigProxyPathWithRoot]
path = ConfigProxyPath.split(self.ConfigProxySep)
cfgobj = self.cfgobj
for i in range(len(path)):
if hasattr(cfgobj, path[i]):
cfgobj = getattr(cfgobj, path[i])
if i == len(path) - 1:
return cfgobj
else:
break
return ConfigProxy(cfgobj = self.cfgobj, ConfigProxyPath = ConfigProxyPath, ConfigProxySep = self.ConfigProxySep, ConfigProxyRoot = self.ConfigProxyRoot, **self.cfgdict)
if __name__ == '__main__':
# code found in detectron2-based codebaes
# ConfigProxy can be used for porting to less intrusive style
class MyModel:
def __init__(self, cfg__MODEL__DiffusionDet__NUM_CLASSES = 0, cfg = None, **config):
cfg = ConfigProxy(cfg, ConfigProxyRoot = 'cfg', ConfigProxySep = '__', cfg__MODEL__DiffusionDet__NUM_CLASSES = cfg__MODEL__DiffusionDet__NUM_CLASSES, **config)
print(cfg.MODEL.DiffusionDet.NUM_CLASSES)
print(cfg.MODEL.DiffusionDet.DROPOUT)
print(cfg.MODEL.DiffusionDet.ACTIVATION)
# can support either config obj
class config:
class MODEL:
class DiffusionDet:
DROPOUT = 0.5
NUM_CLASSES = 20
ACTIVATION = 'relu'
MyModel(cfg = config)
# 20
# 0.5
# relu
# or dicts. can't support both soundly because at getattr time we can't continue resolve dicts if a config object resolves first
config = dict(cfg__MODEL__DiffusionDet__NUM_CLASSES = 20, cfg__MODEL__DiffusionDet__ACTIVATION = 'relu')
MyModel(**config)
# 20
# <__main__.ConfigProxy object at 0x7f6ab796fd00>
# relu
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment