REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Fit a positive heteroscedastic Gaussian likelihood

Use variance=softplus(raw_variance)+floor and return mean(0.5*(log(2*pi)+log(variance)+(target-mean)**2/variance)). Preserve gradients through both mean and raw variance. Require aligned nonempty finite floating tensors and finite floor>0. The floor is part of the declared model; do not clamp a negative variance after taking its logarithm.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Fit a positive heteroscedastic Gaussian likelihood →

Your task

Use variance=softplus(raw_variance)+floor and return mean(0.5*(log(2*pi)+log(variance)+(target-mean)**2/variance)). Preserve gradients through both mean and raw variance. Require aligned nonempty finite floating tensors and finite floor>0. The floor is part of the declared model; do not clamp a negative variance after taking its logarithm.

Starter

import math
import torch
from torch.nn import functional as F

def gaussian_nll(mean, raw_variance, target, floor=1e-4):
    # TODO: implement gaussian_nll under the declared contract.
    return None
Inspect the worked answer
import math
import torch
from torch.nn import functional as F

def gaussian_nll(mean, raw_variance, target, floor=1e-4):
    values=(mean,raw_variance,target)
    if mean.numel()==0 or any(x.shape!=mean.shape or not x.is_floating_point() or not torch.isfinite(x).all() for x in values):raise ValueError('Expected aligned finite floating nonempty tensors.')
    if not math.isfinite(floor) or floor<=0:raise ValueError('Variance floor must be positive and finite.')
    variance=F.softplus(raw_variance)+floor
    result=.5*(math.log(2*math.pi)+variance.log()+(target-mean).square()/variance)
    return result.mean()

About this algorithm

How Fit a positive heteroscedastic Gaussian likelihood works

The idea

Ordinary regression predicts one number and treats every error alike. A heteroscedastic model predicts two numbers for each input, a mean and a variance, so it can say that some predictions are less certain than others. It is trained with the Gaussian negative log-likelihood, 0.5 * (log(2π) + log(variance) + (target - mean)² / variance).

The two variance terms pull in opposite directions, and that tension keeps the variance honest. Dividing the squared error by the variance rewards a large variance where the model misses. The log(variance) term charges for it, so claiming high uncertainty everywhere is not free. A network's raw output can be any real number, so gaussian_nll passes it through softplus and adds a small floor, which keeps the variance positive.

How it works

  1. Require mean, raw_variance and target to be non-empty finite floating tensors of one shape, and floor to be finite and positive.
  2. Compute variance = F.softplus(raw_variance) + floor, which is positive for any raw value.
  3. Compute the squared error (target - mean).square() and divide it by variance.
  4. Add log(2π) and variance.log(), then multiply the sum by 0.5 for each element.
  5. Return the mean, which backpropagates into both mean and raw_variance.

What it costs

Per batch
O(N)
Memory
O(N)
Model outputs
mean and raw variance

The loss is a few elementwise operations per target, and the only added model cost is a second output for the variance.

Where it is used

  • PyTorch provides this loss as torch.nn.GaussianNLLLoss, which takes a predicted mean and a predicted variance for each target.
  • Lakshminarayanan and co-authors' Deep Ensembles train each network with a Gaussian likelihood so that it outputs a mean and a variance.
  • Amazon's DeepAR forecasting model outputs the parameters of a likelihood, such as a Gaussian mean and standard deviation, at every time step.

Watch out for

  • Letting the network output the variance directly: a negative value makes log return nan. Pass it through softplus first.
  • Dropping the log(variance) term, after which the loss can always be lowered by predicting an enormous variance.
  • Clamping only after taking the logarithm, or using a floor of zero: a variance that underflows to 0 still breaks the division.