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 NoneInspect 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()