base
optimus_dl.modules.metrics.base
¶
BaseMeter
¶
Bases: ABC
Abstract base class for all individual stateful meter implementations.
Meters are responsible for accumulating raw data (via the log method)
and processing it into a final, reportable value (via the compute method).
A key feature of BaseMeter is its support for merging states from other
meter instances, which is crucial for distributed aggregation across multiple
workers or processes.
Subclasses must implement:
- compute(): To return the current aggregated value(s).
- log(**kwargs): To accumulate new data points.
- merge(other_state): To combine its state with that of another meter.
Source code in optimus_dl/modules/metrics/base.py
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 | |
compute()
abstractmethod
¶
Compute the final meter value from accumulated data.
This method should perform any necessary calculations on the internally accumulated data and return the result. It should not modify the meter's internal state.
Returns:
| Type | Description |
|---|---|
float | int | dict[str, float | int]
|
The computed value, which can be a float, integer, or a dictionary |
float | int | dict[str, float | int]
|
of sub-values (e.g., {'precision': 0.8, 'recall': 0.9}). |
Source code in optimus_dl/modules/metrics/base.py
from_state_dict(state_dict)
classmethod
¶
Create a new meter instance and restore its state from a dictionary.
This factory method constructs an instance of the meter class (cls)
and then calls its load_state_dict method to populate its internal state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dict
|
dict[str, Any]
|
A dictionary containing the saved internal state of a meter. |
required |
Returns:
| Type | Description |
|---|---|
BaseMeter
|
A new instance of the |
Source code in optimus_dl/modules/metrics/base.py
load_state_dict(state_dict)
¶
Restore the internal meter state from a dictionary.
By default, this updates self.__dict__ with the provided state_dict.
Subclasses may override this method for custom deserialization,
especially if state_dict() was also overridden.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dict
|
dict[str, Any]
|
A dictionary containing the saved internal state of a meter. |
required |
Source code in optimus_dl/modules/metrics/base.py
log(**kwargs)
abstractmethod
¶
Accumulate new raw data points into the meter's internal state.
This method is called for each data point or batch that needs to be
processed by the meter. The specific arguments in **kwargs depend
on the concrete meter implementation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Arbitrary keyword arguments representing the data to be logged. |
{}
|
Source code in optimus_dl/modules/metrics/base.py
merge(other_state)
abstractmethod
¶
Merge state from another instance of the same meter type.
This method is critical for distributed training, allowing the states
of meters from different processes/ranks to be combined into a single,
globally consistent state. The other_state should be a dictionary
representing the internal state of another meter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other_state
|
dict[str, Any]
|
A dictionary containing the internal state of another
|
required |
Source code in optimus_dl/modules/metrics/base.py
state_dict()
¶
Return the internal meter state as a dictionary for checkpointing.
By default, this returns a shallow copy of self.__dict__. Subclasses
may override this method if they need custom serialization logic (e.g.,
to handle non-serializable attributes or specific data structures).
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary representing the internal, serializable state of the meter. |
Source code in optimus_dl/modules/metrics/base.py
MeterEntry
dataclass
¶
Container for a meter and its logging metadata.
This dataclass holds an instance of a BaseMeter along with metadata
that controls its behavior within a MeterGroup and during logging.
Attributes:
| Name | Type | Description |
|---|
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
meter
|
BaseMeter
|
|
required |
reset
|
bool
|
|
False
|
priority
|
int
|
|
0
|
Source code in optimus_dl/modules/metrics/base.py
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 | |
load_state_dict(state_dict)
¶
Restore the MeterEntry's state from a checkpoint.
This method reconstructs the BaseMeter instance and restores its
internal state from the provided state_dict. It also updates
the reset and priority flags.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dict
|
dict[str, Any]
|
A dictionary containing the saved state of a |
required |
Source code in optimus_dl/modules/metrics/base.py
state_dict()
¶
Return the current state of this MeterEntry for checkpointing.
This method serializes the internal state of the meter itself,
along with the reset and priority flags, and the class name
of the meter, to allow for reconstruction.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary containing the serializable state of the |
Source code in optimus_dl/modules/metrics/base.py
MeterGroup
¶
A named collection of meters that are logged together.
This class manages a group of related meters (e.g., 'train' or 'eval'). It handles:
- Sampling Frequency: Only triggers logging every
log_freqsteps. - Priority Sorting: Ensures consistent ordering of meters in output.
- State Management: Can reset meters after logging and serialize the entire group state for checkpointing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique name for the group. |
required |
log_freq
|
int | None
|
Frequency (in iterations) at which to trigger logging. If None, defaults to 1 (log every iteration). |
None
|
Source code in optimus_dl/modules/metrics/base.py
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 304 | |
meters
property
¶
Returns the internal OrderedDict of MeterEntry objects.
The meters are returned in their natural insertion order,
not sorted by priority. Use _keys_sorted for ordered iteration.
add_meter(name, meter_entry)
¶
Add a new meter entry to the group.
If a meter with the same name already exists, it will be overwritten.
After adding, the sorted list of keys is updated to reflect any priority changes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The unique identifier for the meter within this group. |
required |
meter_entry
|
MeterEntry
|
The |
required |
Source code in optimus_dl/modules/metrics/base.py
compute()
¶
Compute the current values for all meters in the group.
Iterates through all meters currently in the group (sorted by priority)
and calls their compute() method to get their current value.
Returns:
| Type | Description |
|---|---|
dict[str, float | int | dict[str, float | int]]
|
An |
dict[str, float | int | dict[str, float | int]]
|
The values can be floats, integers, or nested dictionaries |
dict[str, float | int | dict[str, float | int]]
|
(for meters emitting multiple sub-values). |
Source code in optimus_dl/modules/metrics/base.py
get_meter(name)
¶
Retrieve a specific MeterEntry by its name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the meter to retrieve. |
required |
Returns:
| Type | Description |
|---|---|
MeterEntry | None
|
The |
Source code in optimus_dl/modules/metrics/base.py
load_state_dict(state_dict)
¶
Restore the MeterGroup state from a checkpoint.
Reconstructs the group's internal state, including all its meters
and their individual states, from the provided state_dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dict
|
dict[str, Any]
|
A dictionary containing the saved state of a |
required |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the name in the |
Source code in optimus_dl/modules/metrics/base.py
reset()
¶
Reset all meters marked for reset after logging.
This method iterates through all MeterEntry objects in the group.
If an entry's reset flag is True, the corresponding meter is removed
from the group. This is typically called after a logging event to
prepare for the next accumulation cycle for per-step meters.
Source code in optimus_dl/modules/metrics/base.py
should_log()
¶
Check if the current iteration should trigger logging.
This is a passive check that does not increment the iteration counter.
Returns:
| Type | Description |
|---|---|
bool
|
True if logging should occur at the current iteration, False otherwise. |
Source code in optimus_dl/modules/metrics/base.py
state_dict()
¶
Return the entire MeterGroup state for checkpointing.
Serializes the group's name, logging frequency, and the state of all
contained MeterEntry objects.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary containing the serializable state of the |
Source code in optimus_dl/modules/metrics/base.py
step()
¶
Increment the internal iteration counter for the group.
This method should be called once per relevant step (e.g., per batch)
to track progress and determine when logging should occur based on log_freq.
Returns:
| Type | Description |
|---|---|
bool
|
True if the current step is a logging step (i.e., |
bool
|
is a multiple of |
Source code in optimus_dl/modules/metrics/base.py
compute_meters(group_name, aggregate=False, collective=None)
¶
Compute final values for a named MeterGroup, with optional distributed aggregation.
This function retrieves the specified MeterGroup, computes the current
value for each of its meters, and optionally aggregates these values
across distributed ranks.
If aggregate is True, it performs an all-gather of meter states across
all distributed ranks and merges them before computing final values. This
ensures that metrics reflect a global view of the data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_name
|
str
|
Name of the |
required |
aggregate
|
bool
|
If True, meter states are aggregated from all ranks
using the provided |
False
|
collective
|
Collective | None
|
A |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, float | int | dict[str, float | int]]
|
A dictionary mapping meter names (or metric names, as exposed) to |
dict[str, float | int | dict[str, float | int]]
|
their computed values. These values can be floats, integers, or nested |
dict[str, float | int | dict[str, float | int]]
|
dictionaries. Returns an empty dictionary if the group name is not found. |
Source code in optimus_dl/modules/metrics/base.py
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 | |
load_state_dict(state_dict)
¶
Restore the state for all managed MeterGroups from a state dictionary.
This function iterates through the provided state_dict, recreating
MeterGroups as needed and loading their saved states.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dict
|
dict[str, Any]
|
A dictionary containing the saved state of all |
required |
Source code in optimus_dl/modules/metrics/base.py
log_meter(name, meter_factory, reset=True, priority=100, force_log=False, **kwargs)
¶
Log data point(s) to all currently active meter groups.
This is the primary function for adding data to meters within active
MeterGroups. It ensures that data is only logged when the group's
should_log() condition is met (unless force_log is True) and
handles the creation of meters if they don't already exist in a group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name under which this metric's data will be stored and reported.
This acts as the key for the |
required |
meter_factory
|
Callable[[], BaseMeter]
|
A callable (e.g., a lambda function) that, when called
with no arguments, returns a new instance of a |
required |
reset
|
bool
|
If True, the meter created or used for this log will be removed
from its |
True
|
priority
|
int
|
An integer determining the order of this meter in logs. Lower numbers mean higher priority (appear earlier). Defaults to 100. |
100
|
force_log
|
bool
|
If True, the metric will be logged even if the current
|
False
|
**kwargs
|
Any
|
Arbitrary keyword arguments that will be passed directly
to the |
{}
|
Source code in optimus_dl/modules/metrics/base.py
meters_group(name, log_freq=None, force_recreate=False)
¶
Context manager for activating a metrics group.
While inside this context, any calls to log_meter will be directed to
the MeterGroup identified by name. This allows for grouping related
meters (e.g., "train" or "eval" metrics).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the |
required |
log_freq
|
int | None
|
Optional logging frequency (in iterations) to set or update
for this group. If the group already exists and |
None
|
force_recreate
|
bool
|
If True, any existing |
False
|
Yields:
| Name | Type | Description |
|---|---|---|
bool |
True if the group should trigger logging at this step, based on
its |
Source code in optimus_dl/modules/metrics/base.py
reset_meters(name)
¶
Reset all resettable meters within a named MeterGroup.
This function triggers the reset() method on the specified MeterGroup,
which in turn removes all MeterEntry objects that have their reset flag
set to True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the |
required |
Source code in optimus_dl/modules/metrics/base.py
state_dict()
¶
Return the combined state dictionary for all managed MeterGroups.
This function collects the state_dict() from each active MeterGroup,
allowing the entire metrics system state to be checkpointed.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary where keys are |
dict[str, Any]
|
respective state dictionaries. |
Source code in optimus_dl/modules/metrics/base.py
step_meters(name)
¶
Explicitly step the iteration counter for a named MeterGroup.
This function allows external components to manually advance the iteration
counter of a specific MeterGroup, which can influence when should_log
returns True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the |
required |