or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mddataset.mddistributed.mdfileio.mdindex.mdlogging.mdmodels.mdoptimization.mdregistry.mdtraining.mdvisualization.md

registry.mddocs/

0

# Registry System

1

2

Comprehensive component registry system enabling modular architecture with automatic discovery, registration, and instantiation of models, datasets, optimizers, and other components. The registry system is central to MMEngine's plugin architecture and configuration-driven development.

3

4

## Capabilities

5

6

### Registry Class

7

8

Core registry class for mapping strings to classes with hierarchical organization and scope management.

9

10

```python { .api }

11

class Registry:

12

def __init__(self, name: str, build_func: callable = None, parent: 'Registry' = None, scope: str = None, locations: list = None):

13

"""

14

Initialize Registry.

15

16

Parameters:

17

- name: Registry name

18

- build_func: Function to build objects from config

19

- parent: Parent registry for hierarchy

20

- scope: Registry scope

21

- locations: Import locations for automatic discovery

22

"""

23

24

def register_module(self, name: str = None, force: bool = False, module: type = None) -> callable:

25

"""

26

Register module in registry.

27

28

Parameters:

29

- name: Module name (uses class name if None)

30

- force: Whether to override existing registration

31

- module: Module class to register

32

33

Returns:

34

Decorator function or registered module

35

"""

36

37

def build(self, cfg: dict) -> object:

38

"""

39

Build object from configuration.

40

41

Parameters:

42

- cfg: Configuration dictionary with 'type' key

43

44

Returns:

45

Built object instance

46

"""

47

48

def get(self, key: str) -> type:

49

"""

50

Get registered module class.

51

52

Parameters:

53

- key: Module name

54

55

Returns:

56

Registered module class

57

"""

58

59

def __contains__(self, key: str) -> bool:

60

"""

61

Check if key is registered.

62

63

Parameters:

64

- key: Module name

65

66

Returns:

67

True if module is registered

68

"""

69

70

def __len__(self) -> int:

71

"""Get number of registered modules."""

72

73

@property

74

def name(self) -> str:

75

"""Registry name."""

76

77

@property

78

def scope(self) -> str:

79

"""Registry scope."""

80

81

@property

82

def module_dict(self) -> dict:

83

"""Dictionary of registered modules."""

84

```

85

86

### Default Scope Management

87

88

System for managing registry scopes and hierarchies across the codebase.

89

90

```python { .api }

91

class DefaultScope:

92

def __init__(self, scope_name: str, overrides: list = None):

93

"""

94

Initialize default scope context.

95

96

Parameters:

97

- scope_name: Name of the scope

98

- overrides: List of scope overrides

99

"""

100

101

def __enter__(self) -> 'DefaultScope':

102

"""Enter scope context."""

103

104

def __exit__(self, exc_type, exc_val, exc_tb):

105

"""Exit scope context."""

106

107

@classmethod

108

def get_current_instance(cls) -> 'DefaultScope':

109

"""

110

Get current default scope instance.

111

112

Returns:

113

Current DefaultScope instance

114

"""

115

116

def init_default_scope(scope: str):

117

"""

118

Initialize default scope.

119

120

Parameters:

121

- scope: Scope name to set as default

122

"""

123

```

124

125

### Build Functions

126

127

High-level functions for building objects from configurations using registries.

128

129

```python { .api }

130

def build_from_cfg(cfg: dict, registry: Registry, default_args: dict = None) -> object:

131

"""

132

Build object from configuration using registry.

133

134

Parameters:

135

- cfg: Configuration dictionary

136

- registry: Registry to use for building

137

- default_args: Default arguments to merge

138

139

Returns:

140

Built object instance

141

"""

142

143

def build_model_from_cfg(cfg: dict, registry: Registry = None, default_args: dict = None):

144

"""

145

Build model from configuration.

146

147

Parameters:

148

- cfg: Model configuration

149

- registry: Model registry (uses MODELS if None)

150

- default_args: Default arguments

151

152

Returns:

153

Built model instance

154

"""

155

156

def build_runner_from_cfg(cfg: dict) -> 'Runner':

157

"""

158

Build runner from configuration.

159

160

Parameters:

161

- cfg: Runner configuration

162

163

Returns:

164

Built runner instance

165

"""

166

167

def build_scheduler_from_cfg(cfg: dict, default_args: dict = None):

168

"""

169

Build scheduler from configuration.

170

171

Parameters:

172

- cfg: Scheduler configuration

173

- default_args: Default arguments

174

175

Returns:

176

Built scheduler instance

177

"""

178

```

179

180

### Global Registry Instances

181

182

Pre-defined global registries for different component types used throughout MMEngine.

183

184

```python { .api }

185

# Core component registries

186

RUNNERS: Registry # Registry for runner classes

187

RUNNER_CONSTRUCTORS: Registry # Registry for runner constructors

188

HOOKS: Registry # Registry for hook classes

189

LOOPS: Registry # Registry for training loop classes

190

191

# Data-related registries

192

DATASETS: Registry # Registry for dataset classes

193

DATA_SAMPLERS: Registry # Registry for data sampler classes

194

TRANSFORMS: Registry # Registry for data transform classes

195

196

# Model-related registries

197

MODELS: Registry # Registry for model classes

198

WEIGHT_INITIALIZERS: Registry # Registry for weight initializers

199

MODEL_WRAPPERS: Registry # Registry for model wrapper classes

200

201

# Optimization registries

202

OPTIMIZERS: Registry # Registry for optimizer classes

203

OPTIM_WRAPPERS: Registry # Registry for optimizer wrappers

204

OPTIM_WRAPPER_CONSTRUCTORS: Registry # Registry for optimizer wrapper constructors

205

PARAM_SCHEDULERS: Registry # Registry for parameter schedulers

206

207

# Evaluation registries

208

METRICS: Registry # Registry for metric classes

209

EVALUATOR: Registry # Registry for evaluator classes

210

211

# Visualization registries

212

VISBACKENDS: Registry # Registry for visualization backends

213

VISUALIZERS: Registry # Registry for visualizer classes

214

215

# Utility registries

216

LOG_PROCESSORS: Registry # Registry for log processors

217

INFERENCERS: Registry # Registry for inferencer classes

218

FUNCTIONS: Registry # Registry for utility functions

219

TASK_UTILS: Registry # Registry for task utility functions

220

STRATEGIES: Registry # Registry for training strategies

221

```

