"""Check distributions, support, and gradients in probability and logit space."""
import argparse
import json
from math import fsum,isclose,isfinite,isinf,log
import platform
def validate(p,q):
if len(p)!=len(q) or not p:
raise ValueError("distribution shapes differ")
for values in (p,q):
if any(x<0 or not isfinite(x) for x in values) or not isclose(fsum(values),1.,abs_tol=1e-12,rel_tol=0):
raise ValueError("invalid distribution")
def cross_entropy(p,q):
validate(p,q)
return fsum(-mass*log(guess) if guess else float("inf")
for mass,guess in zip(p,q,strict=True) if mass>0)
def divergence(p,q):
return cross_entropy(p,q)-cross_entropy(p,p)
def main():
parser=argparse.ArgumentParser()
parser.add_argument("--torch",action="store_true")
args=parser.parse_args()
cases=[]
versions={}
def check(name,inputs,expected,actual,operation):
assert expected==actual,(name,expected,actual)
cases.append(dict(name=name,input=inputs,operation=operation,expected=expected,actual=actual,passed=True))
gold=[1,0,0]
guesses=[[.9,.05,.05],[.4,.3,.3],[.1,.8,.1]]
check("three_one_hot_cross_entropies",{"p":gold,"q":guesses},[.105361,.916291,2.302585],
[round(cross_entropy(gold,q),6) for q in guesses],"take the true-class negative log probability")
check("support_and_zero_terms",{"p":[1,0],"q":[0,1]},[True,True,0],
[isinf(cross_entropy([1,0],[0,1])),isinf(divergence([1,0],[0,1])),divergence([1,0],[1,0])],
"compare positive mass lacking support and zero-mass terms")
p=[.8,.2]
q=[.5,.5]
check("kl_asymmetry_and_entropy_relation",{"p":p,"q":q},[.192745,.223144,True],
[round(divergence(p,q),6),round(divergence(q,p),6),
isclose(cross_entropy(p,q),cross_entropy(p,p)+divergence(p,q))],
"evaluate both KL directions and the cross-entropy identity")
check("coding_excess_bits",{"p":p,"q":q},.278072,round(divergence(p,q)/log(2),6),
"convert the per-symbol coding penalty from nats to bits")
if args.torch:
import torch
import torch.nn.functional as nnf
versions["torch"]=torch.__version__
tensor=lambda data,**kwargs: torch.tensor(data,dtype=torch.float64,**kwargs)
probability=tensor(.01,requires_grad=True)
ce_value=-probability.log()
mse_value=(probability-1).square()
prob_grad=[float(torch.autograd.grad(loss,probability)[0]) for loss in (ce_value,mse_value)]
check("probability_space_gradients",{"p":.01,"label":1},[-100.,-1.98],
[round(value,8) for value in prob_grad],"differentiate both losses directly with respect to probability")
logit=tensor(log(.01/.99),requires_grad=True)
ce_value=nnf.binary_cross_entropy_with_logits(logit,tensor(1.))
mse_value=(logit.sigmoid()-1).square()
logit_grad=[float(torch.autograd.grad(loss,logit)[0]) for loss in (ce_value,mse_value)]
check("logit_space_gradients",{"p":.01,"label":1,"z":float(logit.detach())},[-.99,-.019602],
[round(value,8) for value in logit_grad],"differentiate through the sigmoid")
logits=tensor([[log(2),0.,0.]],requires_grad=True)
categorical=nnf.cross_entropy(logits,torch.tensor([2]))
categorical.backward()
check("softmax_cross_entropy_logit_grad",{"logits":[log(2),0,0],"target":2},[.5,.25,-.75],
[round(value,12) for value in logits.grad[0].tolist()],"check unweighted one-sample gradients")
extreme=tensor([[-1000.,1000.]])
check("stable_logits_compute_a_finite_loss",[-1000,1000],[0.,2000.],
[float(extreme.softmax(1)[0,0]),float(nnf.cross_entropy(extreme,torch.tensor([0])))],
"compare softmax underflow with stable logits loss")
target=tensor([p,p])
prediction=tensor([q,q])
actual=nnf.kl_div(prediction.log(),target,reduction="batchmean")
check("torch_kl_batchmean_orientation",{"p":p,"q":q,"batch":2},True,
isclose(float(actual),divergence(p,q),abs_tol=1e-12),"pass model log-probabilities then target probabilities")
teacher=tensor([[3.,1.,0.]])
student=tensor([[1.,0.,0.]],requires_grad=True)
temperature=2.
soft=(teacher/temperature).softmax(dim=1)
hard=teacher.softmax(dim=1)
distill=temperature**2*nnf.kl_div((student/temperature).log_softmax(dim=1),soft,reduction="batchmean")
distill.backward()
check("distillation_teacher_soft_targets",{"teacher":[3,1,0],"student":[1,0,0],"temperature":temperature},
[True,True,True],[bool(soft[0,0]<hard[0,0]),bool(distill.detach()>0),bool(student.grad.abs().sum()>0)],
"temper both models and differentiate teacher-to-student KL")
prior=torch.distributions.Normal(tensor(0),tensor(1))
moved=torch.distributions.Normal(tensor(2),tensor(1))
check("vae_gaussian_kl_to_standard",{"variance":1,"means":[0,2]},[0.,2.],
[float(torch.distributions.kl_divergence(d,prior)) for d in (prior,moved)],
"compare matching and shifted Gaussian latent distributions")
ref=[.5,.5]
policies=[[.5,.5],[.9,.1]]
comparisons=[[sum(v*r for v,r in zip(policy,[1,0],strict=True))-beta*divergence(policy,ref)
for policy in policies] for beta in (0.,2.)]
check("kl_penalty_changes_toy_preference",{"policies":policies,"reference":ref,"coefficients":[0,2]},[1,0],
[max(range(2),key=values.__getitem__) for values in comparisons],
"compare expected reward with and without a reference-policy penalty")
print(json.dumps(dict(version=platform.python_version(),library_versions=versions,cases=cases)))
if __name__=="__main__":
main()
本例需在 Windows、Python 3.12.14。torch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14。torch 2.10.0+cpu。
入口文件:projects/ai-math-cross-entropy-kl-lab/cross-entropy-lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
cross-entropy-lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14。torch 2.10.0+cpu。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a46.zip