Elffuss BraidHub

kikocis/SpatialLM public

main · 11.5 KiBRawPermalink
1# Copyright (c) OpenMMLab. All rights reserved.
2
3"""
4Reference: PointCept
5
6@misc{pointcept2023,
7 title={Pointcept: A Codebase for Point Cloud Perception Research},
8 author={Pointcept Contributors},
9 year={2023}
10}
11"""
12
13import inspect
14import warnings
15from collections import abc
16from functools import partial
17
18
19def is_seq_of(seq, expected_type, seq_type=None):
20 """Check whether it is a sequence of some type.
21
22 Args:
23 seq (Sequence): The sequence to be checked.
24 expected_type (type): Expected type of sequence items.
25 seq_type (type, optional): Expected sequence type.
26
27 Returns:
28 bool: Whether the sequence is valid.
29 """
30 if seq_type is None:
31 exp_seq_type = abc.Sequence
32 else:
33 assert isinstance(seq_type, type)
34 exp_seq_type = seq_type
35 if not isinstance(seq, exp_seq_type):
36 return False
37 for item in seq:
38 if not isinstance(item, expected_type):
39 return False
40 return True
41
42
43def build_from_cfg(cfg, registry, default_args=None):
44 """Build a module from configs dict.
45
46 Args:
47 cfg (dict): Config dict. It should at least contain the key "type".
48 registry (:obj:`Registry`): The registry to search the type from.
49 default_args (dict, optional): Default initialization arguments.
50
51 Returns:
52 object: The constructed object.
53 """
54 if not isinstance(cfg, dict):
55 raise TypeError(f"cfg must be a dict, but got {type(cfg)}")
56 if "type" not in cfg:
57 if default_args is None or "type" not in default_args:
58 raise KeyError(
59 '`cfg` or `default_args` must contain the key "type", '
60 f"but got {cfg}\n{default_args}"
61 )
62 if not isinstance(registry, Registry):
63 raise TypeError(
64 "registry must be an mmcv.Registry object, " f"but got {type(registry)}"
65 )
66 if not (isinstance(default_args, dict) or default_args is None):
67 raise TypeError(
68 "default_args must be a dict or None, " f"but got {type(default_args)}"
69 )
70
71 args = cfg.copy()
72
73 if default_args is not None:
74 for name, value in default_args.items():
75 args.setdefault(name, value)
76
77 obj_type = args.pop("type")
78 if isinstance(obj_type, str):
79 obj_cls = registry.get(obj_type)
80 if obj_cls is None:
81 raise KeyError(f"{obj_type} is not in the {registry.name} registry")
82 elif inspect.isclass(obj_type):
83 obj_cls = obj_type
84 else:
85 raise TypeError(f"type must be a str or valid type, but got {type(obj_type)}")
86 try:
87 return obj_cls(**args)
88 except Exception as e:
89 # Normal TypeError does not print class name.
90 raise type(e)(f"{obj_cls.__name__}: {e}")
91
92
93class Registry:
94 """A registry to map strings to classes.
95
96 Registered object could be built from registry.
97 Example:
98 >>> MODELS = Registry('models')
99 >>> @MODELS.register_module()
100 >>> class ResNet:
101 >>> pass
102 >>> resnet = MODELS.build(dict(type='ResNet'))
103
104 Please refer to
105 https://mmcv.readthedocs.io/en/latest/understand_mmcv/registry.html for
106 advanced usage.
107
108 Args:
109 name (str): Registry name.
110 build_func(func, optional): Build function to construct instance from
111 Registry, func:`build_from_cfg` is used if neither ``parent`` or
112 ``build_func`` is specified. If ``parent`` is specified and
113 ``build_func`` is not given, ``build_func`` will be inherited
114 from ``parent``. Default: None.
115 parent (Registry, optional): Parent registry. The class registered in
116 children registry could be built from parent. Default: None.
117 scope (str, optional): The scope of registry. It is the key to search
118 for children registry. If not specified, scope will be the name of
119 the package where class is defined, e.g. mmdet, mmcls, mmseg.
120 Default: None.
121 """
122
123 def __init__(self, name, build_func=None, parent=None, scope=None):
124 self._name = name
125 self._module_dict = dict()
126 self._children = dict()
127 self._scope = self.infer_scope() if scope is None else scope
128
129 # self.build_func will be set with the following priority:
130 # 1. build_func
131 # 2. parent.build_func
132 # 3. build_from_cfg
133 if build_func is None:
134 if parent is not None:
135 self.build_func = parent.build_func
136 else:
137 self.build_func = build_from_cfg
138 else:
139 self.build_func = build_func
140 if parent is not None:
141 assert isinstance(parent, Registry)
142 parent._add_children(self)
143 self.parent = parent
144 else:
145 self.parent = None
146
147 def __len__(self):
148 return len(self._module_dict)
149
150 def __contains__(self, key):
151 return self.get(key) is not None
152
153 def __repr__(self):
154 format_str = (
155 self.__class__.__name__ + f"(name={self._name}, "
156 f"items={self._module_dict})"
157 )
158 return format_str
159
160 @staticmethod
161 def infer_scope():
162 """Infer the scope of registry.
163
164 The name of the package where registry is defined will be returned.
165
166 Example:
167 # in mmdet/models/backbone/resnet.py
168 >>> MODELS = Registry('models')
169 >>> @MODELS.register_module()
170 >>> class ResNet:
171 >>> pass
172 The scope of ``ResNet`` will be ``mmdet``.
173
174
175 Returns:
176 scope (str): The inferred scope name.
177 """
178 # inspect.stack() trace where this function is called, the index-2
179 # indicates the frame where `infer_scope()` is called
180 filename = inspect.getmodule(inspect.stack()[2][0]).__name__
181 split_filename = filename.split(".")
182 return split_filename[0]
183
184 @staticmethod
185 def split_scope_key(key):
186 """Split scope and key.
187
188 The first scope will be split from key.
189
190 Examples:
191 >>> Registry.split_scope_key('mmdet.ResNet')
192 'mmdet', 'ResNet'
193 >>> Registry.split_scope_key('ResNet')
194 None, 'ResNet'
195
196 Return:
197 scope (str, None): The first scope.
198 key (str): The remaining key.
199 """
200 split_index = key.find(".")
201 if split_index != -1:
202 return key[:split_index], key[split_index + 1 :]
203 else:
204 return None, key
205
206 @property
207 def name(self):
208 return self._name
209
210 @property
211 def scope(self):
212 return self._scope
213
214 @property
215 def module_dict(self):
216 return self._module_dict
217
218 @property
219 def children(self):
220 return self._children
221
222 def get(self, key):
223 """Get the registry record.
224
225 Args:
226 key (str): The class name in string format.
227
228 Returns:
229 class: The corresponding class.
230 """
231 scope, real_key = self.split_scope_key(key)
232 if scope is None or scope == self._scope:
233 # get from self
234 if real_key in self._module_dict:
235 return self._module_dict[real_key]
236 else:
237 # get from self._children
238 if scope in self._children:
239 return self._children[scope].get(real_key)
240 else:
241 # goto root
242 parent = self.parent
243 while parent.parent is not None:
244 parent = parent.parent
245 return parent.get(key)
246
247 def build(self, *args, **kwargs):
248 return self.build_func(*args, **kwargs, registry=self)
249
250 def _add_children(self, registry):
251 """Add children for a registry.
252
253 The ``registry`` will be added as children based on its scope.
254 The parent registry could build objects from children registry.
255
256 Example:
257 >>> models = Registry('models')
258 >>> mmdet_models = Registry('models', parent=models)
259 >>> @mmdet_models.register_module()
260 >>> class ResNet:
261 >>> pass
262 >>> resnet = models.build(dict(type='mmdet.ResNet'))
263 """
264
265 assert isinstance(registry, Registry)
266 assert registry.scope is not None
267 assert (
268 registry.scope not in self.children
269 ), f"scope {registry.scope} exists in {self.name} registry"
270 self.children[registry.scope] = registry
271
272 def _register_module(self, module_class, module_name=None, force=False):
273 if not inspect.isclass(module_class):
274 raise TypeError("module must be a class, " f"but got {type(module_class)}")
275
276 if module_name is None:
277 module_name = module_class.__name__
278 if isinstance(module_name, str):
279 module_name = [module_name]
280 for name in module_name:
281 if not force and name in self._module_dict:
282 raise KeyError(f"{name} is already registered " f"in {self.name}")
283 self._module_dict[name] = module_class
284
285 def deprecated_register_module(self, cls=None, force=False):
286 warnings.warn(
287 "The old API of register_module(module, force=False) "
288 "is deprecated and will be removed, please use the new API "
289 "register_module(name=None, force=False, module=None) instead."
290 )
291 if cls is None:
292 return partial(self.deprecated_register_module, force=force)
293 self._register_module(cls, force=force)
294 return cls
295
296 def register_module(self, name=None, force=False, module=None):
297 """Register a module.
298
299 A record will be added to `self._module_dict`, whose key is the class
300 name or the specified name, and value is the class itself.
301 It can be used as a decorator or a normal function.
302
303 Example:
304 >>> backbones = Registry('backbone')
305 >>> @backbones.register_module()
306 >>> class ResNet:
307 >>> pass
308
309 >>> backbones = Registry('backbone')
310 >>> @backbones.register_module(name='mnet')
311 >>> class MobileNet:
312 >>> pass
313
314 >>> backbones = Registry('backbone')
315 >>> class ResNet:
316 >>> pass
317 >>> backbones.register_module(ResNet)
318
319 Args:
320 name (str | None): The module name to be registered. If not
321 specified, the class name will be used.
322 force (bool, optional): Whether to override an existing class with
323 the same name. Default: False.
324 module (type): Module class to be registered.
325 """
326 if not isinstance(force, bool):
327 raise TypeError(f"force must be a boolean, but got {type(force)}")
328 # NOTE: This is a walkaround to be compatible with the old api,
329 # while it may introduce unexpected bugs.
330 if isinstance(name, type):
331 return self.deprecated_register_module(name, force=force)
332
333 # raise the error ahead of time
334 if not (name is None or isinstance(name, str) or is_seq_of(name, str)):
335 raise TypeError(
336 "name must be either of None, an instance of str or a sequence"
337 f" of str, but got {type(name)}"
338 )
339
340 # use it as a normal method: x.register_module(module=SomeClass)
341 if module is not None:
342 self._register_module(module_class=module, module_name=name, force=force)
343 return module
344
345 # use it as a decorator: @x.register_module()
346 def _register(cls):
347 self._register_module(module_class=cls, module_name=name, force=force)
348 return cls
349
350 return _register