TorchLean API

NN.Examples.DeepDives.Floats.Float32Semantics

Float32 Semantics #

This tutorial runs the same compact MLP under two executable binary32 semantics:

import torch
from torch import nn

model = nn.Sequential(nn.Linear(2, 3), nn.ReLU(), nn.Linear(3, 1)).to(torch.float32)

# PyTorch runs the model through its selected float32 kernels.

The TorchLean example adds an independent second execution. Lean's native Float32 supplies the ordinary runtime path, while ExecFloat.Binary 8 23 computes from explicit binary32 fields and rounding rules. The model and autograd program stay unchanged because their element type is generic.

Run: lake exe torchlean float32_semantics

For editor inspection, put the cursor on the #float32_* commands below. Those widgets are for visualization only; the actual tutorial code uses ordinary def and IO definitions.

Float32 widget probes #

0.1 is the canonical "not exactly representable" decimal. The widget shows the binary32 value that ExecFloat.Binary 8 23 receives after rounding from the host literal.

PyTorch analogue:

torch.tensor(0.1, dtype=torch.float32)
Instances For
    @[reducible, inline]

    The network this tutorial runs twice, once in Float and once in Float32.

    Instances For
      @[reducible, inline]

      Parameter and buffer layout generated by the two affine layers in model.

      Instances For

        Named outputs from one forward and reverse-mode execution.

        Instances For

          Convert every tensor in a run result while preserving its statically known shape.

          Instances For

            Run one forward and backward pass over the fixed parameters at scalar type α.

            The whole tutorial rests on this being generic in α: the same code, the same literals and the same graph run at Float and at Float32, so any difference in the printed numbers comes from the arithmetic and nothing else.

            Instances For

              Largest difference across every tensor in a run: the output, all four parameter gradients and the input gradient. One number summarizing how far the two precisions drifted apart.

              Instances For

                Command-line help for the Float32 semantics tutorial.

                Instances For