WZMIAOMIAO/deep-learning-for-image-processing · error · AttributeError

'{}' object has no attribute '{}'

Error message

'{}' object has no attribute '{}'

What it means

Same MetricLogger.__getattr__ AttributeError as the lraspp variant: the u2net training utility's SmoothedValue/MetricLogger raises AttributeError when an attribute is neither in self.meters nor self.__dict__. It exists so that missing attribute access fails loudly instead of returning None.

Source

Thrown at pytorch_segmentation/u2net/train_utils/distributed_utils.py:209

class MetricLogger(object):
    def __init__(self, delimiter="\t"):
        self.meters = defaultdict(SmoothedValue)
        self.delimiter = delimiter

    def update(self, **kwargs):
        for k, v in kwargs.items():
            if isinstance(v, torch.Tensor):
                v = v.item()
            assert isinstance(v, (float, int))
            self.meters[k].update(v)

    def __getattr__(self, attr):
        if attr in self.meters:
            return self.meters[attr]
        if attr in self.__dict__:
            return self.__dict__[attr]
        raise AttributeError("'{}' object has no attribute '{}'".format(
            type(self).__name__, attr))

    def __str__(self):
        loss_str = []
        for name, meter in self.meters.items():
            loss_str.append(
                "{}: {}".format(name, str(meter))
            )
        return self.delimiter.join(loss_str)

    def synchronize_between_processes(self):
        for meter in self.meters.values():
            meter.synchronize_between_processes()

    def add_meter(self, name, meter):
        self.meters[name] = meter

    def log_every(self, iterable, print_freq, header=None):

View on GitHub (pinned to 1ec3fe6f37)

Solutions

  1. Correct the attribute/meter name
  2. Initialize the meter before first read, e.g. metric_logger.lr = SmoothedValue()
  3. Guard with hasattr() or `name in metric_logger.meters`

Example fix

// before
lr = metric_logger.learnig_rate.global_avg
// after
lr = metric_logger.lr.global_avg
Defensive patterns

Strategy: validation

Validate before calling

missing = [n for n in ['loss', 'lr'] if n not in metric_logger.meters]
if missing:
    raise KeyError(f"meters not registered: {missing}")

Type guard

def has_attr(logger, name: str) -> bool:
    return name in getattr(logger, 'meters', {}) or hasattr(logger, name)

Try / catch

try:
    stats = {k: v.global_avg for k, v in metric_logger.meters.items()}
except AttributeError as e:
    print(f"metric access failed: {e}"); stats = {}

Prevention

When it happens

Trigger: Reading a meter attribute (e.g. metric_logger.lr) before it was ever assigned, or misspelling a meter name in the validation/training loop of u2net training.

Common situations: Typos like metric_logger.metres, accessing a metric before update() was called, refactoring meter names between train and eval phases.

Related errors


AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30). Data as JSON: /api/errors/3916ed1e2f8d48e5. Report an issue: GitHub.