222

223

### Registry Utilities

224

225

Utility functions for working with registries and registry hierarchies.

226

227

```python { .api }

228

def traverse_registry_tree(registry: Registry, verbose: bool = False) -> dict:

229

"""

230

Traverse registry hierarchy tree.

231

232

Parameters:

233

- registry: Root registry to traverse

234

- verbose: Whether to include detailed information

235

236

Returns:

237

Dictionary representing registry tree structure

238

"""

239

240

def count_registered_modules(registry: Registry, verbose: bool = False) -> int:

241

"""

242

Count registered modules in registry.

243

244

Parameters:

245

- registry: Registry to count

246

- verbose: Whether to print detailed count

247

248

Returns:

249

Number of registered modules

250

"""

251

```

252

253

## Usage Examples

254

255

### Basic Module Registration

256

257

```python

258

from mmengine import Registry

259

260

# Create custom registry

261

MODELS = Registry('model')

262

263

# Register using decorator

264

@MODELS.register_module()

265

class MyModel:

266

def __init__(self, param1, param2):

267

self.param1 = param1

268

self.param2 = param2

269

270

# Register with custom name

271

@MODELS.register_module(name='CustomModel')

272

class AnotherModel:

273

pass

274

275

# Register programmatically

276

MODELS.register_module(name='ThirdModel', module=SomeModelClass)

277

```

278

279

### Building from Configuration

280

281

```python

282

from mmengine import Registry, build_from_cfg

283

284

# Configuration dictionary

285

cfg = {

286

'type': 'MyModel',

287

'param1': 'value1',

288

'param2': 42

289

}

290

291

# Build object from config

292

model = build_from_cfg(cfg, MODELS)

293

294

# Build with default arguments

295

default_args = {'param3': 'default_value'}

296

model = build_from_cfg(cfg, MODELS, default_args)

297

```

298

299

### Using Global Registries

300

301

```python

302

from mmengine import MODELS, OPTIMIZERS, build_from_cfg

303

304

# Register model in global registry

305

@MODELS.register_module()

306

class ResNet:

307

def __init__(self, depth, num_classes):

308

self.depth = depth

309

self.num_classes = num_classes

310

311

# Register optimizer

312

@OPTIMIZERS.register_module()

313

class AdamW:

314

def __init__(self, lr, weight_decay):

315

self.lr = lr

316

self.weight_decay = weight_decay

317

318

# Build from configs

319

model_cfg = {'type': 'ResNet', 'depth': 50, 'num_classes': 1000}

320

model = build_from_cfg(model_cfg, MODELS)

321

322

optim_cfg = {'type': 'AdamW', 'lr': 0.001, 'weight_decay': 0.01}

323

optimizer = build_from_cfg(optim_cfg, OPTIMIZERS)

324

```

325

326

### Scope Management

327

328

```python

329

from mmengine import DefaultScope, Registry

330

331

# Create registry with scope

332

MODELS = Registry('models', scope='myproject')

333

334

# Use scope context

335

with DefaultScope('myproject'):

336

@MODELS.register_module()

337

class ScopedModel:

338

pass

339

340

# Initialize default scope

341

init_default_scope('myproject')

342

```

343

344

### Registry Hierarchy

345

346

```python

347

from mmengine import Registry

348

349

# Create parent registry

350

BASE_MODELS = Registry('base_models')

351

352

# Create child registry

353

SPECIFIC_MODELS = Registry('specific_models', parent=BASE_MODELS)

354

355

# Register in parent

356

@BASE_MODELS.register_module()

357

class BaseModel:

358

pass

359

360

# Register in child

361

@SPECIFIC_MODELS.register_module()

362

class SpecificModel:

363

pass

364

365

# Child can access parent modules

366

assert 'BaseModel' in SPECIFIC_MODELS

367

assert 'SpecificModel' in SPECIFIC_MODELS

368

```

369

370

### Custom Build Function

371

372

```python

373

from mmengine import Registry

374

375

def custom_build_func(cfg, registry, default_args=None):

376

"""Custom build function with preprocessing."""

377

# Preprocess config

378

cfg = preprocess_config(cfg)

379

380

# Get class from registry

381

cls = registry.get(cfg['type'])

382

383

# Build with custom logic

384

return cls(**cfg)

385

386

# Create registry with custom build function

387

CUSTOM_REGISTRY = Registry('custom', build_func=custom_build_func)

388

```

389

390

### Registry Inspection

391

392

```python

393

from mmengine import MODELS, traverse_registry_tree, count_registered_modules

394

395

# Count registered modules

396

num_models = count_registered_modules(MODELS, verbose=True)

397

398

# Traverse registry tree

399

tree = traverse_registry_tree(MODELS, verbose=True)

400

401

# Check registration

402

if 'ResNet' in MODELS:

403

resnet_cls = MODELS.get('ResNet')

404

405

# List all registered modules

406

all_models = MODELS.module_dict.keys()

407

```