TorchLean API

NN.API.Models.Diffusion

Diffusion Models #

Config-style diffusion model constructors plus reusable, dataset-independent DDPM/DDIM helpers.

The runnable examples decide where data comes from (CIFAR-10, ImageNet-style folders, synthetic artifacts). The definitions here are shape-parametric and can be reused by tests, examples, and future proof layer specifications.

Configuration for a convolutional diffusion-noise predictor.

  • dataChannels :

    Number of channels in the denoised sample.

  • spatial : Tensor [d]

    Size of each sample axis. Values such as [32, 32] work directly.

  • hiddenChannels :

    Hidden channel width.

  • kernelRadius : Tensor [d]

    Radius of the same-padding convolution kernel on each axis.

    A radius of 1 gives the usual kernel size 3; every residual branch therefore preserves the sample grid by construction.

Instances For

    Validate the complete epsilon-predictor geometry before allocating convolution parameters.

    Instances For
      @[reducible, inline]

      Input shape, with one extra channel carrying diffusion time.

      Instances For
        @[reducible, inline]

        Output shape matching the denoised data channels.

        Instances For
          def TorchLean.nn.models.Internal.noisePredictorConvolution {d : } (config : Diffusion.NoisePredictor.Config d) (batchShape : Shape) (inputChannels outputChannels : ) :
          Builder (Sequential (batchShape.concat ((config.spatial.to Shape).prependDim inputChannels)) (batchShape.concat ((config.spatial.to Shape).prependDim outputChannels)))

          Implementation helper for the shape-preserving convolutions in the epsilon predictors.

          Instances For
            def TorchLean.nn.models.Diffusion.NoisePredictor.basic {d : } (config : Config d) (batchShape : Shape := []) :
            Builder (Sequential (config.inputShape batchShape) (config.outputShape batchShape))

            Build a minimal epsilon-predictor conv net: conv -> relu -> conv -> relu -> conv -> relu -> conv.

            This stays compact enough for the eager CUDA example while giving the CIFAR trainer more denoising capacity than a bare two-layer network.

            Instances For
              def TorchLean.nn.models.Diffusion.NoisePredictor.residual {d : } (config : Config d) (batchShape : Shape := []) :
              Builder (Sequential (config.inputShape batchShape) (config.outputShape batchShape))

              Build a stronger same-resolution residual epsilon predictor.

              Architecture:

              stem conv -> relu -> residual block -> relu -> residual block -> relu -> output conv

              Each residual block preserves hiddenChannels :: spatial and computes $x+\operatorname{conv}(\operatorname{relu}(\operatorname{conv}(x)))$. This compact residual denoiser omits U-Net downsampling, upsampling, and multi-scale skip concatenation. It is still a useful compact architecture because residual paths make the denoising problem much easier than a plain conv chain while staying within the eager CUDA memory envelope used by examples.

              Instances For

                Map a tensor from the unit interval to the signed unit interval.

                Instances For
                  def TorchLean.diffusion.normalNoise {shape : Shape} (seed step : ) :

                  Deterministic Gaussian epsilon tensor for an arbitrary diffusion shape.

                  The (seed, step) pair is turned into the runtime RNG key, so examples and artifact generation can reproduce the same noising path without ambient randomness.

                  Instances For
                    @[reducible, inline]
                    abbrev TorchLean.diffusion.sampleShape (batchShape : Shape) (channels : ) {d : } (spatial : Tensor [d]) :

                    Diffusion sample layout: arbitrary batch axes followed by channels and spatial axes.

                    Instances For
                      def TorchLean.diffusion.Internal.linearBetaAt (T : ) (betaStart betaEnd : Float) (t : ) :

                      Linear beta-schedule worker for a natural-number timestep.

                      Instances For
                        def TorchLean.diffusion.Internal.linearAlphaBarAt (T : ) (betaStart betaEnd : Float) (t : ) :

                        Cumulative linear-schedule worker for a natural-number timestep.

                        Instances For

                          Whether a loaded cumulative diffusion coefficient is finite and probabilistically valid.

                          Instances For

                            Cumulative diffusion coefficients cannot increase as noise is added.

                            Instances For
                              def TorchLean.diffusion.linearBeta {T : } (betaStart betaEnd : Float) (t : Fin T) :

                              Linear beta-schedule value at a timestep that belongs to the schedule.

                              Instances For
                                def TorchLean.diffusion.linearAlphaBar {T : } (betaStart betaEnd : Float) (t : Fin T) :

                                The cumulative coefficient $\bar\alpha_t=\prod_{s=0}^{t}(1-\beta_s)$.

                                Instances For
                                  def TorchLean.diffusion.linearAlphaBars (T : ) (betaStart betaEnd : Float) :

                                  The T cumulative coefficients of a linear beta schedule.

                                  The length belongs to the return type, so a consumer cannot pair the coefficients with a different timestep count.

                                  Instances For

                                    A validated, nonempty diffusion schedule.

                                    The constructor is private so runnable code never carries a separate proof that the coefficient tensor can be indexed. Use Schedule.from for loaded coefficients or Schedule.linear for the standard linear beta schedule.

                                    • alphaBars : Tensor Float [steps]

                                      Cumulative coefficients indexed by diffusion timestep.

                                    • nonempty : steps 0

                                      Internal invariant used to cycle natural-number training steps safely.

                                    Instances For
                                      opaque TorchLean.diffusion.Schedule.from {steps : } (alphaBars : Tensor Float [steps]) :

                                      Validate a coefficient tensor as a runnable diffusion schedule.

                                      def TorchLean.diffusion.Schedule.linear (steps : ) (betaStart betaEnd : Float) :

                                      Build and validate the standard linear beta schedule.

                                      Instances For
                                        def TorchLean.diffusion.Schedule.index {steps : } (schedule : Schedule steps) (step : ) :
                                        Fin steps

                                        Cycle an arbitrary logical step through this schedule.

                                        Instances For
                                          def TorchLean.diffusion.Schedule.alphaBar {steps : } (schedule : Schedule steps) (step : ) :

                                          Cumulative coefficient selected by a logical training step.

                                          Instances For
                                            def TorchLean.diffusion.Schedule.normalizedTime {steps : } (schedule : Schedule steps) (step : ) :

                                            Normalize a logical training step to the unit interval used by the time channel.

                                            Instances For
                                              def TorchLean.diffusion.Internal.appendTimeChannel (batchShape : Shape) {d c : } (spatial : Tensor [d]) (x : Tensor Float (sampleShape batchShape c spatial)) (tNorm : Float) :
                                              Tensor Float (sampleShape batchShape (c + 1) spatial)

                                              Recursive worker for diffusion.appendTimeChannel.

                                              Instances For
                                                def TorchLean.diffusion.appendTimeChannel (batchShape : Shape) {d c : } (spatial : Tensor [d]) (x : Tensor Float (sampleShape batchShape c spatial)) (tNorm : Float) :
                                                Tensor Float (sampleShape batchShape (c + 1) spatial)

                                                Append a constant time channel to every sample in batchShape.

                                                The input layout is batchShape × channels × spatial. The result preserves the batch and spatial axes and changes only the channel count from c to c + 1.

                                                Instances For
                                                  def TorchLean.diffusion.noisedSampleFromNoise (batchShape : Shape) {d c T : } (spatial : Tensor [d]) (schedule : Schedule T) (x0 eps : Tensor Float (sampleShape batchShape c spatial)) (step : ) :
                                                  Sample.Supervised Float (sampleShape batchShape (c + 1) spatial) (sampleShape batchShape c spatial)

                                                  Build an epsilon-prediction training sample from explicit noise.

                                                  The caller supplies eps, usually from the runtime RNG. Keeping randomness outside this helper makes the transformation reusable:

                                                  $x_t=\sqrt{\bar{\alpha}_t}\,x_0+\sqrt{1-\bar{\alpha}_t}\,\varepsilon$, with target $\varepsilon$.

                                                  Instances For
                                                    def TorchLean.diffusion.noisedSample (batchShape : Shape) {d c T : } (spatial : Tensor [d]) (schedule : Schedule T) (x0 : Tensor Float (sampleShape batchShape c spatial)) (seed step : ) :
                                                    Sample.Supervised Float (sampleShape batchShape (c + 1) spatial) (sampleShape batchShape c spatial)

                                                    Build a deterministic epsilon-prediction training sample.

                                                    This is the common DDPM training step used by examples: draw reproducible Gaussian noise from (seed, step), corrupt $x_0$, and use that same noise as the target.

                                                    Instances For
                                                      def TorchLean.diffusion.ddimPrev {shape : Shape} (abPrev ab : Float) (x_t epsHat : Tensor Float shape) :

                                                      One deterministic DDIM reverse update ($\eta=0$).

                                                      Given $x_t$, predicted epsilon, and adjacent schedule values, this estimates $x_0$ and remixes it to the previous timestep.

                                                      We clamp the intermediate $x_0$ estimate to the training image range $[-1,1]$. This is the standard "clipped denoised" stabilizer used by many DDPM/DDIM samplers: without it, a compact model can drive one color channel far outside the data range and the final PPM exporter merely clips the damage into saturated color blobs.

                                                      Instances For