experiment_runner.losses

Loss lookup: the config string to a torch.nn loss object.

The package takes the loss object itself (see train_model()), so every nn.*Loss and every custom Module with a (logits, targets) -> scalar call works without a table entry. The table exists only because YAML cannot hold an object; see experiment_runner.lookups for the shared mechanics.

Attributes

logger

LOSSES

Config name -> loss class. Anything else resolves by dotted path.

Functions

build_loss(→ torch.nn.Module | None)

Return the loss object for the config value name.

as_tensors(→ dict)

Return params with every list value converted to a float32 tensor.

Module Contents

experiment_runner.losses.logger
experiment_runner.losses.LOSSES: dict[str, type[torch.nn.Module]]

Config name -> loss class. Anything else resolves by dotted path.

experiment_runner.losses.build_loss(name: str | None, params: dict | None = None) → torch.nn.Module | None

Return the loss object for the config value name.

Parameters:
  • name (str or None) – A key of LOSSES (matched case-insensitively, since configs spell it "CrossEntropy"), or a dotted import path to a loss class. None returns None, which leaves train_model() on its own default so the default lives in one place.

  • params (dict, optional) – Constructor arguments, e.g. {"weight": [1.0, 3.0, 1.0]}. List values become float32 tensors - see as_tensors().

Returns:

The constructed loss, or None when no name was given.

Return type:

torch.nn.Module or None

Raises:

ValueError – If name resolves to nothing, if construction fails, or if params were given without a name to apply them to.

experiment_runner.losses.as_tensors(params: dict) → dict

Return params with every list value converted to a float32 tensor.

The tensor-valued arguments of the torch loss family - weight for CrossEntropyLoss and NLLLoss, weight and pos_weight for BCEWithLogitsLoss - are registered buffers, and a list cannot be assigned to one: the constructor raises cannot assign 'list' object to buffer 'weight'. YAML has no tensor, so the conversion happens here. float32 specifically, because a float64 weight makes the loss raise expected scalar type Float but found Double at the first call.

Parameters:

params (dict) – Constructor arguments as they came from YAML.

Returns:

The same mapping with list and tuple values as tensors.

Return type:

dict